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
182     @TestApi
getInt(@onNull String key, int def)183     public static int getInt(@NonNull String key, int def) {
184         if (TRACK_KEY_ACCESS) onKeyAccess(key);
185         return native_get_int(key, def);
186     }
187 
188     /**
189      * Get the value for the given {@code key}, and return as a long.
190      *
191      * @param key the key to lookup
192      * @param def a default value to return
193      * @return the key parsed as a long, or def if the key isn't found or
194      *         cannot be parsed
195      * @hide
196      */
197     @SystemApi
198     @TestApi
getLong(@onNull String key, long def)199     public static long getLong(@NonNull String key, long def) {
200         if (TRACK_KEY_ACCESS) onKeyAccess(key);
201         return native_get_long(key, def);
202     }
203 
204     /**
205      * Get the value for the given {@code key}, returned as a boolean.
206      * Values 'n', 'no', '0', 'false' or 'off' are considered false.
207      * Values 'y', 'yes', '1', 'true' or 'on' are considered true.
208      * (case sensitive).
209      * If the key does not exist, or has any other value, then the default
210      * result is returned.
211      *
212      * @param key the key to lookup
213      * @param def a default value to return
214      * @return the key parsed as a boolean, or def if the key isn't found or is
215      *         not able to be parsed as a boolean.
216      * @hide
217      */
218     @SystemApi
219     @TestApi
getBoolean(@onNull String key, boolean def)220     public static boolean getBoolean(@NonNull String key, boolean def) {
221         if (TRACK_KEY_ACCESS) onKeyAccess(key);
222         return native_get_boolean(key, def);
223     }
224 
225     /**
226      * Set the value for the given {@code key} to {@code val}.
227      *
228      * @throws IllegalArgumentException if the {@code val} exceeds 91 characters
229      * @throws RuntimeException if the property cannot be set, for example, if it was blocked by
230      * SELinux. libc will log the underlying reason.
231      * @hide
232      */
233     @UnsupportedAppUsage
set(@onNull String key, @Nullable String val)234     public static void set(@NonNull String key, @Nullable String val) {
235         if (val != null && !val.startsWith("ro.") && val.length() > PROP_VALUE_MAX) {
236             throw new IllegalArgumentException("value of system property '" + key
237                     + "' is longer than " + PROP_VALUE_MAX + " characters: " + val);
238         }
239         if (TRACK_KEY_ACCESS) onKeyAccess(key);
240         native_set(key, val);
241     }
242 
243     /**
244      * Add a callback that will be run whenever any system property changes.
245      *
246      * @param callback The {@link Runnable} that should be executed when a system property
247      * changes.
248      * @hide
249      */
250     @UnsupportedAppUsage
addChangeCallback(@onNull Runnable callback)251     public static void addChangeCallback(@NonNull Runnable callback) {
252         synchronized (sChangeCallbacks) {
253             if (sChangeCallbacks.size() == 0) {
254                 native_add_change_callback();
255             }
256             sChangeCallbacks.add(callback);
257         }
258     }
259 
260     /**
261      * Remove the target callback.
262      *
263      * @param callback The {@link Runnable} that should be removed.
264      * @hide
265      */
266     @UnsupportedAppUsage
removeChangeCallback(@onNull Runnable callback)267     public static void removeChangeCallback(@NonNull Runnable callback) {
268         synchronized (sChangeCallbacks) {
269             if (sChangeCallbacks.contains(callback)) {
270                 sChangeCallbacks.remove(callback);
271             }
272         }
273     }
274 
275     @SuppressWarnings("unused")  // Called from native code.
callChangeCallbacks()276     private static void callChangeCallbacks() {
277         ArrayList<Runnable> callbacks = null;
278         synchronized (sChangeCallbacks) {
279             //Log.i("foo", "Calling " + sChangeCallbacks.size() + " change callbacks!");
280             if (sChangeCallbacks.size() == 0) {
281                 return;
282             }
283             callbacks = new ArrayList<Runnable>(sChangeCallbacks);
284         }
285         final long token = Binder.clearCallingIdentity();
286         try {
287             for (int i = 0; i < callbacks.size(); i++) {
288                 try {
289                     callbacks.get(i).run();
290                 } catch (Throwable t) {
291                     // Ignore and try to go on. Don't use wtf here: that
292                     // will cause the process to exit on some builds and break tests.
293                     Log.e(TAG, "Exception in SystemProperties change callback", t);
294                 }
295             }
296         } finally {
297             Binder.restoreCallingIdentity(token);
298         }
299     }
300 
301     /**
302      * Notifies listeners that a system property has changed
303      * @hide
304      */
305     @UnsupportedAppUsage
reportSyspropChanged()306     public static void reportSyspropChanged() {
307         native_report_sysprop_change();
308     }
309 
310     /**
311      * Return a {@code SHA-1} digest of the given keys and their values as a
312      * hex-encoded string. The ordering of the incoming keys doesn't change the
313      * digest result.
314      *
315      * @hide
316      */
digestOf(@onNull String... keys)317     public static @NonNull String digestOf(@NonNull String... keys) {
318         Arrays.sort(keys);
319         try {
320             final MessageDigest digest = MessageDigest.getInstance("SHA-1");
321             for (String key : keys) {
322                 final String item = key + "=" + get(key) + "\n";
323                 digest.update(item.getBytes(StandardCharsets.UTF_8));
324             }
325             return HexEncoding.encodeToString(digest.digest()).toLowerCase();
326         } catch (NoSuchAlgorithmException e) {
327             throw new RuntimeException(e);
328         }
329     }
330 
331     @UnsupportedAppUsage
SystemProperties()332     private SystemProperties() {
333     }
334 
335     /**
336      * Look up a property location by name.
337      * @name name of the property
338      * @return property handle or {@code null} if property isn't set
339      * @hide
340      */
find(@onNull String name)341     @Nullable public static Handle find(@NonNull String name) {
342         long nativeHandle = native_find(name);
343         if (nativeHandle == 0) {
344             return null;
345         }
346         return new Handle(nativeHandle);
347     }
348 
349     /**
350      * Handle to a pre-located property. Looking up a property handle in advance allows
351      * for optimal repeated lookup of a single property.
352      * @hide
353      */
354     public static final class Handle {
355 
356         private final long mNativeHandle;
357 
358         /**
359          * @return Value of the property
360          */
get()361         @NonNull public String get() {
362             return native_get(mNativeHandle);
363         }
364         /**
365          * @param def default value
366          * @return value or {@code def} on parse error
367          */
getInt(int def)368         public int getInt(int def) {
369             return native_get_int(mNativeHandle, def);
370         }
371         /**
372          * @param def default value
373          * @return value or {@code def} on parse error
374          */
getLong(long def)375         public long getLong(long def) {
376             return native_get_long(mNativeHandle, def);
377         }
378         /**
379          * @param def default value
380          * @return value or {@code def} on parse error
381          */
getBoolean(boolean def)382         public boolean getBoolean(boolean def) {
383             return native_get_boolean(mNativeHandle, def);
384         }
385 
Handle(long nativeHandle)386         private Handle(long nativeHandle) {
387             mNativeHandle = nativeHandle;
388         }
389     }
390 }
391