1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.os;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.SystemApi;
22 import android.annotation.TestApi;
23 import android.compat.annotation.UnsupportedAppUsage;
24 import android.util.Log;
25 import android.util.MutableInt;
26 
27 import com.android.internal.annotations.GuardedBy;
28 
29 import dalvik.annotation.optimization.CriticalNative;
30 import dalvik.annotation.optimization.FastNative;
31 
32 import libcore.util.HexEncoding;
33 
34 import java.nio.charset.StandardCharsets;
35 import java.security.MessageDigest;
36 import java.security.NoSuchAlgorithmException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.HashMap;
40 
41 /**
42  * Gives access to the system properties store.  The system properties
43  * store contains a list of string key-value pairs.
44  *
45  * <p>Use this class only for the system properties that are local. e.g., within
46  * an app, a partition, or a module. For system properties used across the
47  * boundaries, formally define them in <code>*.sysprop</code> files and use the
48  * auto-generated methods. For more information, see <a href=
49  * "https://source.android.com/devices/architecture/sysprops-apis">Implementing
50  * System Properties as APIs</a>.</p>
51  *
52  * {@hide}
53  */
54 @SystemApi
55 @TestApi
56 public class SystemProperties {
57     private static final String TAG = "SystemProperties";
58     private static final boolean TRACK_KEY_ACCESS = false;
59 
60     /**
61      * Android O removed the property name length limit, but com.amazon.kindle 7.8.1.5
62      * uses reflection to read this whenever text is selected (http://b/36095274).
63      * @hide
64      */
65     @UnsupportedAppUsage
66     public static final int PROP_NAME_MAX = Integer.MAX_VALUE;
67 
68     /** @hide */
69     public static final int PROP_VALUE_MAX = 91;
70 
71     @UnsupportedAppUsage
72     @GuardedBy("sChangeCallbacks")
73     private static final ArrayList<Runnable> sChangeCallbacks = new ArrayList<Runnable>();
74 
75     @GuardedBy("sRoReads")
76     private static final HashMap<String, MutableInt> sRoReads =
77             TRACK_KEY_ACCESS ? new HashMap<>() : null;
78 
onKeyAccess(String key)79     private static void onKeyAccess(String key) {
80         if (!TRACK_KEY_ACCESS) return;
81 
82         if (key != null && key.startsWith("ro.")) {
83             synchronized (sRoReads) {
84                 MutableInt numReads = sRoReads.getOrDefault(key, null);
85                 if (numReads == null) {
86                     numReads = new MutableInt(0);
87                     sRoReads.put(key, numReads);
88                 }
89                 numReads.value++;
90                 if (numReads.value > 3) {
91                     Log.d(TAG, "Repeated read (count=" + numReads.value
92                             + ") of a read-only system property '" + key + "'",
93                             new Exception());
94                 }
95             }
96         }
97     }
98 
99     // The one-argument version of native_get used to be a regular native function. Nowadays,
100     // we use the two-argument form of native_get all the time, but we can't just delete the
101     // one-argument overload: apps use it via reflection, as the UnsupportedAppUsage annotation
102     // indicates. Let's just live with having a Java function with a very unusual name.
103     @UnsupportedAppUsage
native_get(String key)104     private static String native_get(String key) {
105         return native_get(key, "");
106     }
107 
108     @FastNative
109     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
native_get(String key, String def)110     private static native String native_get(String key, String def);
111     @FastNative
112     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
native_get_int(String key, int def)113     private static native int native_get_int(String key, int def);
114     @FastNative
115     @UnsupportedAppUsage
native_get_long(String key, long def)116     private static native long native_get_long(String key, long def);
117     @FastNative
118     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
native_get_boolean(String key, boolean def)119     private static native boolean native_get_boolean(String key, boolean def);
120 
121     @FastNative
native_find(String name)122     private static native long native_find(String name);
123     @FastNative
native_get(long handle)124     private static native String native_get(long handle);
125     @CriticalNative
native_get_int(long handle, int def)126     private static native int native_get_int(long handle, int def);
127     @CriticalNative
native_get_long(long handle, long def)128     private static native long native_get_long(long handle, long def);
129     @CriticalNative
native_get_boolean(long handle, boolean def)130     private static native boolean native_get_boolean(long handle, boolean def);
131 
132     // _NOT_ FastNative: native_set performs IPC and can block
133     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
native_set(String key, String def)134     private static native void native_set(String key, String def);
135 
136     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
native_add_change_callback()137     private static native void native_add_change_callback();
native_report_sysprop_change()138     private static native void native_report_sysprop_change();
139 
140     /**
141      * Get the String value for the given {@code key}.
142      *
143      * @param key the key to lookup
144      * @return an empty string if the {@code key} isn't found
145      * @hide
146      */
147     @NonNull
148     @SystemApi
149     @TestApi
get(@onNull String key)150     public static String get(@NonNull String key) {
151         if (TRACK_KEY_ACCESS) onKeyAccess(key);
152         return native_get(key);
153     }
154 
155     /**
156      * Get the String value for the given {@code key}.
157      *
158      * @param key the key to lookup
159      * @param def the default value in case the property is not set or empty
160      * @return if the {@code key} isn't found, return {@code def} if it isn't null, or an empty
161      * string otherwise
162      * @hide
163      */
164     @NonNull
165     @SystemApi
166     @TestApi
get(@onNull String key, @Nullable String def)167     public static String get(@NonNull String key, @Nullable String def) {
168         if (TRACK_KEY_ACCESS) onKeyAccess(key);
169         return native_get(key, def);
170     }
171 
172     /**
173      * Get the value for the given {@code key}, and return as an integer.
174      *
175      * @param key the key to lookup
176      * @param def a default value to return
177      * @return the key parsed as an integer, or def if the key isn't found or
178      *         cannot be parsed
179      * @hide
180      */
181     @SystemApi
getInt(@onNull String key, int def)182     public static int getInt(@NonNull String key, int def) {
183         if (TRACK_KEY_ACCESS) onKeyAccess(key);
184         return native_get_int(key, def);
185     }
186 
187     /**
188      * Get the value for the given {@code key}, and return as a long.
189      *
190      * @param key the key to lookup
191      * @param def a default value to return
192      * @return the key parsed as a long, or def if the key isn't found or
193      *         cannot be parsed
194      * @hide
195      */
196     @SystemApi
getLong(@onNull String key, long def)197     public static long getLong(@NonNull String key, long def) {
198         if (TRACK_KEY_ACCESS) onKeyAccess(key);
199         return native_get_long(key, def);
200     }
201 
202     /**
203      * Get the value for the given {@code key}, returned as a boolean.
204      * Values 'n', 'no', '0', 'false' or 'off' are considered false.
205      * Values 'y', 'yes', '1', 'true' or 'on' are considered true.
206      * (case sensitive).
207      * If the key does not exist, or has any other value, then the default
208      * result is returned.
209      *
210      * @param key the key to lookup
211      * @param def a default value to return
212      * @return the key parsed as a boolean, or def if the key isn't found or is
213      *         not able to be parsed as a boolean.
214      * @hide
215      */
216     @SystemApi
217     @TestApi
getBoolean(@onNull String key, boolean def)218     public static boolean getBoolean(@NonNull String key, boolean def) {
219         if (TRACK_KEY_ACCESS) onKeyAccess(key);
220         return native_get_boolean(key, def);
221     }
222 
223     /**
224      * Set the value for the given {@code key} to {@code val}.
225      *
226      * @throws IllegalArgumentException if the {@code val} exceeds 91 characters
227      * @throws RuntimeException if the property cannot be set, for example, if it was blocked by
228      * SELinux. libc will log the underlying reason.
229      * @hide
230      */
231     @UnsupportedAppUsage
set(@onNull String key, @Nullable String val)232     public static void set(@NonNull String key, @Nullable String val) {
233         if (val != null && !val.startsWith("ro.") && val.length() > PROP_VALUE_MAX) {
234             throw new IllegalArgumentException("value of system property '" + key
235                     + "' is longer than " + PROP_VALUE_MAX + " characters: " + val);
236         }
237         if (TRACK_KEY_ACCESS) onKeyAccess(key);
238         native_set(key, val);
239     }
240 
241     /**
242      * Add a callback that will be run whenever any system property changes.
243      *
244      * @param callback The {@link Runnable} that should be executed when a system property
245      * changes.
246      * @hide
247      */
248     @UnsupportedAppUsage
addChangeCallback(@onNull Runnable callback)249     public static void addChangeCallback(@NonNull Runnable callback) {
250         synchronized (sChangeCallbacks) {
251             if (sChangeCallbacks.size() == 0) {
252                 native_add_change_callback();
253             }
254             sChangeCallbacks.add(callback);
255         }
256     }
257 
258     @SuppressWarnings("unused")  // Called from native code.
callChangeCallbacks()259     private static void callChangeCallbacks() {
260         ArrayList<Runnable> callbacks = null;
261         synchronized (sChangeCallbacks) {
262             //Log.i("foo", "Calling " + sChangeCallbacks.size() + " change callbacks!");
263             if (sChangeCallbacks.size() == 0) {
264                 return;
265             }
266             callbacks = new ArrayList<Runnable>(sChangeCallbacks);
267         }
268         final long token = Binder.clearCallingIdentity();
269         try {
270             for (int i = 0; i < callbacks.size(); i++) {
271                 try {
272                     callbacks.get(i).run();
273                 } catch (Throwable t) {
274                     // Ignore and try to go on. Don't use wtf here: that
275                     // will cause the process to exit on some builds and break tests.
276                     Log.e(TAG, "Exception in SystemProperties change callback", t);
277                 }
278             }
279         } finally {
280             Binder.restoreCallingIdentity(token);
281         }
282     }
283 
284     /**
285      * Notifies listeners that a system property has changed
286      * @hide
287      */
288     @UnsupportedAppUsage
reportSyspropChanged()289     public static void reportSyspropChanged() {
290         native_report_sysprop_change();
291     }
292 
293     /**
294      * Return a {@code SHA-1} digest of the given keys and their values as a
295      * hex-encoded string. The ordering of the incoming keys doesn't change the
296      * digest result.
297      *
298      * @hide
299      */
digestOf(@onNull String... keys)300     public static @NonNull String digestOf(@NonNull String... keys) {
301         Arrays.sort(keys);
302         try {
303             final MessageDigest digest = MessageDigest.getInstance("SHA-1");
304             for (String key : keys) {
305                 final String item = key + "=" + get(key) + "\n";
306                 digest.update(item.getBytes(StandardCharsets.UTF_8));
307             }
308             return HexEncoding.encodeToString(digest.digest()).toLowerCase();
309         } catch (NoSuchAlgorithmException e) {
310             throw new RuntimeException(e);
311         }
312     }
313 
314     @UnsupportedAppUsage
SystemProperties()315     private SystemProperties() {
316     }
317 
318     /**
319      * Look up a property location by name.
320      * @name name of the property
321      * @return property handle or {@code null} if property isn't set
322      * @hide
323      */
find(@onNull String name)324     @Nullable public static Handle find(@NonNull String name) {
325         long nativeHandle = native_find(name);
326         if (nativeHandle == 0) {
327             return null;
328         }
329         return new Handle(nativeHandle);
330     }
331 
332     /**
333      * Handle to a pre-located property. Looking up a property handle in advance allows
334      * for optimal repeated lookup of a single property.
335      * @hide
336      */
337     public static final class Handle {
338 
339         private final long mNativeHandle;
340 
341         /**
342          * @return Value of the property
343          */
get()344         @NonNull public String get() {
345             return native_get(mNativeHandle);
346         }
347         /**
348          * @param def default value
349          * @return value or {@code def} on parse error
350          */
getInt(int def)351         public int getInt(int def) {
352             return native_get_int(mNativeHandle, def);
353         }
354         /**
355          * @param def default value
356          * @return value or {@code def} on parse error
357          */
getLong(long def)358         public long getLong(long def) {
359             return native_get_long(mNativeHandle, def);
360         }
361         /**
362          * @param def default value
363          * @return value or {@code def} on parse error
364          */
getBoolean(boolean def)365         public boolean getBoolean(boolean def) {
366             return native_get_boolean(mNativeHandle, def);
367         }
368 
Handle(long nativeHandle)369         private Handle(long nativeHandle) {
370             mNativeHandle = nativeHandle;
371         }
372     }
373 }
374