OSDN Git Service

Merge "Merge "Docs: minor AS 2.0 related fixes" into mnc-mr-docs am: a598807 am:...
[android-x86/frameworks-base.git] / packages / SettingsProvider / src / com / android / providers / settings / SettingsProvider.java
1 /*
2  * Copyright (C) 2007 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 com.android.providers.settings;
18
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;
63
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;
70
71 import java.io.File;
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;
78 import java.util.Set;
79 import java.util.regex.Pattern;
80
81 /**
82  * <p>
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.
87  * </p>
88  * <p>
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.
99  * </p>
100  * <p>
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.
110  * </p>
111  */
112 @SuppressWarnings("deprecation")
113 public class SettingsProvider extends ContentProvider {
114     private static final boolean DEBUG = false;
115
116     private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
117
118     private static final String LOG_TAG = "SettingsProvider";
119
120     private static final String TABLE_SYSTEM = "system";
121     private static final String TABLE_SECURE = "secure";
122     private static final String TABLE_GLOBAL = "global";
123
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";
130
131     // The set of removed legacy tables.
132     private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
133     static {
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);
139     }
140
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;
144
145     private static final String[] ALL_COLUMNS = new String[] {
146             Settings.NameValueTable._ID,
147             Settings.NameValueTable.NAME,
148             Settings.NameValueTable.VALUE
149     };
150
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;
154
155     public static final int SETTINGS_TYPE_MASK = 0xF0000000;
156     public static final int SETTINGS_TYPE_SHIFT = 28;
157
158     private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
159             Settings.NameValueTable.VALUE, null);
160
161     // Per user secure settings that moved to the for all users global settings.
162     static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
163     static {
164         Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
165     }
166
167     // Per user system settings that moved to the for all users global settings.
168     static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
169     static {
170         Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
171     }
172
173     // Per user system settings that moved to the per user secure settings.
174     static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
175     static {
176         Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
177     }
178
179     // Per all users global settings that moved to the per user secure settings.
180     static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
181     static {
182         Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
183     }
184
185     // Per user secure settings that are cloned for the managed profiles of the user.
186     private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
187     static {
188         Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
189     }
190
191     // Per user system settings that are cloned for the managed profiles of the user.
192     private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
193     static {
194         Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
195     }
196
197     private final Object mLock = new Object();
198
199     @GuardedBy("mLock")
200     private SettingsRegistry mSettingsRegistry;
201
202     // We have to call in the user manager with no lock held,
203     private volatile UserManager mUserManager;
204
205     // We have to call in the package manager with no lock held,
206     private volatile IPackageManager mPackageManager;
207
208     public static int makeKey(int type, int userId) {
209         return (type << SETTINGS_TYPE_SHIFT) | userId;
210     }
211
212     public static int getTypeFromKey(int key) {
213         return key >>> SETTINGS_TYPE_SHIFT;
214     }
215
216     public static int getUserIdFromKey(int key) {
217         return key & ~SETTINGS_TYPE_MASK;
218     }
219
220     public static String settingTypeToString(int type) {
221         switch (type) {
222             case SETTINGS_TYPE_GLOBAL: {
223                 return "SETTINGS_GLOBAL";
224             }
225             case SETTINGS_TYPE_SECURE: {
226                 return "SETTINGS_SECURE";
227             }
228             case SETTINGS_TYPE_SYSTEM: {
229                 return "SETTINGS_SYSTEM";
230             }
231             default: {
232                 return "UNKNOWN";
233             }
234         }
235     }
236
237     public static String keyToString(int key) {
238         return "Key[user=" + getUserIdFromKey(key) + ";type="
239                 + settingTypeToString(getTypeFromKey(key)) + "]";
240     }
241
242     @Override
243     public boolean onCreate() {
244         synchronized (mLock) {
245             mUserManager = UserManager.get(getContext());
246             mPackageManager = AppGlobals.getPackageManager();
247             mSettingsRegistry = new SettingsRegistry();
248         }
249         registerBroadcastReceivers();
250         startWatchingUserRestrictionChanges();
251         return true;
252     }
253
254     @Override
255     public Bundle call(String method, String name, Bundle args) {
256         final int requestingUserId = getRequestingUserId(args);
257         switch (method) {
258             case Settings.CALL_METHOD_GET_GLOBAL: {
259                 Setting setting = getGlobalSetting(name);
260                 return packageValueForCallResult(setting, isTrackingGeneration(args));
261             }
262
263             case Settings.CALL_METHOD_GET_SECURE: {
264                 Setting setting = getSecureSetting(name, requestingUserId);
265                 return packageValueForCallResult(setting, isTrackingGeneration(args));
266             }
267
268             case Settings.CALL_METHOD_GET_SYSTEM: {
269                 Setting setting = getSystemSetting(name, requestingUserId);
270                 return packageValueForCallResult(setting, isTrackingGeneration(args));
271             }
272
273             case Settings.CALL_METHOD_PUT_GLOBAL: {
274                 String value = getSettingValue(args);
275                 insertGlobalSetting(name, value, requestingUserId, false);
276                 break;
277             }
278
279             case Settings.CALL_METHOD_PUT_SECURE: {
280                 String value = getSettingValue(args);
281                 insertSecureSetting(name, value, requestingUserId, false);
282                 break;
283             }
284
285             case Settings.CALL_METHOD_PUT_SYSTEM: {
286                 String value = getSettingValue(args);
287                 insertSystemSetting(name, value, requestingUserId);
288                 break;
289             }
290
291             default: {
292                 Slog.w(LOG_TAG, "call() with invalid method: " + method);
293             } break;
294         }
295
296         return null;
297     }
298
299     @Override
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;
304         } else {
305             return "vnd.android.cursor.item/" + args.table;
306         }
307     }
308
309     @Override
310     public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
311             String order) {
312         if (DEBUG) {
313             Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
314         }
315
316         Arguments args = new Arguments(uri, where, whereArgs, true);
317         String[] normalizedProjection = normalizeProjection(projection);
318
319         // If a legacy table that is gone, done.
320         if (REMOVED_LEGACY_TABLES.contains(args.table)) {
321             return new MatrixCursor(normalizedProjection, 0);
322         }
323
324         switch (args.table) {
325             case TABLE_GLOBAL: {
326                 if (args.name != null) {
327                     Setting setting = getGlobalSetting(args.name);
328                     return packageSettingForQuery(setting, normalizedProjection);
329                 } else {
330                     return getAllGlobalSettings(projection);
331                 }
332             }
333
334             case TABLE_SECURE: {
335                 final int userId = UserHandle.getCallingUserId();
336                 if (args.name != null) {
337                     Setting setting = getSecureSetting(args.name, userId);
338                     return packageSettingForQuery(setting, normalizedProjection);
339                 } else {
340                     return getAllSecureSettings(userId, projection);
341                 }
342             }
343
344             case TABLE_SYSTEM: {
345                 final int userId = UserHandle.getCallingUserId();
346                 if (args.name != null) {
347                     Setting setting = getSystemSetting(args.name, userId);
348                     return packageSettingForQuery(setting, normalizedProjection);
349                 } else {
350                     return getAllSystemSettings(userId, projection);
351                 }
352             }
353
354             default: {
355                 throw new IllegalArgumentException("Invalid Uri path:" + uri);
356             }
357         }
358     }
359
360     @Override
361     public Uri insert(Uri uri, ContentValues values) {
362         if (DEBUG) {
363             Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
364         }
365
366         String table = getValidTableOrThrow(uri);
367
368         // If a legacy table that is gone, done.
369         if (REMOVED_LEGACY_TABLES.contains(table)) {
370             return null;
371         }
372
373         String name = values.getAsString(Settings.Secure.NAME);
374         if (!isKeyValid(name)) {
375             return null;
376         }
377
378         String value = values.getAsString(Settings.Secure.VALUE);
379
380         switch (table) {
381             case TABLE_GLOBAL: {
382                 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
383                     return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
384                 }
385             } break;
386
387             case TABLE_SECURE: {
388                 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
389                     return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
390                 }
391             } break;
392
393             case TABLE_SYSTEM: {
394                 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
395                     return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
396                 }
397             } break;
398
399             default: {
400                 throw new IllegalArgumentException("Bad Uri path:" + uri);
401             }
402         }
403
404         return null;
405     }
406
407     @Override
408     public int bulkInsert(Uri uri, ContentValues[] allValues) {
409         if (DEBUG) {
410             Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
411         }
412
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) {
418                 insertionCount++;
419             }
420         }
421
422         return insertionCount;
423     }
424
425     @Override
426     public int delete(Uri uri, String where, String[] whereArgs) {
427         if (DEBUG) {
428             Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
429         }
430
431         Arguments args = new Arguments(uri, where, whereArgs, false);
432
433         // If a legacy table that is gone, done.
434         if (REMOVED_LEGACY_TABLES.contains(args.table)) {
435             return 0;
436         }
437
438         if (!isKeyValid(args.name)) {
439             return 0;
440         }
441
442         switch (args.table) {
443             case TABLE_GLOBAL: {
444                 final int userId = UserHandle.getCallingUserId();
445                 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
446             }
447
448             case TABLE_SECURE: {
449                 final int userId = UserHandle.getCallingUserId();
450                 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
451             }
452
453             case TABLE_SYSTEM: {
454                 final int userId = UserHandle.getCallingUserId();
455                 return deleteSystemSetting(args.name, userId) ? 1 : 0;
456             }
457
458             default: {
459                 throw new IllegalArgumentException("Bad Uri path:" + uri);
460             }
461         }
462     }
463
464     @Override
465     public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
466         if (DEBUG) {
467             Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
468         }
469
470         Arguments args = new Arguments(uri, where, whereArgs, false);
471
472         // If a legacy table that is gone, done.
473         if (REMOVED_LEGACY_TABLES.contains(args.table)) {
474             return 0;
475         }
476
477         String name = values.getAsString(Settings.Secure.NAME);
478         if (!isKeyValid(name)) {
479             return 0;
480         }
481         String value = values.getAsString(Settings.Secure.VALUE);
482
483         switch (args.table) {
484             case TABLE_GLOBAL: {
485                 final int userId = UserHandle.getCallingUserId();
486                 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
487             }
488
489             case TABLE_SECURE: {
490                 final int userId = UserHandle.getCallingUserId();
491                 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
492             }
493
494             case TABLE_SYSTEM: {
495                 final int userId = UserHandle.getCallingUserId();
496                 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
497             }
498
499             default: {
500                 throw new IllegalArgumentException("Invalid Uri path:" + uri);
501             }
502         }
503     }
504
505     @Override
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;
514         } else {
515             throw new FileNotFoundException("Direct file access no longer supported; "
516                     + "ringtone playback is available through android.media.Ringtone");
517         }
518
519         final File cacheFile = new File(
520                 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
521         return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
522     }
523
524     private File getRingtoneCacheDir(int userId) {
525         final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
526         cacheDir.mkdir();
527         SELinux.restorecon(cacheDir);
528         return cacheDir;
529     }
530
531     @Override
532     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
533         synchronized (mLock) {
534             final long identity = Binder.clearCallingIdentity();
535             try {
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);
541                 }
542             } finally {
543                 Binder.restoreCallingIdentity(identity);
544             }
545         }
546     }
547
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);
553             pw.println();
554         }
555
556         pw.println("SECURE SETTINGS (user " + userId + ")");
557         Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
558         dumpSettings(secureCursor, pw);
559         pw.println();
560
561         pw.println("SYSTEM SETTINGS (user " + userId + ")");
562         Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
563         dumpSettings(systemCursor, pw);
564         pw.println();
565     }
566
567     private void dumpSettings(Cursor cursor, PrintWriter pw) {
568         if (cursor == null || !cursor.moveToFirst()) {
569             return;
570         }
571
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);
575
576         do {
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)));
580             pw.println();
581         } while (cursor.moveToNext());
582     }
583
584     private static String toDumpString(String s) {
585         if (s != null) {
586             return s;
587         }
588         return "{null}";
589     }
590
591     private void registerBroadcastReceivers() {
592         IntentFilter userFilter = new IntentFilter();
593         userFilter.addAction(Intent.ACTION_USER_REMOVED);
594         userFilter.addAction(Intent.ACTION_USER_STOPPED);
595
596         getContext().registerReceiver(new BroadcastReceiver() {
597             @Override
598             public void onReceive(Context context, Intent intent) {
599                 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
600                         UserHandle.USER_SYSTEM);
601
602                 switch (intent.getAction()) {
603                     case Intent.ACTION_USER_REMOVED: {
604                         synchronized (mLock) {
605                             mSettingsRegistry.removeUserStateLocked(userId, true);
606                         }
607                     } break;
608
609                     case Intent.ACTION_USER_STOPPED: {
610                         synchronized (mLock) {
611                             mSettingsRegistry.removeUserStateLocked(userId, false);
612                         }
613                     } break;
614                 }
615             }
616         }, userFilter);
617
618         PackageMonitor monitor = new PackageMonitor() {
619             @Override
620             public void onPackageRemoved(String packageName, int uid) {
621                 synchronized (mLock) {
622                     mSettingsRegistry.onPackageRemovedLocked(packageName,
623                             UserHandle.getUserId(uid));
624                 }
625             }
626         };
627
628         // package changes
629         monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
630                 UserHandle.ALL, true);
631     }
632
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();
647                 try {
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);
653                     }
654                 } finally {
655                     Binder.restoreCallingIdentity(identity);
656                 }
657             }
658             if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
659                     != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
660                 final long identity = Binder.clearCallingIdentity();
661                 try {
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);
666                     }
667                 } finally {
668                     Binder.restoreCallingIdentity(identity);
669                 }
670             }
671             if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
672                     != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
673                 final long identity = Binder.clearCallingIdentity();
674                 try {
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);
679                     }
680                 } finally {
681                     Binder.restoreCallingIdentity(identity);
682                 }
683             }
684             if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
685                     != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
686                 final long identity = Binder.clearCallingIdentity();
687                 try {
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);
697                     }
698                 } finally {
699                     Binder.restoreCallingIdentity(identity);
700                 }
701             }
702             if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
703                     != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
704                 final long identity = Binder.clearCallingIdentity();
705                 try {
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);
711                     }
712                 } finally {
713                     Binder.restoreCallingIdentity(identity);
714                 }
715             }
716         });
717     }
718
719     private Cursor getAllGlobalSettings(String[] projection) {
720         if (DEBUG) {
721             Slog.v(LOG_TAG, "getAllGlobalSettings()");
722         }
723
724         synchronized (mLock) {
725             // Get the settings.
726             SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
727                     SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
728
729             List<String> names = settingsState.getSettingNamesLocked();
730
731             final int nameCount = names.size();
732
733             String[] normalizedProjection = normalizeProjection(projection);
734             MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
735
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);
741             }
742
743             return result;
744         }
745     }
746
747     private Setting getGlobalSetting(String name) {
748         if (DEBUG) {
749             Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
750         }
751
752         // Get the value.
753         synchronized (mLock) {
754             return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
755                     UserHandle.USER_SYSTEM, name);
756         }
757     }
758
759     private boolean updateGlobalSetting(String name, String value, int requestingUserId,
760             boolean forceNotify) {
761         if (DEBUG) {
762             Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
763         }
764         return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
765                 forceNotify);
766     }
767
768     private boolean insertGlobalSetting(String name, String value, int requestingUserId,
769             boolean forceNotify) {
770         if (DEBUG) {
771             Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
772         }
773         return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
774                 forceNotify);
775     }
776
777     private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
778         if (DEBUG) {
779             Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
780         }
781         return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
782                 forceNotify);
783     }
784
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);
789
790         // Resolve the userId on whose behalf the call is made.
791         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
792
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)) {
796             return false;
797         }
798
799         // Perform the mutation.
800         synchronized (mLock) {
801             switch (operation) {
802                 case MUTATION_OPERATION_INSERT: {
803                     return mSettingsRegistry
804                             .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
805                                     name, value, getCallingPackage(), forceNotify);
806                 }
807
808                 case MUTATION_OPERATION_DELETE: {
809                     return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
810                             UserHandle.USER_SYSTEM, name, forceNotify);
811                 }
812
813                 case MUTATION_OPERATION_UPDATE: {
814                     return mSettingsRegistry
815                             .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
816                                     name, value, getCallingPackage(), forceNotify);
817                 }
818             }
819         }
820
821         return false;
822     }
823
824     private Cursor getAllSecureSettings(int userId, String[] projection) {
825         if (DEBUG) {
826             Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
827         }
828
829         // Resolve the userId on whose behalf the call is made.
830         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
831
832         synchronized (mLock) {
833             List<String> names = mSettingsRegistry.getSettingsNamesLocked(
834                     SETTINGS_TYPE_SECURE, callingUserId);
835
836             final int nameCount = names.size();
837
838             String[] normalizedProjection = normalizeProjection(projection);
839             MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
840
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,
845                         name);
846
847                 // Special case for location (sigh).
848                 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
849                     return null;
850                 }
851
852                 Setting setting = mSettingsRegistry.getSettingLocked(
853                         SETTINGS_TYPE_SECURE, owningUserId, name);
854                 appendSettingToCursor(result, setting);
855             }
856
857             return result;
858         }
859     }
860
861     private Setting getSecureSetting(String name, int requestingUserId) {
862         if (DEBUG) {
863             Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
864         }
865
866         // Resolve the userId on whose behalf the call is made.
867         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
868
869         // Determine the owning user as some profile settings are cloned from the parent.
870         final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
871
872         // Special case for location (sigh).
873         if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
874             return null;
875         }
876
877         // Get the value.
878         synchronized (mLock) {
879             return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
880                     owningUserId, name);
881         }
882     }
883
884     private boolean insertSecureSetting(String name, String value, int requestingUserId,
885             boolean forceNotify) {
886         if (DEBUG) {
887             Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
888                     + requestingUserId + ")");
889         }
890
891         return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
892                 forceNotify);
893     }
894
895     private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
896         if (DEBUG) {
897             Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
898         }
899
900         return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
901                 forceNotify);
902     }
903
904     private boolean updateSecureSetting(String name, String value, int requestingUserId,
905             boolean forceNotify) {
906         if (DEBUG) {
907             Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
908                     + requestingUserId + ")");
909         }
910
911         return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
912                 forceNotify);
913     }
914
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);
919
920         // Resolve the userId on whose behalf the call is made.
921         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
922
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)) {
926             return false;
927         }
928
929         // Determine the owning user as some profile settings are cloned from the parent.
930         final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
931
932         // Only the owning user can change the setting.
933         if (owningUserId != callingUserId) {
934             return false;
935         }
936
937         // Special cases for location providers (sigh).
938         if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
939             return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
940         }
941
942         // Mutate the value.
943         synchronized (mLock) {
944             switch (operation) {
945                 case MUTATION_OPERATION_INSERT: {
946                     return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
947                             owningUserId, name, value, getCallingPackage(), forceNotify);
948                 }
949
950                 case MUTATION_OPERATION_DELETE: {
951                     return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
952                             owningUserId, name, forceNotify);
953                 }
954
955                 case MUTATION_OPERATION_UPDATE: {
956                     return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
957                             owningUserId, name, value, getCallingPackage(), forceNotify);
958                 }
959             }
960         }
961
962         return false;
963     }
964
965     private Cursor getAllSystemSettings(int userId, String[] projection) {
966         if (DEBUG) {
967             Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
968         }
969
970         // Resolve the userId on whose behalf the call is made.
971         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
972
973         synchronized (mLock) {
974             List<String> names = mSettingsRegistry.getSettingsNamesLocked(
975                     SETTINGS_TYPE_SYSTEM, callingUserId);
976
977             final int nameCount = names.size();
978
979             String[] normalizedProjection = normalizeProjection(projection);
980             MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
981
982             for (int i = 0; i < nameCount; i++) {
983                 String name = names.get(i);
984
985                 // Determine the owning user as some profile settings are cloned from the parent.
986                 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
987                         name);
988
989                 Setting setting = mSettingsRegistry.getSettingLocked(
990                         SETTINGS_TYPE_SYSTEM, owningUserId, name);
991                 appendSettingToCursor(result, setting);
992             }
993
994             return result;
995         }
996     }
997
998     private Setting getSystemSetting(String name, int requestingUserId) {
999         if (DEBUG) {
1000             Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1001         }
1002
1003         // Resolve the userId on whose behalf the call is made.
1004         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1005
1006         // Determine the owning user as some profile settings are cloned from the parent.
1007         final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1008
1009         // Get the value.
1010         synchronized (mLock) {
1011             return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
1012         }
1013     }
1014
1015     private boolean insertSystemSetting(String name, String value, int requestingUserId) {
1016         if (DEBUG) {
1017             Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
1018                     + requestingUserId + ")");
1019         }
1020
1021         return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
1022     }
1023
1024     private boolean deleteSystemSetting(String name, int requestingUserId) {
1025         if (DEBUG) {
1026             Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
1027         }
1028
1029         return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
1030     }
1031
1032     private boolean updateSystemSetting(String name, String value, int requestingUserId) {
1033         if (DEBUG) {
1034             Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
1035                     + requestingUserId + ")");
1036         }
1037
1038         return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
1039     }
1040
1041     private boolean mutateSystemSetting(String name, String value, int runAsUserId,
1042             int operation) {
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)) {
1048                 return false;
1049             }
1050         }
1051
1052         // Resolve the userId on whose behalf the call is made.
1053         final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1054
1055         // Enforce what the calling package can mutate the system settings.
1056         enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1057
1058         // Determine the owning user as some profile settings are cloned from the parent.
1059         final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1060
1061         // Only the owning user id can change the setting.
1062         if (owningUserId != callingUserId) {
1063             return false;
1064         }
1065
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;
1074         }
1075         if (cacheName != null) {
1076             final File cacheFile = new File(
1077                     getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
1078             cacheFile.delete();
1079         }
1080
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);
1088                 }
1089
1090                 case MUTATION_OPERATION_DELETE: {
1091                     return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1092                             owningUserId, name, false);
1093                 }
1094
1095                 case MUTATION_OPERATION_UPDATE: {
1096                     validateSystemSettingValue(name, value);
1097                     return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1098                             owningUserId, name, value, getCallingPackage(), false);
1099                 }
1100             }
1101
1102             return false;
1103         }
1104     }
1105
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) {
1110             return true;
1111         }
1112
1113         return false;
1114     }
1115
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);
1121         }
1122     }
1123
1124     private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1125             int owningUserId) {
1126         // Optimization - location providers are restricted only for managed profiles.
1127         if (callingUserId == owningUserId) {
1128             return false;
1129         }
1130         if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1131                 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1132                 new UserHandle(callingUserId))) {
1133             return true;
1134         }
1135         return false;
1136     }
1137
1138     /**
1139      * Checks whether changing a setting to a value is prohibited by the corresponding user
1140      * restriction.
1141      *
1142      * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1143      * Context, int, String, boolean)}, which should be in sync with this method.
1144      *
1145      * @return true if the change is prohibited, false if the change is allowed.
1146      */
1147     private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
1148             String value) {
1149         String restriction;
1150         switch (setting) {
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;
1157                 break;
1158
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;
1164                 break;
1165
1166             case Settings.Secure.INSTALL_NON_MARKET_APPS:
1167                 if ("0".equals(value)) return false;
1168                 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1169                 break;
1170
1171             case Settings.Global.ADB_ENABLED:
1172                 if ("0".equals(value)) return false;
1173                 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1174                 break;
1175
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;
1180                 break;
1181
1182             case Settings.Global.PREFERRED_NETWORK_MODE:
1183                 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1184                 break;
1185
1186             default:
1187                 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
1188                     if ("0".equals(value)) return false;
1189                     restriction = UserManager.DISALLOW_DATA_ROAMING;
1190                     break;
1191                 }
1192                 return false;
1193         }
1194
1195         return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
1196     }
1197
1198     private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1199         return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1200     }
1201
1202     private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1203         return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1204     }
1205
1206     private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1207         final int parentId = getGroupParentLocked(userId);
1208         if (parentId != userId && keys.contains(name)) {
1209             return parentId;
1210         }
1211         return userId;
1212     }
1213
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) {
1221             return;
1222         }
1223
1224         switch (operation) {
1225             case MUTATION_OPERATION_INSERT:
1226                 // Insert updates.
1227             case MUTATION_OPERATION_UPDATE: {
1228                 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1229                     return;
1230                 }
1231
1232                 // The calling package is already verified.
1233                 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
1234
1235                 // Privileged apps can do whatever they want.
1236                 if ((packageInfo.applicationInfo.privateFlags
1237                         & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1238                     return;
1239                 }
1240
1241                 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1242                         packageInfo.applicationInfo.targetSdkVersion, name);
1243             } break;
1244
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.");
1250                 }
1251
1252                 // The calling package is already verified.
1253                 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
1254
1255                 // Privileged apps can do whatever they want.
1256                 if ((packageInfo.applicationInfo.privateFlags &
1257                         ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1258                     return;
1259                 }
1260
1261                 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1262                         packageInfo.applicationInfo.targetSdkVersion, name);
1263             } break;
1264         }
1265     }
1266
1267     private PackageInfo getCallingPackageInfoOrThrow(int userId) {
1268         try {
1269             PackageInfo packageInfo = mPackageManager.getPackageInfo(
1270                     getCallingPackage(), 0, userId);
1271             if (packageInfo != null) {
1272                 return packageInfo;
1273             }
1274         } catch (RemoteException e) {
1275             /* ignore */
1276         }
1277         throw new IllegalStateException("Calling package doesn't exist");
1278     }
1279
1280     private int getGroupParentLocked(int userId) {
1281         // Most frequent use case.
1282         if (userId == UserHandle.USER_SYSTEM) {
1283             return userId;
1284         }
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();
1288         try {
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;
1292         } finally {
1293             Binder.restoreCallingIdentity(identity);
1294         }
1295     }
1296
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:"
1301                     + permission);
1302         }
1303     }
1304
1305     /*
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.
1310      *
1311      * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}.  If DISALLOW_SHARE_LOCATION
1312      * is set, the said method will only allow values with the "-" prefix.
1313      *
1314      * @returns whether the enabled location providers changed.
1315      */
1316     private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1317             boolean forceNotify) {
1318         if (TextUtils.isEmpty(value)) {
1319             return false;
1320         }
1321
1322         final char prefix = value.charAt(0);
1323         if (prefix != '+' && prefix != '-') {
1324             if (forceNotify) {
1325                 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1326                 mSettingsRegistry.notifyForSettingsChange(key,
1327                         Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1328             }
1329             return false;
1330         }
1331
1332         // skip prefix
1333         value = value.substring(1);
1334
1335         Setting settingValue = getSecureSetting(
1336                 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1337
1338         String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1339
1340         int index = oldProviders.indexOf(value);
1341         int end = index + value.length();
1342
1343         // check for commas to avoid matching on partial string
1344         if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1345             index = -1;
1346         }
1347
1348         // check for commas to avoid matching on partial string
1349         if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1350             index = -1;
1351         }
1352
1353         String newProviders;
1354
1355         if (prefix == '+' && index < 0) {
1356             // append the provider to the list if not present
1357             if (oldProviders.length() == 0) {
1358                 newProviders = value;
1359             } else {
1360                 newProviders = oldProviders + ',' + value;
1361             }
1362         } else if (prefix == '-' && index >= 0) {
1363             // remove the provider from the list if present
1364             // remove leading or trailing comma
1365             if (index > 0) {
1366                 index--;
1367             } else if (end < oldProviders.length()) {
1368                 end++;
1369             }
1370
1371             newProviders = oldProviders.substring(0, index);
1372             if (end < oldProviders.length()) {
1373                 newProviders += oldProviders.substring(end);
1374             }
1375         } else {
1376             // nothing changed, so no need to update the database
1377             if (forceNotify) {
1378                 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1379                 mSettingsRegistry.notifyForSettingsChange(key,
1380                         Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1381             }
1382             return false;
1383         }
1384
1385         return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
1386                 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1387                 getCallingPackage(), forceNotify);
1388     }
1389
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.");
1397             } else {
1398                 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1399                         + " This will soon become an error.");
1400             }
1401         } else {
1402             if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1403                 throw new IllegalArgumentException("You cannot change private secure settings.");
1404             } else {
1405                 throw new IllegalArgumentException("You cannot keep your settings in"
1406                         + " the secure settings.");
1407             }
1408         }
1409     }
1410
1411     private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1412         if (requestingUserId == UserHandle.getCallingUserId()) {
1413             return requestingUserId;
1414         }
1415         return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1416                 Binder.getCallingUid(), requestingUserId, false, true,
1417                 "get/set setting for user", null);
1418     }
1419
1420     private Bundle packageValueForCallResult(Setting setting,
1421             boolean trackingGeneration) {
1422         if (!trackingGeneration) {
1423             if (setting.isNull()) {
1424                 return NULL_SETTING_BUNDLE;
1425             }
1426             return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1427         }
1428         Bundle result = new Bundle();
1429         result.putString(Settings.NameValueTable.VALUE,
1430                 !setting.isNull() ? setting.getValue() : null);
1431         mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1432         return result;
1433     }
1434
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)
1438                 : callingUserId;
1439     }
1440
1441     private boolean isTrackingGeneration(Bundle args) {
1442         return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1443     }
1444
1445     private static String getSettingValue(Bundle args) {
1446         return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1447     }
1448
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)) {
1453                 return table;
1454             }
1455             throw new IllegalArgumentException("Bad root path: " + table);
1456         }
1457         throw new IllegalArgumentException("Invalid URI:" + uri);
1458     }
1459
1460     private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1461         if (setting.isNull()) {
1462             return new MatrixCursor(projection, 0);
1463         }
1464         MatrixCursor cursor = new MatrixCursor(projection, 1);
1465         appendSettingToCursor(cursor, setting);
1466         return cursor;
1467     }
1468
1469     private static String[] normalizeProjection(String[] projection) {
1470         if (projection == null) {
1471             return ALL_COLUMNS;
1472         }
1473
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);
1479             }
1480         }
1481
1482         return projection;
1483     }
1484
1485     private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1486         if (setting.isNull()) {
1487             return;
1488         }
1489         final int columnCount = cursor.getColumnCount();
1490
1491         String[] values =  new String[columnCount];
1492
1493         for (int i = 0; i < columnCount; i++) {
1494             String column = cursor.getColumnName(i);
1495
1496             switch (column) {
1497                 case Settings.NameValueTable._ID: {
1498                     values[i] = setting.getId();
1499                 } break;
1500
1501                 case Settings.NameValueTable.NAME: {
1502                     values[i] = setting.getName();
1503                 } break;
1504
1505                 case Settings.NameValueTable.VALUE: {
1506                     values[i] = setting.getValue();
1507                 } break;
1508             }
1509         }
1510
1511         cursor.addRow(values);
1512     }
1513
1514     private static boolean isKeyValid(String key) {
1515         return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1516     }
1517
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]*");
1521
1522         private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1523                 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1524
1525         private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1526                 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1527
1528         private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1529                 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1530
1531         public final String table;
1532         public final String name;
1533
1534         public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1535             final int segmentSize = uri.getPathSegments().size();
1536             switch (segmentSize) {
1537                 case 1: {
1538                     if (where != null
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);
1544                         return;
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);
1554                         return;
1555                     } else if (supportAll && where == null && whereArgs == null) {
1556                         name = null;
1557                         table = computeTableForSetting(uri, null);
1558                         return;
1559                     }
1560                 } break;
1561
1562                 case 2: {
1563                     if (where == null && whereArgs == null) {
1564                         name = uri.getPathSegments().get(1);
1565                         table = computeTableForSetting(uri, name);
1566                         return;
1567                     }
1568                 } break;
1569             }
1570
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);
1580         }
1581
1582         private static String computeTableForSetting(Uri uri, String name) {
1583             String table = getValidTableOrThrow(uri);
1584
1585             if (name != null) {
1586                 if (sSystemMovedToSecureSettings.contains(name)) {
1587                     table = TABLE_SECURE;
1588                 }
1589
1590                 if (sSystemMovedToGlobalSettings.contains(name)) {
1591                     table = TABLE_GLOBAL;
1592                 }
1593
1594                 if (sSecureMovedToGlobalSettings.contains(name)) {
1595                     table = TABLE_GLOBAL;
1596                 }
1597
1598                 if (sGlobalMovedToSecureSettings.contains(name)) {
1599                     table = TABLE_SECURE;
1600                 }
1601             }
1602
1603             return table;
1604         }
1605     }
1606
1607     final class SettingsRegistry {
1608         private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1609
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";
1613
1614         private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1615
1616         private GenerationRegistry mGenerationRegistry;
1617
1618         private final Handler mHandler;
1619
1620         private final BackupManager mBackupManager;
1621
1622         public SettingsRegistry() {
1623             mHandler = new MyHandler(getContext().getMainLooper());
1624             mGenerationRegistry = new GenerationRegistry(mLock);
1625             mBackupManager = new BackupManager(getContext());
1626             migrateAllLegacySettingsIfNeeded();
1627         }
1628
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();
1633         }
1634
1635         public SettingsState getSettingsLocked(int type, int userId) {
1636             final int key = makeKey(type, userId);
1637             return peekSettingsStateLocked(key);
1638         }
1639
1640         public void ensureSettingsForUserLocked(int userId) {
1641             // Migrate the setting for this user if needed.
1642             migrateLegacySettingsForUserIfNeededLocked(userId);
1643
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);
1648             }
1649
1650             // Ensure secure settings loaded.
1651             final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1652             ensureSettingsStateLocked(secureKey);
1653
1654             // Make sure the secure settings have an Android id set.
1655             SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1656             ensureSecureSettingAndroidIdSetLocked(secureSettings);
1657
1658             // Ensure system settings loaded.
1659             final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1660             ensureSettingsStateLocked(systemKey);
1661
1662             // Upgrade the settings to the latest version.
1663             UpgradeController upgrader = new UpgradeController(userId);
1664             upgrader.upgradeIfNeededLocked();
1665         }
1666
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);
1673             }
1674         }
1675
1676         public void removeUserStateLocked(int userId, boolean permanently) {
1677             // We always keep the global settings in memory.
1678
1679             // Nuke system settings.
1680             final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1681             final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1682             if (systemSettingsState != null) {
1683                 if (permanently) {
1684                     mSettingsStates.remove(systemKey);
1685                     systemSettingsState.destroyLocked(null);
1686                 } else {
1687                     systemSettingsState.destroyLocked(new Runnable() {
1688                         @Override
1689                         public void run() {
1690                             mSettingsStates.remove(systemKey);
1691                         }
1692                     });
1693                 }
1694             }
1695
1696             // Nuke secure settings.
1697             final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1698             final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1699             if (secureSettingsState != null) {
1700                 if (permanently) {
1701                     mSettingsStates.remove(secureKey);
1702                     secureSettingsState.destroyLocked(null);
1703                 } else {
1704                     secureSettingsState.destroyLocked(new Runnable() {
1705                         @Override
1706                         public void run() {
1707                             mSettingsStates.remove(secureKey);
1708                         }
1709                     });
1710                 }
1711             }
1712
1713             // Nuke generation tracking data
1714             mGenerationRegistry.onUserRemoved(userId);
1715         }
1716
1717         public boolean insertSettingLocked(int type, int userId, String name, String value,
1718                 String packageName, boolean forceNotify) {
1719             final int key = makeKey(type, userId);
1720
1721             SettingsState settingsState = peekSettingsStateLocked(key);
1722             final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1723
1724             if (forceNotify || success) {
1725                 notifyForSettingsChange(key, name);
1726             }
1727             return success;
1728         }
1729
1730         public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
1731             final int key = makeKey(type, userId);
1732
1733             SettingsState settingsState = peekSettingsStateLocked(key);
1734             final boolean success = settingsState.deleteSettingLocked(name);
1735
1736             if (forceNotify || success) {
1737                 notifyForSettingsChange(key, name);
1738             }
1739             return success;
1740         }
1741
1742         public Setting getSettingLocked(int type, int userId, String name) {
1743             final int key = makeKey(type, userId);
1744
1745             SettingsState settingsState = peekSettingsStateLocked(key);
1746             return settingsState.getSettingLocked(name);
1747         }
1748
1749         public boolean updateSettingLocked(int type, int userId, String name, String value,
1750                 String packageName, boolean forceNotify) {
1751             final int key = makeKey(type, userId);
1752
1753             SettingsState settingsState = peekSettingsStateLocked(key);
1754             final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1755
1756             if (forceNotify || success) {
1757                 notifyForSettingsChange(key, name);
1758             }
1759
1760             return success;
1761         }
1762
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.
1768
1769             final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1770             SettingsState systemSettings = mSettingsStates.get(systemKey);
1771             if (systemSettings != null) {
1772                 systemSettings.onPackageRemovedLocked(packageName);
1773             }
1774         }
1775
1776         private SettingsState peekSettingsStateLocked(int key) {
1777             SettingsState settingsState = mSettingsStates.get(key);
1778             if (settingsState != null) {
1779                 return settingsState;
1780             }
1781
1782             ensureSettingsForUserLocked(getUserIdFromKey(key));
1783             return mSettingsStates.get(key);
1784         }
1785
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()) {
1791                     return;
1792                 }
1793
1794                 final long identity = Binder.clearCallingIdentity();
1795                 try {
1796                     List<UserInfo> users = mUserManager.getUsers(true);
1797
1798                     final int userCount = users.size();
1799                     for (int i = 0; i < userCount; i++) {
1800                         final int userId = users.get(i).id;
1801
1802                         DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1803                         SQLiteDatabase database = dbHelper.getWritableDatabase();
1804                         migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1805
1806                         // Upgrade to the latest version.
1807                         UpgradeController upgrader = new UpgradeController(userId);
1808                         upgrader.upgradeIfNeededLocked();
1809
1810                         // Drop from memory if not a running user.
1811                         if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1812                             removeUserStateLocked(userId, false);
1813                         }
1814                     }
1815                 } finally {
1816                     Binder.restoreCallingIdentity(identity);
1817                 }
1818             }
1819         }
1820
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()) {
1826                 return;
1827             }
1828
1829             DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1830             SQLiteDatabase database = dbHelper.getWritableDatabase();
1831
1832             migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1833         }
1834
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();
1843
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();
1853
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();
1863             }
1864
1865             // Drop the database as now all is moved and persisted.
1866             if (DROP_DATABASE_ON_MIGRATION) {
1867                 dbHelper.dropDatabase();
1868             } else {
1869                 dbHelper.backupDatabase();
1870             }
1871         }
1872
1873         private void migrateLegacySettingsLocked(SettingsState settingsState,
1874                 SQLiteDatabase database, String table) {
1875             SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1876             queryBuilder.setTables(table);
1877
1878             Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1879                     null, null, null, null, null);
1880
1881             if (cursor == null) {
1882                 return;
1883             }
1884
1885             try {
1886                 if (!cursor.moveToFirst()) {
1887                     return;
1888                 }
1889
1890                 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1891                 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1892
1893                 settingsState.setVersionLocked(database.getVersion());
1894
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();
1901                 }
1902             } finally {
1903                 cursor.close();
1904             }
1905         }
1906
1907         private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1908             Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1909
1910             if (value != null) {
1911                 return;
1912             }
1913
1914             final int userId = getUserIdFromKey(secureSettings.mKey);
1915
1916             final UserInfo user;
1917             final long identity = Binder.clearCallingIdentity();
1918             try {
1919                 user = mUserManager.getUserInfo(userId);
1920             } finally {
1921                 Binder.restoreCallingIdentity(identity);
1922             }
1923             if (user == null) {
1924                 // Can happen due to races when deleting users - treat as benign.
1925                 return;
1926             }
1927
1928             String androidId = Long.toHexString(new SecureRandom().nextLong());
1929             secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1930                     SettingsState.SYSTEM_PACKAGE_NAME);
1931
1932             Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1933                     + "] for user " + userId);
1934
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");
1942                 }
1943             }
1944         }
1945
1946         private void notifyForSettingsChange(int key, String name) {
1947             final int userId = getUserIdFromKey(key);
1948             Uri uri = getNotificationUriFor(key, name);
1949
1950             mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1951                     userId, 0, uri).sendToTarget();
1952
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);
1959             }
1960
1961             mGenerationRegistry.incrementGeneration(key);
1962
1963             mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
1964         }
1965
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);
1976
1977                         mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
1978                     }
1979                 }
1980             }
1981         }
1982
1983         private boolean isGlobalSettingsKey(int key) {
1984             return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1985         }
1986
1987         private boolean isSystemSettingsKey(int key) {
1988             return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1989         }
1990
1991         private boolean isSecureSettingsKey(int key) {
1992             return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1993         }
1994
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);
2008             } else {
2009                 throw new IllegalArgumentException("Invalid settings key:" + key);
2010             }
2011         }
2012
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;
2023             } else {
2024                 throw new IllegalArgumentException("Invalid settings key:" + key);
2025             }
2026         }
2027
2028         private int getMaxBytesPerPackageForType(int type) {
2029             switch (type) {
2030                 case SETTINGS_TYPE_GLOBAL:
2031                 case SETTINGS_TYPE_SECURE: {
2032                     return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2033                 }
2034
2035                 default: {
2036                     return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2037                 }
2038             }
2039         }
2040
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;
2044
2045             public MyHandler(Looper looper) {
2046                 super(looper);
2047             }
2048
2049             @Override
2050             public void handleMessage(Message msg) {
2051                 switch (msg.what) {
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);
2056                         if (DEBUG) {
2057                             Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2058                         }
2059                     } break;
2060
2061                     case MSG_NOTIFY_DATA_CHANGED: {
2062                         mBackupManager.dataChanged();
2063                     } break;
2064                 }
2065             }
2066         }
2067
2068         private final class UpgradeController {
2069             private static final int SETTINGS_VERSION = 127;
2070
2071             private final int mUserId;
2072
2073             public UpgradeController(int userId) {
2074                 mUserId = userId;
2075             }
2076
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);
2081
2082                 // Try an update from the current state.
2083                 final int oldVersion = secureSettings.getVersionLocked();
2084                 final int newVersion = SETTINGS_VERSION;
2085
2086                 // If up do date - done.
2087                 if (oldVersion == newVersion) {
2088                     return;
2089                 }
2090
2091                 // Try to upgrade.
2092                 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2093
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);
2098
2099                     // Recreate the database.
2100                     DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2101                     SQLiteDatabase database = dbHelper.getWritableDatabase();
2102                     dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2103
2104                     // Migrate the settings for this user.
2105                     migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2106
2107                     // Now upgrade should work fine.
2108                     onUpgradeLocked(mUserId, oldVersion, newVersion);
2109                 }
2110
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);
2116                 }
2117
2118                 // Set the secure settings version.
2119                 secureSettings.setVersionLocked(newVersion);
2120
2121                 // Set the system settings version.
2122                 SettingsState systemSettings = getSettingsLocked(
2123                         SETTINGS_TYPE_SYSTEM, mUserId);
2124                 systemSettings.setVersionLocked(newVersion);
2125             }
2126
2127             private SettingsState getGlobalSettingsLocked() {
2128                 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
2129             }
2130
2131             private SettingsState getSecureSettingsLocked(int userId) {
2132                 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2133             }
2134
2135             private SettingsState getSystemSettingsLocked(int userId) {
2136                 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2137             }
2138
2139             /**
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.
2143              *
2144              * This is an example of moving a setting from secure to global.
2145              *
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);
2154              *
2155              *         // Add to the global settings.
2156              *         SettingsState globalSettings = getGlobalSettingsLocked();
2157              *         globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2158              *     }
2159              *
2160              *     // Update the current version.
2161              *     currentVersion = 119;
2162              * }
2163              */
2164             private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2165                 if (DEBUG) {
2166                     Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2167                             + oldVersion + " to version: " + newVersion);
2168                 }
2169
2170                 int currentVersion = oldVersion;
2171
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);
2182                     }
2183                     currentVersion = 119;
2184                 }
2185
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);
2193
2194                     currentVersion = 120;
2195                 }
2196
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;
2201                 }
2202
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,
2216                                 defaultComponent,
2217                                 SettingsState.SYSTEM_PACKAGE_NAME);
2218                     }
2219                     currentVersion = 122;
2220                 }
2221
2222                 if (currentVersion == 122) {
2223                     // Version 123: Adding a default value for the ability to add a user from
2224                     // the lock screen.
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);
2235                         }
2236                     }
2237                     currentVersion = 123;
2238                 }
2239
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;
2247                 }
2248
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);
2261                     }
2262                     currentVersion = 125;
2263                 }
2264
2265                 if (currentVersion == 125) {
2266                     // Version 125: Allow OEMs to set the default VR service.
2267                     final SettingsState secureSettings = getSecureSettingsLocked(userId);
2268
2269                     Setting currentSetting = secureSettings.getSettingLocked(
2270                             Settings.Secure.ENABLED_VR_LISTENERS);
2271                     if (currentSetting.isNull()) {
2272                         ArraySet<ComponentName> l =
2273                                 SystemConfig.getInstance().getDefaultVrComponents();
2274
2275                         if (l != null && !l.isEmpty()) {
2276                             StringBuilder b = new StringBuilder();
2277                             boolean start = true;
2278                             for (ComponentName c : l) {
2279                                 if (!start) {
2280                                     b.append(':');
2281                                 }
2282                                 b.append(c.flattenToString());
2283                                 start = false;
2284                             }
2285                             secureSettings.insertSettingLocked(
2286                                     Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2287                                     SettingsState.SYSTEM_PACKAGE_NAME);
2288                         }
2289
2290                     }
2291                     currentVersion = 126;
2292                 }
2293
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);
2300
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);
2309                         }
2310
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);
2319                         }
2320                     }
2321                     currentVersion = 127;
2322                 }
2323
2324                 // vXXX: Add new settings above this point.
2325
2326                 // Return the current version.
2327                 return currentVersion;
2328             }
2329         }
2330     }
2331 }