2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.providers.settings;
19 import android.Manifest;
20 import android.app.ActivityManager;
21 import android.app.AppGlobals;
22 import android.app.backup.BackupManager;
23 import android.content.BroadcastReceiver;
24 import android.content.ComponentName;
25 import android.content.ContentProvider;
26 import android.content.ContentValues;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.pm.ApplicationInfo;
31 import android.content.pm.IPackageManager;
32 import android.content.pm.PackageInfo;
33 import android.content.pm.PackageManager;
34 import android.content.pm.UserInfo;
35 import android.database.Cursor;
36 import android.database.MatrixCursor;
37 import android.database.sqlite.SQLiteDatabase;
38 import android.database.sqlite.SQLiteQueryBuilder;
39 import android.hardware.camera2.utils.ArrayUtils;
40 import android.media.AudioManager;
41 import android.net.Uri;
42 import android.os.Binder;
43 import android.os.Build;
44 import android.os.Bundle;
45 import android.os.Debug;
46 import android.os.DropBoxManager;
47 import android.os.Environment;
48 import android.os.Handler;
49 import android.os.Looper;
50 import android.os.Message;
51 import android.os.ParcelFileDescriptor;
52 import android.os.Process;
53 import android.os.RemoteException;
54 import android.os.SELinux;
55 import android.os.UserHandle;
56 import android.os.UserManager;
57 import android.os.UserManagerInternal;
58 import android.provider.Settings;
59 import android.text.TextUtils;
60 import android.util.ArraySet;
61 import android.util.Slog;
62 import android.util.SparseArray;
64 import com.android.internal.annotations.GuardedBy;
65 import com.android.internal.content.PackageMonitor;
66 import com.android.internal.os.BackgroundThread;
67 import com.android.providers.settings.SettingsState.Setting;
68 import com.android.server.LocalServices;
69 import com.android.server.SystemConfig;
72 import java.io.FileDescriptor;
73 import java.io.FileNotFoundException;
74 import java.io.PrintWriter;
75 import java.security.SecureRandom;
76 import java.util.Arrays;
77 import java.util.List;
79 import java.util.regex.Pattern;
83 * This class is a content provider that publishes the system settings.
84 * It can be accessed via the content provider APIs or via custom call
85 * commands. The latter is a bit faster and is the preferred way to access
86 * the platform settings.
89 * There are three settings types, global (with signature level protection
90 * and shared across users), secure (with signature permission level
91 * protection and per user), and system (with dangerous permission level
92 * protection and per user). Global settings are stored under the device owner.
93 * Each of these settings is represented by a {@link
94 * com.android.providers.settings.SettingsState} object mapped to an integer
95 * key derived from the setting type in the most significant bits and user
96 * id in the least significant bits. Settings are synchronously loaded on
97 * instantiation of a SettingsState and asynchronously persisted on mutation.
98 * Settings are stored in the user specific system directory.
101 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
102 * and get a warning. Targeting higher API version prohibits this as the
103 * system settings are not a place for apps to save their state. When a package
104 * is removed the settings it added are deleted. Apps cannot delete system
105 * settings added by the platform. System settings values are validated to
106 * ensure the clients do not put bad values. Global and secure settings are
107 * changed only by trusted parties, therefore no validation is performed. Also
108 * there is a limit on the amount of app specific settings that can be added
109 * to prevent unlimited growth of the system process memory footprint.
112 @SuppressWarnings("deprecation")
113 public class SettingsProvider extends ContentProvider {
114 private static final boolean DEBUG = false;
116 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
118 private static final String LOG_TAG = "SettingsProvider";
120 private static final String TABLE_SYSTEM = "system";
121 private static final String TABLE_SECURE = "secure";
122 private static final String TABLE_GLOBAL = "global";
124 // Old tables no longer exist.
125 private static final String TABLE_FAVORITES = "favorites";
126 private static final String TABLE_OLD_FAVORITES = "old_favorites";
127 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
128 private static final String TABLE_BOOKMARKS = "bookmarks";
129 private static final String TABLE_ANDROID_METADATA = "android_metadata";
131 // The set of removed legacy tables.
132 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
134 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
135 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
136 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
137 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
138 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
141 private static final int MUTATION_OPERATION_INSERT = 1;
142 private static final int MUTATION_OPERATION_DELETE = 2;
143 private static final int MUTATION_OPERATION_UPDATE = 3;
145 private static final String[] ALL_COLUMNS = new String[] {
146 Settings.NameValueTable._ID,
147 Settings.NameValueTable.NAME,
148 Settings.NameValueTable.VALUE
151 public static final int SETTINGS_TYPE_GLOBAL = 0;
152 public static final int SETTINGS_TYPE_SYSTEM = 1;
153 public static final int SETTINGS_TYPE_SECURE = 2;
155 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
156 public static final int SETTINGS_TYPE_SHIFT = 28;
158 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
159 Settings.NameValueTable.VALUE, null);
161 // Per user secure settings that moved to the for all users global settings.
162 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
164 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
167 // Per user system settings that moved to the for all users global settings.
168 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
170 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
173 // Per user system settings that moved to the per user secure settings.
174 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
176 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
179 // Per all users global settings that moved to the per user secure settings.
180 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
182 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
185 // Per user secure settings that are cloned for the managed profiles of the user.
186 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
188 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
191 // Per user system settings that are cloned for the managed profiles of the user.
192 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
194 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
197 private final Object mLock = new Object();
200 private SettingsRegistry mSettingsRegistry;
202 // We have to call in the user manager with no lock held,
203 private volatile UserManager mUserManager;
205 // We have to call in the package manager with no lock held,
206 private volatile IPackageManager mPackageManager;
208 public static int makeKey(int type, int userId) {
209 return (type << SETTINGS_TYPE_SHIFT) | userId;
212 public static int getTypeFromKey(int key) {
213 return key >>> SETTINGS_TYPE_SHIFT;
216 public static int getUserIdFromKey(int key) {
217 return key & ~SETTINGS_TYPE_MASK;
220 public static String settingTypeToString(int type) {
222 case SETTINGS_TYPE_GLOBAL: {
223 return "SETTINGS_GLOBAL";
225 case SETTINGS_TYPE_SECURE: {
226 return "SETTINGS_SECURE";
228 case SETTINGS_TYPE_SYSTEM: {
229 return "SETTINGS_SYSTEM";
237 public static String keyToString(int key) {
238 return "Key[user=" + getUserIdFromKey(key) + ";type="
239 + settingTypeToString(getTypeFromKey(key)) + "]";
243 public boolean onCreate() {
244 synchronized (mLock) {
245 mUserManager = UserManager.get(getContext());
246 mPackageManager = AppGlobals.getPackageManager();
247 mSettingsRegistry = new SettingsRegistry();
249 registerBroadcastReceivers();
250 startWatchingUserRestrictionChanges();
255 public Bundle call(String method, String name, Bundle args) {
256 final int requestingUserId = getRequestingUserId(args);
258 case Settings.CALL_METHOD_GET_GLOBAL: {
259 Setting setting = getGlobalSetting(name);
260 return packageValueForCallResult(setting, isTrackingGeneration(args));
263 case Settings.CALL_METHOD_GET_SECURE: {
264 Setting setting = getSecureSetting(name, requestingUserId);
265 return packageValueForCallResult(setting, isTrackingGeneration(args));
268 case Settings.CALL_METHOD_GET_SYSTEM: {
269 Setting setting = getSystemSetting(name, requestingUserId);
270 return packageValueForCallResult(setting, isTrackingGeneration(args));
273 case Settings.CALL_METHOD_PUT_GLOBAL: {
274 String value = getSettingValue(args);
275 insertGlobalSetting(name, value, requestingUserId, false);
279 case Settings.CALL_METHOD_PUT_SECURE: {
280 String value = getSettingValue(args);
281 insertSecureSetting(name, value, requestingUserId, false);
285 case Settings.CALL_METHOD_PUT_SYSTEM: {
286 String value = getSettingValue(args);
287 insertSystemSetting(name, value, requestingUserId);
292 Slog.w(LOG_TAG, "call() with invalid method: " + method);
300 public String getType(Uri uri) {
301 Arguments args = new Arguments(uri, null, null, true);
302 if (TextUtils.isEmpty(args.name)) {
303 return "vnd.android.cursor.dir/" + args.table;
305 return "vnd.android.cursor.item/" + args.table;
310 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
313 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
316 Arguments args = new Arguments(uri, where, whereArgs, true);
317 String[] normalizedProjection = normalizeProjection(projection);
319 // If a legacy table that is gone, done.
320 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
321 return new MatrixCursor(normalizedProjection, 0);
324 switch (args.table) {
326 if (args.name != null) {
327 Setting setting = getGlobalSetting(args.name);
328 return packageSettingForQuery(setting, normalizedProjection);
330 return getAllGlobalSettings(projection);
335 final int userId = UserHandle.getCallingUserId();
336 if (args.name != null) {
337 Setting setting = getSecureSetting(args.name, userId);
338 return packageSettingForQuery(setting, normalizedProjection);
340 return getAllSecureSettings(userId, projection);
345 final int userId = UserHandle.getCallingUserId();
346 if (args.name != null) {
347 Setting setting = getSystemSetting(args.name, userId);
348 return packageSettingForQuery(setting, normalizedProjection);
350 return getAllSystemSettings(userId, projection);
355 throw new IllegalArgumentException("Invalid Uri path:" + uri);
361 public Uri insert(Uri uri, ContentValues values) {
363 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
366 String table = getValidTableOrThrow(uri);
368 // If a legacy table that is gone, done.
369 if (REMOVED_LEGACY_TABLES.contains(table)) {
373 String name = values.getAsString(Settings.Secure.NAME);
374 if (!isKeyValid(name)) {
378 String value = values.getAsString(Settings.Secure.VALUE);
382 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
383 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
388 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
389 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
394 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
395 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
400 throw new IllegalArgumentException("Bad Uri path:" + uri);
408 public int bulkInsert(Uri uri, ContentValues[] allValues) {
410 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
413 int insertionCount = 0;
414 final int valuesCount = allValues.length;
415 for (int i = 0; i < valuesCount; i++) {
416 ContentValues values = allValues[i];
417 if (insert(uri, values) != null) {
422 return insertionCount;
426 public int delete(Uri uri, String where, String[] whereArgs) {
428 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
431 Arguments args = new Arguments(uri, where, whereArgs, false);
433 // If a legacy table that is gone, done.
434 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
438 if (!isKeyValid(args.name)) {
442 switch (args.table) {
444 final int userId = UserHandle.getCallingUserId();
445 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
449 final int userId = UserHandle.getCallingUserId();
450 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
454 final int userId = UserHandle.getCallingUserId();
455 return deleteSystemSetting(args.name, userId) ? 1 : 0;
459 throw new IllegalArgumentException("Bad Uri path:" + uri);
465 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
467 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
470 Arguments args = new Arguments(uri, where, whereArgs, false);
472 // If a legacy table that is gone, done.
473 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
477 String name = values.getAsString(Settings.Secure.NAME);
478 if (!isKeyValid(name)) {
481 String value = values.getAsString(Settings.Secure.VALUE);
483 switch (args.table) {
485 final int userId = UserHandle.getCallingUserId();
486 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
490 final int userId = UserHandle.getCallingUserId();
491 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
495 final int userId = UserHandle.getCallingUserId();
496 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
500 throw new IllegalArgumentException("Invalid Uri path:" + uri);
506 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
507 final String cacheName;
508 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
509 cacheName = Settings.System.RINGTONE_CACHE;
510 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
511 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
512 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
513 cacheName = Settings.System.ALARM_ALERT_CACHE;
515 throw new FileNotFoundException("Direct file access no longer supported; "
516 + "ringtone playback is available through android.media.Ringtone");
519 final File cacheFile = new File(
520 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
521 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
524 private File getRingtoneCacheDir(int userId) {
525 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
527 SELinux.restorecon(cacheDir);
532 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
533 synchronized (mLock) {
534 final long identity = Binder.clearCallingIdentity();
536 List<UserInfo> users = mUserManager.getUsers(true);
537 final int userCount = users.size();
538 for (int i = 0; i < userCount; i++) {
539 UserInfo user = users.get(i);
540 dumpForUser(user.id, pw);
543 Binder.restoreCallingIdentity(identity);
548 private void dumpForUser(int userId, PrintWriter pw) {
549 if (userId == UserHandle.USER_SYSTEM) {
550 pw.println("GLOBAL SETTINGS (user " + userId + ")");
551 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
552 dumpSettings(globalCursor, pw);
556 pw.println("SECURE SETTINGS (user " + userId + ")");
557 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
558 dumpSettings(secureCursor, pw);
561 pw.println("SYSTEM SETTINGS (user " + userId + ")");
562 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
563 dumpSettings(systemCursor, pw);
567 private void dumpSettings(Cursor cursor, PrintWriter pw) {
568 if (cursor == null || !cursor.moveToFirst()) {
572 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
573 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
574 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
577 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
578 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
579 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
581 } while (cursor.moveToNext());
584 private static String toDumpString(String s) {
591 private void registerBroadcastReceivers() {
592 IntentFilter userFilter = new IntentFilter();
593 userFilter.addAction(Intent.ACTION_USER_REMOVED);
594 userFilter.addAction(Intent.ACTION_USER_STOPPED);
596 getContext().registerReceiver(new BroadcastReceiver() {
598 public void onReceive(Context context, Intent intent) {
599 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
600 UserHandle.USER_SYSTEM);
602 switch (intent.getAction()) {
603 case Intent.ACTION_USER_REMOVED: {
604 synchronized (mLock) {
605 mSettingsRegistry.removeUserStateLocked(userId, true);
609 case Intent.ACTION_USER_STOPPED: {
610 synchronized (mLock) {
611 mSettingsRegistry.removeUserStateLocked(userId, false);
618 PackageMonitor monitor = new PackageMonitor() {
620 public void onPackageRemoved(String packageName, int uid) {
621 synchronized (mLock) {
622 mSettingsRegistry.onPackageRemovedLocked(packageName,
623 UserHandle.getUserId(uid));
629 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
630 UserHandle.ALL, true);
633 private void startWatchingUserRestrictionChanges() {
634 // TODO: The current design of settings looking different based on user restrictions
635 // should be reworked to keep them separate and system code should check the setting
636 // first followed by checking the user restriction before performing an operation.
637 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
638 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
639 Bundle prevRestrictions) -> {
640 // We are changing the settings affected by restrictions to their current
641 // value with a forced update to ensure that all cross profile dependencies
642 // are taken into account. Also make sure the settings update to.. the same
643 // value passes the security checks, so clear binder calling id.
644 if (newRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)
645 != prevRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)) {
646 final long identity = Binder.clearCallingIdentity();
648 synchronized (mLock) {
649 Setting setting = getSecureSetting(
650 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
651 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
652 setting != null ? setting.getValue() : null, userId, true);
655 Binder.restoreCallingIdentity(identity);
658 if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
659 != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
660 final long identity = Binder.clearCallingIdentity();
662 synchronized (mLock) {
663 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
664 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
665 setting != null ? setting.getValue() : null, userId, true);
668 Binder.restoreCallingIdentity(identity);
671 if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
672 != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
673 final long identity = Binder.clearCallingIdentity();
675 synchronized (mLock) {
676 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
677 updateGlobalSetting(Settings.Global.ADB_ENABLED,
678 setting != null ? setting.getValue() : null, userId, true);
681 Binder.restoreCallingIdentity(identity);
684 if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
685 != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
686 final long identity = Binder.clearCallingIdentity();
688 synchronized (mLock) {
689 Setting enable = getGlobalSetting(
690 Settings.Global.PACKAGE_VERIFIER_ENABLE);
691 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
692 enable != null ? enable.getValue() : null, userId, true);
693 Setting include = getGlobalSetting(
694 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
695 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
696 include != null ? include.getValue() : null, userId, true);
699 Binder.restoreCallingIdentity(identity);
702 if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
703 != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
704 final long identity = Binder.clearCallingIdentity();
706 synchronized (mLock) {
707 Setting setting = getGlobalSetting(
708 Settings.Global.PREFERRED_NETWORK_MODE);
709 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
710 setting != null ? setting.getValue() : null, userId, true);
713 Binder.restoreCallingIdentity(identity);
719 private Cursor getAllGlobalSettings(String[] projection) {
721 Slog.v(LOG_TAG, "getAllGlobalSettings()");
724 synchronized (mLock) {
726 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
727 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
729 List<String> names = settingsState.getSettingNamesLocked();
731 final int nameCount = names.size();
733 String[] normalizedProjection = normalizeProjection(projection);
734 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
736 // Anyone can get the global settings, so no security checks.
737 for (int i = 0; i < nameCount; i++) {
738 String name = names.get(i);
739 Setting setting = settingsState.getSettingLocked(name);
740 appendSettingToCursor(result, setting);
747 private Setting getGlobalSetting(String name) {
749 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
753 synchronized (mLock) {
754 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
755 UserHandle.USER_SYSTEM, name);
759 private boolean updateGlobalSetting(String name, String value, int requestingUserId,
760 boolean forceNotify) {
762 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
764 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
768 private boolean insertGlobalSetting(String name, String value, int requestingUserId,
769 boolean forceNotify) {
771 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
773 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
777 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
779 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
781 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
785 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
786 int operation, boolean forceNotify) {
787 // Make sure the caller can change the settings - treated as secure.
788 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
790 // Resolve the userId on whose behalf the call is made.
791 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
793 // If this is a setting that is currently restricted for this user, do not allow
794 // unrestricting changes.
795 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
799 // Perform the mutation.
800 synchronized (mLock) {
802 case MUTATION_OPERATION_INSERT: {
803 return mSettingsRegistry
804 .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
805 name, value, getCallingPackage(), forceNotify);
808 case MUTATION_OPERATION_DELETE: {
809 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
810 UserHandle.USER_SYSTEM, name, forceNotify);
813 case MUTATION_OPERATION_UPDATE: {
814 return mSettingsRegistry
815 .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
816 name, value, getCallingPackage(), forceNotify);
824 private Cursor getAllSecureSettings(int userId, String[] projection) {
826 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
829 // Resolve the userId on whose behalf the call is made.
830 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
832 synchronized (mLock) {
833 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
834 SETTINGS_TYPE_SECURE, callingUserId);
836 final int nameCount = names.size();
838 String[] normalizedProjection = normalizeProjection(projection);
839 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
841 for (int i = 0; i < nameCount; i++) {
842 String name = names.get(i);
843 // Determine the owning user as some profile settings are cloned from the parent.
844 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
847 // Special case for location (sigh).
848 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
852 Setting setting = mSettingsRegistry.getSettingLocked(
853 SETTINGS_TYPE_SECURE, owningUserId, name);
854 appendSettingToCursor(result, setting);
861 private Setting getSecureSetting(String name, int requestingUserId) {
863 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
866 // Resolve the userId on whose behalf the call is made.
867 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
869 // Determine the owning user as some profile settings are cloned from the parent.
870 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
872 // Special case for location (sigh).
873 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
878 synchronized (mLock) {
879 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
884 private boolean insertSecureSetting(String name, String value, int requestingUserId,
885 boolean forceNotify) {
887 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
888 + requestingUserId + ")");
891 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
895 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
897 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
900 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
904 private boolean updateSecureSetting(String name, String value, int requestingUserId,
905 boolean forceNotify) {
907 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
908 + requestingUserId + ")");
911 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
915 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
916 int operation, boolean forceNotify) {
917 // Make sure the caller can change the settings.
918 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
920 // Resolve the userId on whose behalf the call is made.
921 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
923 // If this is a setting that is currently restricted for this user, do not allow
924 // unrestricting changes.
925 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
929 // Determine the owning user as some profile settings are cloned from the parent.
930 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
932 // Only the owning user can change the setting.
933 if (owningUserId != callingUserId) {
937 // Special cases for location providers (sigh).
938 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
939 return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
943 synchronized (mLock) {
945 case MUTATION_OPERATION_INSERT: {
946 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
947 owningUserId, name, value, getCallingPackage(), forceNotify);
950 case MUTATION_OPERATION_DELETE: {
951 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
952 owningUserId, name, forceNotify);
955 case MUTATION_OPERATION_UPDATE: {
956 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
957 owningUserId, name, value, getCallingPackage(), forceNotify);
965 private Cursor getAllSystemSettings(int userId, String[] projection) {
967 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
970 // Resolve the userId on whose behalf the call is made.
971 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
973 synchronized (mLock) {
974 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
975 SETTINGS_TYPE_SYSTEM, callingUserId);
977 final int nameCount = names.size();
979 String[] normalizedProjection = normalizeProjection(projection);
980 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
982 for (int i = 0; i < nameCount; i++) {
983 String name = names.get(i);
985 // Determine the owning user as some profile settings are cloned from the parent.
986 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
989 Setting setting = mSettingsRegistry.getSettingLocked(
990 SETTINGS_TYPE_SYSTEM, owningUserId, name);
991 appendSettingToCursor(result, setting);
998 private Setting getSystemSetting(String name, int requestingUserId) {
1000 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1003 // Resolve the userId on whose behalf the call is made.
1004 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1006 // Determine the owning user as some profile settings are cloned from the parent.
1007 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1010 synchronized (mLock) {
1011 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
1015 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
1017 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
1018 + requestingUserId + ")");
1021 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
1024 private boolean deleteSystemSetting(String name, int requestingUserId) {
1026 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
1029 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
1032 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
1034 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
1035 + requestingUserId + ")");
1038 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
1041 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
1043 if (!hasWriteSecureSettingsPermission()) {
1044 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1045 // operation is allowed for the calling package through appops.
1046 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1047 Binder.getCallingUid(), getCallingPackage(), true)) {
1052 // Resolve the userId on whose behalf the call is made.
1053 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1055 // Enforce what the calling package can mutate the system settings.
1056 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1058 // Determine the owning user as some profile settings are cloned from the parent.
1059 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1061 // Only the owning user id can change the setting.
1062 if (owningUserId != callingUserId) {
1066 // Invalidate any relevant cache files
1067 String cacheName = null;
1068 if (Settings.System.RINGTONE.equals(name)) {
1069 cacheName = Settings.System.RINGTONE_CACHE;
1070 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1071 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1072 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1073 cacheName = Settings.System.ALARM_ALERT_CACHE;
1075 if (cacheName != null) {
1076 final File cacheFile = new File(
1077 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
1081 // Mutate the value.
1082 synchronized (mLock) {
1083 switch (operation) {
1084 case MUTATION_OPERATION_INSERT: {
1085 validateSystemSettingValue(name, value);
1086 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
1087 owningUserId, name, value, getCallingPackage(), false);
1090 case MUTATION_OPERATION_DELETE: {
1091 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1092 owningUserId, name, false);
1095 case MUTATION_OPERATION_UPDATE: {
1096 validateSystemSettingValue(name, value);
1097 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1098 owningUserId, name, value, getCallingPackage(), false);
1106 private boolean hasWriteSecureSettingsPermission() {
1107 // Write secure settings is a more protected permission. If caller has it we are good.
1108 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1109 == PackageManager.PERMISSION_GRANTED) {
1116 private void validateSystemSettingValue(String name, String value) {
1117 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1118 if (validator != null && !validator.validate(value)) {
1119 throw new IllegalArgumentException("Invalid value: " + value
1120 + " for setting: " + name);
1124 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1126 // Optimization - location providers are restricted only for managed profiles.
1127 if (callingUserId == owningUserId) {
1130 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1131 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1132 new UserHandle(callingUserId))) {
1139 * Checks whether changing a setting to a value is prohibited by the corresponding user
1142 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1143 * Context, int, String, boolean)}, which should be in sync with this method.
1145 * @return true if the change is prohibited, false if the change is allowed.
1147 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
1151 case Settings.Secure.LOCATION_MODE:
1152 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1153 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1154 // here normally, but we still protect it here from a direct provider write.
1155 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1156 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1159 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1160 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1161 // a provider, which should be allowed even if the user restriction is set.
1162 if (value != null && value.startsWith("-")) return false;
1163 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1166 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1167 if ("0".equals(value)) return false;
1168 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1171 case Settings.Global.ADB_ENABLED:
1172 if ("0".equals(value)) return false;
1173 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1176 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1177 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1178 if ("1".equals(value)) return false;
1179 restriction = UserManager.ENSURE_VERIFY_APPS;
1182 case Settings.Global.PREFERRED_NETWORK_MODE:
1183 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1187 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
1188 if ("0".equals(value)) return false;
1189 restriction = UserManager.DISALLOW_DATA_ROAMING;
1195 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
1198 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1199 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1202 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1203 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1206 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1207 final int parentId = getGroupParentLocked(userId);
1208 if (parentId != userId && keys.contains(name)) {
1214 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
1215 String name, int userId) {
1216 // System/root/shell can mutate whatever secure settings they want.
1217 final int callingUid = Binder.getCallingUid();
1218 if (callingUid == android.os.Process.SYSTEM_UID
1219 || callingUid == Process.SHELL_UID
1220 || callingUid == Process.ROOT_UID) {
1224 switch (operation) {
1225 case MUTATION_OPERATION_INSERT:
1227 case MUTATION_OPERATION_UPDATE: {
1228 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1232 // The calling package is already verified.
1233 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
1235 // Privileged apps can do whatever they want.
1236 if ((packageInfo.applicationInfo.privateFlags
1237 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1241 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1242 packageInfo.applicationInfo.targetSdkVersion, name);
1245 case MUTATION_OPERATION_DELETE: {
1246 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1247 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1248 throw new IllegalArgumentException("You cannot delete system defined"
1249 + " secure settings.");
1252 // The calling package is already verified.
1253 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
1255 // Privileged apps can do whatever they want.
1256 if ((packageInfo.applicationInfo.privateFlags &
1257 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1261 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1262 packageInfo.applicationInfo.targetSdkVersion, name);
1267 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
1269 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1270 getCallingPackage(), 0, userId);
1271 if (packageInfo != null) {
1274 } catch (RemoteException e) {
1277 throw new IllegalStateException("Calling package doesn't exist");
1280 private int getGroupParentLocked(int userId) {
1281 // Most frequent use case.
1282 if (userId == UserHandle.USER_SYSTEM) {
1285 // We are in the same process with the user manager and the returned
1286 // user info is a cached instance, so just look up instead of cache.
1287 final long identity = Binder.clearCallingIdentity();
1289 // Just a lookup and not reentrant, so holding a lock is fine.
1290 UserInfo userInfo = mUserManager.getProfileParent(userId);
1291 return (userInfo != null) ? userInfo.id : userId;
1293 Binder.restoreCallingIdentity(identity);
1297 private void enforceWritePermission(String permission) {
1298 if (getContext().checkCallingOrSelfPermission(permission)
1299 != PackageManager.PERMISSION_GRANTED) {
1300 throw new SecurityException("Permission denial: writing to settings requires:"
1306 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1307 * This setting contains a list of the currently enabled location providers.
1308 * But helper functions in android.providers.Settings can enable or disable
1309 * a single provider by using a "+" or "-" prefix before the provider name.
1311 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1312 * is set, the said method will only allow values with the "-" prefix.
1314 * @returns whether the enabled location providers changed.
1316 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1317 boolean forceNotify) {
1318 if (TextUtils.isEmpty(value)) {
1322 final char prefix = value.charAt(0);
1323 if (prefix != '+' && prefix != '-') {
1325 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1326 mSettingsRegistry.notifyForSettingsChange(key,
1327 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1333 value = value.substring(1);
1335 Setting settingValue = getSecureSetting(
1336 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1338 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1340 int index = oldProviders.indexOf(value);
1341 int end = index + value.length();
1343 // check for commas to avoid matching on partial string
1344 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1348 // check for commas to avoid matching on partial string
1349 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1353 String newProviders;
1355 if (prefix == '+' && index < 0) {
1356 // append the provider to the list if not present
1357 if (oldProviders.length() == 0) {
1358 newProviders = value;
1360 newProviders = oldProviders + ',' + value;
1362 } else if (prefix == '-' && index >= 0) {
1363 // remove the provider from the list if present
1364 // remove leading or trailing comma
1367 } else if (end < oldProviders.length()) {
1371 newProviders = oldProviders.substring(0, index);
1372 if (end < oldProviders.length()) {
1373 newProviders += oldProviders.substring(end);
1376 // nothing changed, so no need to update the database
1378 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1379 mSettingsRegistry.notifyForSettingsChange(key,
1380 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1385 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
1386 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1387 getCallingPackage(), forceNotify);
1390 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1391 int targetSdkVersion, String name) {
1392 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1393 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1394 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1395 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1396 + " This will soon become an error.");
1398 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1399 + " This will soon become an error.");
1402 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1403 throw new IllegalArgumentException("You cannot change private secure settings.");
1405 throw new IllegalArgumentException("You cannot keep your settings in"
1406 + " the secure settings.");
1411 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1412 if (requestingUserId == UserHandle.getCallingUserId()) {
1413 return requestingUserId;
1415 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1416 Binder.getCallingUid(), requestingUserId, false, true,
1417 "get/set setting for user", null);
1420 private Bundle packageValueForCallResult(Setting setting,
1421 boolean trackingGeneration) {
1422 if (!trackingGeneration) {
1423 if (setting.isNull()) {
1424 return NULL_SETTING_BUNDLE;
1426 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1428 Bundle result = new Bundle();
1429 result.putString(Settings.NameValueTable.VALUE,
1430 !setting.isNull() ? setting.getValue() : null);
1431 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1435 private static int getRequestingUserId(Bundle args) {
1436 final int callingUserId = UserHandle.getCallingUserId();
1437 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1441 private boolean isTrackingGeneration(Bundle args) {
1442 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1445 private static String getSettingValue(Bundle args) {
1446 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1449 private static String getValidTableOrThrow(Uri uri) {
1450 if (uri.getPathSegments().size() > 0) {
1451 String table = uri.getPathSegments().get(0);
1452 if (DatabaseHelper.isValidTable(table)) {
1455 throw new IllegalArgumentException("Bad root path: " + table);
1457 throw new IllegalArgumentException("Invalid URI:" + uri);
1460 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1461 if (setting.isNull()) {
1462 return new MatrixCursor(projection, 0);
1464 MatrixCursor cursor = new MatrixCursor(projection, 1);
1465 appendSettingToCursor(cursor, setting);
1469 private static String[] normalizeProjection(String[] projection) {
1470 if (projection == null) {
1474 final int columnCount = projection.length;
1475 for (int i = 0; i < columnCount; i++) {
1476 String column = projection[i];
1477 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1478 throw new IllegalArgumentException("Invalid column: " + column);
1485 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1486 if (setting.isNull()) {
1489 final int columnCount = cursor.getColumnCount();
1491 String[] values = new String[columnCount];
1493 for (int i = 0; i < columnCount; i++) {
1494 String column = cursor.getColumnName(i);
1497 case Settings.NameValueTable._ID: {
1498 values[i] = setting.getId();
1501 case Settings.NameValueTable.NAME: {
1502 values[i] = setting.getName();
1505 case Settings.NameValueTable.VALUE: {
1506 values[i] = setting.getValue();
1511 cursor.addRow(values);
1514 private static boolean isKeyValid(String key) {
1515 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1518 private static final class Arguments {
1519 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1520 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1522 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1523 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1525 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1526 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1528 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1529 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1531 public final String table;
1532 public final String name;
1534 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1535 final int segmentSize = uri.getPathSegments().size();
1536 switch (segmentSize) {
1539 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1540 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1541 && whereArgs.length == 1) {
1542 name = whereArgs[0];
1543 table = computeTableForSetting(uri, name);
1545 } else if (where != null
1546 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1547 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1548 final int startIndex = Math.max(where.indexOf("'"),
1549 where.indexOf("\"")) + 1;
1550 final int endIndex = Math.max(where.lastIndexOf("'"),
1551 where.lastIndexOf("\""));
1552 name = where.substring(startIndex, endIndex);
1553 table = computeTableForSetting(uri, name);
1555 } else if (supportAll && where == null && whereArgs == null) {
1557 table = computeTableForSetting(uri, null);
1563 if (where == null && whereArgs == null) {
1564 name = uri.getPathSegments().get(1);
1565 table = computeTableForSetting(uri, name);
1571 EventLogTags.writeUnsupportedSettingsQuery(
1572 uri.toSafeString(), where, Arrays.toString(whereArgs));
1573 String message = String.format( "Supported SQL:\n"
1574 + " uri content://some_table/some_property with null where and where args\n"
1575 + " uri content://some_table with query name=? and single name as arg\n"
1576 + " uri content://some_table with query name=some_name and null args\n"
1577 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1578 Arrays.toString(whereArgs));
1579 throw new IllegalArgumentException(message);
1582 private static String computeTableForSetting(Uri uri, String name) {
1583 String table = getValidTableOrThrow(uri);
1586 if (sSystemMovedToSecureSettings.contains(name)) {
1587 table = TABLE_SECURE;
1590 if (sSystemMovedToGlobalSettings.contains(name)) {
1591 table = TABLE_GLOBAL;
1594 if (sSecureMovedToGlobalSettings.contains(name)) {
1595 table = TABLE_GLOBAL;
1598 if (sGlobalMovedToSecureSettings.contains(name)) {
1599 table = TABLE_SECURE;
1607 final class SettingsRegistry {
1608 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1610 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1611 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1612 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1614 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1616 private GenerationRegistry mGenerationRegistry;
1618 private final Handler mHandler;
1620 private final BackupManager mBackupManager;
1622 public SettingsRegistry() {
1623 mHandler = new MyHandler(getContext().getMainLooper());
1624 mGenerationRegistry = new GenerationRegistry(mLock);
1625 mBackupManager = new BackupManager(getContext());
1626 migrateAllLegacySettingsIfNeeded();
1629 public List<String> getSettingsNamesLocked(int type, int userId) {
1630 final int key = makeKey(type, userId);
1631 SettingsState settingsState = peekSettingsStateLocked(key);
1632 return settingsState.getSettingNamesLocked();
1635 public SettingsState getSettingsLocked(int type, int userId) {
1636 final int key = makeKey(type, userId);
1637 return peekSettingsStateLocked(key);
1640 public void ensureSettingsForUserLocked(int userId) {
1641 // Migrate the setting for this user if needed.
1642 migrateLegacySettingsForUserIfNeededLocked(userId);
1644 // Ensure global settings loaded if owner.
1645 if (userId == UserHandle.USER_SYSTEM) {
1646 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
1647 ensureSettingsStateLocked(globalKey);
1650 // Ensure secure settings loaded.
1651 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1652 ensureSettingsStateLocked(secureKey);
1654 // Make sure the secure settings have an Android id set.
1655 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1656 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1658 // Ensure system settings loaded.
1659 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1660 ensureSettingsStateLocked(systemKey);
1662 // Upgrade the settings to the latest version.
1663 UpgradeController upgrader = new UpgradeController(userId);
1664 upgrader.upgradeIfNeededLocked();
1667 private void ensureSettingsStateLocked(int key) {
1668 if (mSettingsStates.get(key) == null) {
1669 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1670 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1671 maxBytesPerPackage);
1672 mSettingsStates.put(key, settingsState);
1676 public void removeUserStateLocked(int userId, boolean permanently) {
1677 // We always keep the global settings in memory.
1679 // Nuke system settings.
1680 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1681 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1682 if (systemSettingsState != null) {
1684 mSettingsStates.remove(systemKey);
1685 systemSettingsState.destroyLocked(null);
1687 systemSettingsState.destroyLocked(new Runnable() {
1690 mSettingsStates.remove(systemKey);
1696 // Nuke secure settings.
1697 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1698 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1699 if (secureSettingsState != null) {
1701 mSettingsStates.remove(secureKey);
1702 secureSettingsState.destroyLocked(null);
1704 secureSettingsState.destroyLocked(new Runnable() {
1707 mSettingsStates.remove(secureKey);
1713 // Nuke generation tracking data
1714 mGenerationRegistry.onUserRemoved(userId);
1717 public boolean insertSettingLocked(int type, int userId, String name, String value,
1718 String packageName, boolean forceNotify) {
1719 final int key = makeKey(type, userId);
1721 SettingsState settingsState = peekSettingsStateLocked(key);
1722 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1724 if (forceNotify || success) {
1725 notifyForSettingsChange(key, name);
1730 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
1731 final int key = makeKey(type, userId);
1733 SettingsState settingsState = peekSettingsStateLocked(key);
1734 final boolean success = settingsState.deleteSettingLocked(name);
1736 if (forceNotify || success) {
1737 notifyForSettingsChange(key, name);
1742 public Setting getSettingLocked(int type, int userId, String name) {
1743 final int key = makeKey(type, userId);
1745 SettingsState settingsState = peekSettingsStateLocked(key);
1746 return settingsState.getSettingLocked(name);
1749 public boolean updateSettingLocked(int type, int userId, String name, String value,
1750 String packageName, boolean forceNotify) {
1751 final int key = makeKey(type, userId);
1753 SettingsState settingsState = peekSettingsStateLocked(key);
1754 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1756 if (forceNotify || success) {
1757 notifyForSettingsChange(key, name);
1763 public void onPackageRemovedLocked(String packageName, int userId) {
1764 // Global and secure settings are signature protected. Apps signed
1765 // by the platform certificate are generally not uninstalled and
1766 // the main exception is tests. We trust components signed
1767 // by the platform certificate and do not do a clean up after them.
1769 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1770 SettingsState systemSettings = mSettingsStates.get(systemKey);
1771 if (systemSettings != null) {
1772 systemSettings.onPackageRemovedLocked(packageName);
1776 private SettingsState peekSettingsStateLocked(int key) {
1777 SettingsState settingsState = mSettingsStates.get(key);
1778 if (settingsState != null) {
1779 return settingsState;
1782 ensureSettingsForUserLocked(getUserIdFromKey(key));
1783 return mSettingsStates.get(key);
1786 private void migrateAllLegacySettingsIfNeeded() {
1787 synchronized (mLock) {
1788 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
1789 File globalFile = getSettingsFile(key);
1790 if (globalFile.exists()) {
1794 final long identity = Binder.clearCallingIdentity();
1796 List<UserInfo> users = mUserManager.getUsers(true);
1798 final int userCount = users.size();
1799 for (int i = 0; i < userCount; i++) {
1800 final int userId = users.get(i).id;
1802 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1803 SQLiteDatabase database = dbHelper.getWritableDatabase();
1804 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1806 // Upgrade to the latest version.
1807 UpgradeController upgrader = new UpgradeController(userId);
1808 upgrader.upgradeIfNeededLocked();
1810 // Drop from memory if not a running user.
1811 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1812 removeUserStateLocked(userId, false);
1816 Binder.restoreCallingIdentity(identity);
1821 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1822 // Every user has secure settings and if no file we need to migrate.
1823 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1824 File secureFile = getSettingsFile(secureKey);
1825 if (secureFile.exists()) {
1829 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1830 SQLiteDatabase database = dbHelper.getWritableDatabase();
1832 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1835 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1836 SQLiteDatabase database, int userId) {
1837 // Move over the system settings.
1838 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1839 ensureSettingsStateLocked(systemKey);
1840 SettingsState systemSettings = mSettingsStates.get(systemKey);
1841 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1842 systemSettings.persistSyncLocked();
1844 // Move over the secure settings.
1845 // Do this after System settings, since this is the first thing we check when deciding
1846 // to skip over migration from db to xml for a secondary user.
1847 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1848 ensureSettingsStateLocked(secureKey);
1849 SettingsState secureSettings = mSettingsStates.get(secureKey);
1850 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1851 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1852 secureSettings.persistSyncLocked();
1854 // Move over the global settings if owner.
1855 // Do this last, since this is the first thing we check when deciding
1856 // to skip over migration from db to xml for owner user.
1857 if (userId == UserHandle.USER_SYSTEM) {
1858 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1859 ensureSettingsStateLocked(globalKey);
1860 SettingsState globalSettings = mSettingsStates.get(globalKey);
1861 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1862 globalSettings.persistSyncLocked();
1865 // Drop the database as now all is moved and persisted.
1866 if (DROP_DATABASE_ON_MIGRATION) {
1867 dbHelper.dropDatabase();
1869 dbHelper.backupDatabase();
1873 private void migrateLegacySettingsLocked(SettingsState settingsState,
1874 SQLiteDatabase database, String table) {
1875 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1876 queryBuilder.setTables(table);
1878 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1879 null, null, null, null, null);
1881 if (cursor == null) {
1886 if (!cursor.moveToFirst()) {
1890 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1891 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1893 settingsState.setVersionLocked(database.getVersion());
1895 while (!cursor.isAfterLast()) {
1896 String name = cursor.getString(nameColumnIdx);
1897 String value = cursor.getString(valueColumnIdx);
1898 settingsState.insertSettingLocked(name, value,
1899 SettingsState.SYSTEM_PACKAGE_NAME);
1900 cursor.moveToNext();
1907 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1908 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1910 if (value != null) {
1914 final int userId = getUserIdFromKey(secureSettings.mKey);
1916 final UserInfo user;
1917 final long identity = Binder.clearCallingIdentity();
1919 user = mUserManager.getUserInfo(userId);
1921 Binder.restoreCallingIdentity(identity);
1924 // Can happen due to races when deleting users - treat as benign.
1928 String androidId = Long.toHexString(new SecureRandom().nextLong());
1929 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1930 SettingsState.SYSTEM_PACKAGE_NAME);
1932 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1933 + "] for user " + userId);
1935 // Write a drop box entry if it's a restricted profile
1936 if (user.isRestricted()) {
1937 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1938 Context.DROPBOX_SERVICE);
1939 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1940 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1941 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1946 private void notifyForSettingsChange(int key, String name) {
1947 final int userId = getUserIdFromKey(key);
1948 Uri uri = getNotificationUriFor(key, name);
1950 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1951 userId, 0, uri).sendToTarget();
1953 if (isSecureSettingsKey(key)) {
1954 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1955 sSecureCloneToManagedSettings);
1956 } else if (isSystemSettingsKey(key)) {
1957 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1958 sSystemCloneToManagedSettings);
1961 mGenerationRegistry.incrementGeneration(key);
1963 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
1966 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
1967 Set<String> keysCloned) {
1968 if (keysCloned.contains(name)) {
1969 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
1970 // the notification for userId has already been sent.
1971 if (profileId != userId) {
1972 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1973 profileId, 0, uri).sendToTarget();
1974 final int key = makeKey(type, profileId);
1975 mGenerationRegistry.incrementGeneration(key);
1977 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
1983 private boolean isGlobalSettingsKey(int key) {
1984 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1987 private boolean isSystemSettingsKey(int key) {
1988 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1991 private boolean isSecureSettingsKey(int key) {
1992 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1995 private File getSettingsFile(int key) {
1996 if (isGlobalSettingsKey(key)) {
1997 final int userId = getUserIdFromKey(key);
1998 return new File(Environment.getUserSystemDirectory(userId),
1999 SETTINGS_FILE_GLOBAL);
2000 } else if (isSystemSettingsKey(key)) {
2001 final int userId = getUserIdFromKey(key);
2002 return new File(Environment.getUserSystemDirectory(userId),
2003 SETTINGS_FILE_SYSTEM);
2004 } else if (isSecureSettingsKey(key)) {
2005 final int userId = getUserIdFromKey(key);
2006 return new File(Environment.getUserSystemDirectory(userId),
2007 SETTINGS_FILE_SECURE);
2009 throw new IllegalArgumentException("Invalid settings key:" + key);
2013 private Uri getNotificationUriFor(int key, String name) {
2014 if (isGlobalSettingsKey(key)) {
2015 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2016 : Settings.Global.CONTENT_URI;
2017 } else if (isSecureSettingsKey(key)) {
2018 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2019 : Settings.Secure.CONTENT_URI;
2020 } else if (isSystemSettingsKey(key)) {
2021 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2022 : Settings.System.CONTENT_URI;
2024 throw new IllegalArgumentException("Invalid settings key:" + key);
2028 private int getMaxBytesPerPackageForType(int type) {
2030 case SETTINGS_TYPE_GLOBAL:
2031 case SETTINGS_TYPE_SECURE: {
2032 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2036 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2041 private final class MyHandler extends Handler {
2042 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2043 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2045 public MyHandler(Looper looper) {
2050 public void handleMessage(Message msg) {
2052 case MSG_NOTIFY_URI_CHANGED: {
2053 final int userId = msg.arg1;
2054 Uri uri = (Uri) msg.obj;
2055 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2057 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2061 case MSG_NOTIFY_DATA_CHANGED: {
2062 mBackupManager.dataChanged();
2068 private final class UpgradeController {
2069 private static final int SETTINGS_VERSION = 127;
2071 private final int mUserId;
2073 public UpgradeController(int userId) {
2077 public void upgradeIfNeededLocked() {
2078 // The version of all settings for a user is the same (all users have secure).
2079 SettingsState secureSettings = getSettingsLocked(
2080 SETTINGS_TYPE_SECURE, mUserId);
2082 // Try an update from the current state.
2083 final int oldVersion = secureSettings.getVersionLocked();
2084 final int newVersion = SETTINGS_VERSION;
2086 // If up do date - done.
2087 if (oldVersion == newVersion) {
2092 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2094 // If upgrade failed start from scratch and upgrade.
2095 if (curVersion != newVersion) {
2096 // Drop state we have for this user.
2097 removeUserStateLocked(mUserId, true);
2099 // Recreate the database.
2100 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2101 SQLiteDatabase database = dbHelper.getWritableDatabase();
2102 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2104 // Migrate the settings for this user.
2105 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2107 // Now upgrade should work fine.
2108 onUpgradeLocked(mUserId, oldVersion, newVersion);
2111 // Set the global settings version if owner.
2112 if (mUserId == UserHandle.USER_SYSTEM) {
2113 SettingsState globalSettings = getSettingsLocked(
2114 SETTINGS_TYPE_GLOBAL, mUserId);
2115 globalSettings.setVersionLocked(newVersion);
2118 // Set the secure settings version.
2119 secureSettings.setVersionLocked(newVersion);
2121 // Set the system settings version.
2122 SettingsState systemSettings = getSettingsLocked(
2123 SETTINGS_TYPE_SYSTEM, mUserId);
2124 systemSettings.setVersionLocked(newVersion);
2127 private SettingsState getGlobalSettingsLocked() {
2128 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
2131 private SettingsState getSecureSettingsLocked(int userId) {
2132 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2135 private SettingsState getSystemSettingsLocked(int userId) {
2136 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2140 * You must perform all necessary mutations to bring the settings
2141 * for this user from the old to the new version. When you add a new
2142 * upgrade step you *must* update SETTINGS_VERSION.
2144 * This is an example of moving a setting from secure to global.
2146 * // v119: Example settings changes.
2147 * if (currentVersion == 118) {
2148 * if (userId == UserHandle.USER_OWNER) {
2149 * // Remove from the secure settings.
2150 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2151 * String name = "example_setting_to_move";
2152 * String value = secureSettings.getSetting(name);
2153 * secureSettings.deleteSetting(name);
2155 * // Add to the global settings.
2156 * SettingsState globalSettings = getGlobalSettingsLocked();
2157 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2160 * // Update the current version.
2161 * currentVersion = 119;
2164 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2166 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2167 + oldVersion + " to version: " + newVersion);
2170 int currentVersion = oldVersion;
2172 // v119: Reset zen + ringer mode.
2173 if (currentVersion == 118) {
2174 if (userId == UserHandle.USER_SYSTEM) {
2175 final SettingsState globalSettings = getGlobalSettingsLocked();
2176 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2177 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2178 SettingsState.SYSTEM_PACKAGE_NAME);
2179 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2180 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2181 SettingsState.SYSTEM_PACKAGE_NAME);
2183 currentVersion = 119;
2186 // v120: Add double tap to wake setting.
2187 if (currentVersion == 119) {
2188 SettingsState secureSettings = getSecureSettingsLocked(userId);
2189 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2190 getContext().getResources().getBoolean(
2191 R.bool.def_double_tap_to_wake) ? "1" : "0",
2192 SettingsState.SYSTEM_PACKAGE_NAME);
2194 currentVersion = 120;
2197 if (currentVersion == 120) {
2198 // Before 121, we used a different string encoding logic. We just bump the
2199 // version here; SettingsState knows how to handle pre-version 120 files.
2200 currentVersion = 121;
2203 if (currentVersion == 121) {
2204 // Version 122: allow OEMs to set a default payment component in resources.
2205 // Note that we only write the default if no default has been set;
2206 // if there is, we just leave the default at whatever it currently is.
2207 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2208 String defaultComponent = (getContext().getResources().getString(
2209 R.string.def_nfc_payment_component));
2210 Setting currentSetting = secureSettings.getSettingLocked(
2211 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2212 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2213 currentSetting.isNull()) {
2214 secureSettings.insertSettingLocked(
2215 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2217 SettingsState.SYSTEM_PACKAGE_NAME);
2219 currentVersion = 122;
2222 if (currentVersion == 122) {
2223 // Version 123: Adding a default value for the ability to add a user from
2225 if (userId == UserHandle.USER_SYSTEM) {
2226 final SettingsState globalSettings = getGlobalSettingsLocked();
2227 Setting currentSetting = globalSettings.getSettingLocked(
2228 Settings.Global.ADD_USERS_WHEN_LOCKED);
2229 if (currentSetting.isNull()) {
2230 globalSettings.insertSettingLocked(
2231 Settings.Global.ADD_USERS_WHEN_LOCKED,
2232 getContext().getResources().getBoolean(
2233 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2234 SettingsState.SYSTEM_PACKAGE_NAME);
2237 currentVersion = 123;
2240 if (currentVersion == 123) {
2241 final SettingsState globalSettings = getGlobalSettingsLocked();
2242 String defaultDisabledProfiles = (getContext().getResources().getString(
2243 R.string.def_bluetooth_disabled_profiles));
2244 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2245 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
2246 currentVersion = 124;
2249 if (currentVersion == 124) {
2250 // Version 124: allow OEMs to set a default value for whether IME should be
2251 // shown when a physical keyboard is connected.
2252 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2253 Setting currentSetting = secureSettings.getSettingLocked(
2254 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
2255 if (currentSetting.isNull()) {
2256 secureSettings.insertSettingLocked(
2257 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2258 getContext().getResources().getBoolean(
2259 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2260 SettingsState.SYSTEM_PACKAGE_NAME);
2262 currentVersion = 125;
2265 if (currentVersion == 125) {
2266 // Version 125: Allow OEMs to set the default VR service.
2267 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2269 Setting currentSetting = secureSettings.getSettingLocked(
2270 Settings.Secure.ENABLED_VR_LISTENERS);
2271 if (currentSetting.isNull()) {
2272 ArraySet<ComponentName> l =
2273 SystemConfig.getInstance().getDefaultVrComponents();
2275 if (l != null && !l.isEmpty()) {
2276 StringBuilder b = new StringBuilder();
2277 boolean start = true;
2278 for (ComponentName c : l) {
2282 b.append(c.flattenToString());
2285 secureSettings.insertSettingLocked(
2286 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2287 SettingsState.SYSTEM_PACKAGE_NAME);
2291 currentVersion = 126;
2294 if (currentVersion == 126) {
2295 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2296 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2297 if (mUserManager.isManagedProfile(userId)) {
2298 final SettingsState systemSecureSettings =
2299 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2301 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2302 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
2303 if (showNotifications != null) {
2304 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2305 secureSettings.insertSettingLocked(
2306 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2307 showNotifications.getValue(),
2308 SettingsState.SYSTEM_PACKAGE_NAME);
2311 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2312 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
2313 if (allowPrivate != null) {
2314 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2315 secureSettings.insertSettingLocked(
2316 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2317 allowPrivate.getValue(),
2318 SettingsState.SYSTEM_PACKAGE_NAME);
2321 currentVersion = 127;
2324 // vXXX: Add new settings above this point.
2326 // Return the current version.
2327 return currentVersion;