blob: 31c5b366ac6e2409ae00c03366fb976e375380a3 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
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
17package com.android.providers.settings;
18
Svetoslav683914b2015-01-15 14:22:26 -080019import android.Manifest;
Christopher Tated5fe1472012-09-10 15:48:38 -070020import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070021import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080022import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070023import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080024import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070026import android.content.ContentValues;
27import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.Intent;
29import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080030import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070031import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070034import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040040import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Svet Ganov53a441c2016-04-19 19:38:00 -070045import android.os.Debug;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070046import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080047import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070048import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070049import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Looper;
51import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070053import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070054import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070055import android.os.SELinux;
Christopher Tate06efb532012-08-24 15:29:27 -070056import android.os.UserHandle;
57import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070058import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059import android.provider.Settings;
60import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080061import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070062import android.util.Slog;
63import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040064
Svetoslav683914b2015-01-15 14:22:26 -080065import com.android.internal.annotations.GuardedBy;
66import com.android.internal.content.PackageMonitor;
67import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080068import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070069import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080070import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040071
Svetoslav683914b2015-01-15 14:22:26 -080072import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080073import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080074import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080075import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080076import java.security.SecureRandom;
77import java.util.Arrays;
78import java.util.List;
Svetoslav683914b2015-01-15 14:22:26 -080079import java.util.Set;
80import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070081
Svetoslav683914b2015-01-15 14:22:26 -080082/**
83 * <p>
84 * This class is a content provider that publishes the system settings.
85 * It can be accessed via the content provider APIs or via custom call
86 * commands. The latter is a bit faster and is the preferred way to access
87 * the platform settings.
88 * </p>
89 * <p>
90 * There are three settings types, global (with signature level protection
91 * and shared across users), secure (with signature permission level
92 * protection and per user), and system (with dangerous permission level
93 * protection and per user). Global settings are stored under the device owner.
94 * Each of these settings is represented by a {@link
95 * com.android.providers.settings.SettingsState} object mapped to an integer
96 * key derived from the setting type in the most significant bits and user
97 * id in the least significant bits. Settings are synchronously loaded on
98 * instantiation of a SettingsState and asynchronously persisted on mutation.
99 * Settings are stored in the user specific system directory.
100 * </p>
101 * <p>
102 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
103 * and get a warning. Targeting higher API version prohibits this as the
104 * system settings are not a place for apps to save their state. When a package
105 * is removed the settings it added are deleted. Apps cannot delete system
106 * settings added by the platform. System settings values are validated to
107 * ensure the clients do not put bad values. Global and secure settings are
108 * changed only by trusted parties, therefore no validation is performed. Also
109 * there is a limit on the amount of app specific settings that can be added
110 * to prevent unlimited growth of the system process memory footprint.
111 * </p>
112 */
113@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800115 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116
Svetoslav683914b2015-01-15 14:22:26 -0800117 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
118
119 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700120
Christopher Tate06efb532012-08-24 15:29:27 -0700121 private static final String TABLE_SYSTEM = "system";
122 private static final String TABLE_SECURE = "secure";
123 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800124
125 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final String TABLE_FAVORITES = "favorites";
127 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800128 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
129 private static final String TABLE_BOOKMARKS = "bookmarks";
130 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Svetoslav683914b2015-01-15 14:22:26 -0800132 // The set of removed legacy tables.
133 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700134 static {
Svetoslav683914b2015-01-15 14:22:26 -0800135 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
136 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
137 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
138 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
139 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
140 }
Christopher Tate06efb532012-08-24 15:29:27 -0700141
Svetoslav683914b2015-01-15 14:22:26 -0800142 private static final int MUTATION_OPERATION_INSERT = 1;
143 private static final int MUTATION_OPERATION_DELETE = 2;
144 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400145
Svetoslav683914b2015-01-15 14:22:26 -0800146 private static final String[] ALL_COLUMNS = new String[] {
147 Settings.NameValueTable._ID,
148 Settings.NameValueTable.NAME,
149 Settings.NameValueTable.VALUE
150 };
151
Svet Ganov53a441c2016-04-19 19:38:00 -0700152 public static final int SETTINGS_TYPE_GLOBAL = 0;
153 public static final int SETTINGS_TYPE_SYSTEM = 1;
154 public static final int SETTINGS_TYPE_SECURE = 2;
Svetoslav683914b2015-01-15 14:22:26 -0800155
Svet Ganov53a441c2016-04-19 19:38:00 -0700156 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
157 public static final int SETTINGS_TYPE_SHIFT = 28;
158
159 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
160 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700161
Svetoslav683914b2015-01-15 14:22:26 -0800162 // Per user secure settings that moved to the for all users global settings.
163 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
164 static {
165 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700166 }
167
Svetoslav683914b2015-01-15 14:22:26 -0800168 // Per user system settings that moved to the for all users global settings.
169 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
170 static {
171 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172 }
173
Svetoslav683914b2015-01-15 14:22:26 -0800174 // Per user system settings that moved to the per user secure settings.
175 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
176 static {
177 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 }
179
Svetoslav683914b2015-01-15 14:22:26 -0800180 // Per all users global settings that moved to the per user secure settings.
181 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
182 static {
183 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700184 }
185
Svetoslav683914b2015-01-15 14:22:26 -0800186 // Per user secure settings that are cloned for the managed profiles of the user.
187 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
188 static {
189 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700190 }
191
Svetoslav683914b2015-01-15 14:22:26 -0800192 // Per user system settings that are cloned for the managed profiles of the user.
193 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
194 static {
195 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400196 }
197
Svetoslav683914b2015-01-15 14:22:26 -0800198 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700199
Svetoslav683914b2015-01-15 14:22:26 -0800200 @GuardedBy("mLock")
201 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700202
Svet Ganova8f90262016-05-10 08:44:48 -0700203 @GuardedBy("mLock")
204 private HandlerThread mHandlerThread;
205
Svetoslav7ec28e82015-05-20 17:01:10 -0700206 // We have to call in the user manager with no lock held,
207 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800208
Svetoslav7ec28e82015-05-20 17:01:10 -0700209 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700210 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700211
Svet Ganov53a441c2016-04-19 19:38:00 -0700212 public static int makeKey(int type, int userId) {
213 return (type << SETTINGS_TYPE_SHIFT) | userId;
214 }
215
216 public static int getTypeFromKey(int key) {
217 return key >>> SETTINGS_TYPE_SHIFT;
218 }
219
220 public static int getUserIdFromKey(int key) {
221 return key & ~SETTINGS_TYPE_MASK;
222 }
223
224 public static String settingTypeToString(int type) {
225 switch (type) {
226 case SETTINGS_TYPE_GLOBAL: {
227 return "SETTINGS_GLOBAL";
228 }
229 case SETTINGS_TYPE_SECURE: {
230 return "SETTINGS_SECURE";
231 }
232 case SETTINGS_TYPE_SYSTEM: {
233 return "SETTINGS_SYSTEM";
234 }
235 default: {
236 return "UNKNOWN";
237 }
238 }
239 }
240
241 public static String keyToString(int key) {
242 return "Key[user=" + getUserIdFromKey(key) + ";type="
243 + settingTypeToString(getTypeFromKey(key)) + "]";
244 }
245
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 @Override
247 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800248 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700249 mUserManager = UserManager.get(getContext());
250 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700251 mHandlerThread = new HandlerThread(LOG_TAG,
252 Process.THREAD_PRIORITY_BACKGROUND);
253 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800254 mSettingsRegistry = new SettingsRegistry();
255 }
256 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700257 startWatchingUserRestrictionChanges();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 return true;
259 }
260
Svetoslav683914b2015-01-15 14:22:26 -0800261 @Override
262 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700263 final int requestingUserId = getRequestingUserId(args);
264 switch (method) {
265 case Settings.CALL_METHOD_GET_GLOBAL: {
266 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700267 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800268 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700269
270 case Settings.CALL_METHOD_GET_SECURE: {
271 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700272 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700273 }
274
275 case Settings.CALL_METHOD_GET_SYSTEM: {
276 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700277 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700278 }
279
280 case Settings.CALL_METHOD_PUT_GLOBAL: {
281 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700282 insertGlobalSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700283 break;
284 }
285
286 case Settings.CALL_METHOD_PUT_SECURE: {
287 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700288 insertSecureSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700289 break;
290 }
291
292 case Settings.CALL_METHOD_PUT_SYSTEM: {
293 String value = getSettingValue(args);
294 insertSystemSetting(name, value, requestingUserId);
295 break;
296 }
297
298 default: {
299 Slog.w(LOG_TAG, "call() with invalid method: " + method);
300 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700301 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700302
Christopher Tate06efb532012-08-24 15:29:27 -0700303 return null;
304 }
305
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800306 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800307 public String getType(Uri uri) {
308 Arguments args = new Arguments(uri, null, null, true);
309 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 return "vnd.android.cursor.dir/" + args.table;
311 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700312 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700313 }
314 }
315
316 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800317 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
318 String order) {
319 if (DEBUG) {
320 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 }
322
Svetoslav683914b2015-01-15 14:22:26 -0800323 Arguments args = new Arguments(uri, where, whereArgs, true);
324 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325
Svetoslav683914b2015-01-15 14:22:26 -0800326 // If a legacy table that is gone, done.
327 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
328 return new MatrixCursor(normalizedProjection, 0);
329 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700330
Svetoslav7ec28e82015-05-20 17:01:10 -0700331 switch (args.table) {
332 case TABLE_GLOBAL: {
333 if (args.name != null) {
334 Setting setting = getGlobalSetting(args.name);
335 return packageSettingForQuery(setting, normalizedProjection);
336 } else {
337 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700338 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700339 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700340
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 case TABLE_SECURE: {
342 final int userId = UserHandle.getCallingUserId();
343 if (args.name != null) {
344 Setting setting = getSecureSetting(args.name, userId);
345 return packageSettingForQuery(setting, normalizedProjection);
346 } else {
347 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800348 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700349 }
Svetoslav683914b2015-01-15 14:22:26 -0800350
Svetoslav7ec28e82015-05-20 17:01:10 -0700351 case TABLE_SYSTEM: {
352 final int userId = UserHandle.getCallingUserId();
353 if (args.name != null) {
354 Setting setting = getSystemSetting(args.name, userId);
355 return packageSettingForQuery(setting, normalizedProjection);
356 } else {
357 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800358 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700359 }
Svetoslav683914b2015-01-15 14:22:26 -0800360
Svetoslav7ec28e82015-05-20 17:01:10 -0700361 default: {
362 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700363 }
364 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700365 }
366
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800368 public Uri insert(Uri uri, ContentValues values) {
369 if (DEBUG) {
370 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700371 }
372
Svetoslav683914b2015-01-15 14:22:26 -0800373 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700374
Svetoslav683914b2015-01-15 14:22:26 -0800375 // If a legacy table that is gone, done.
376 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 return null;
378 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379
Svetoslav683914b2015-01-15 14:22:26 -0800380 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700381 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800382 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700383 }
384
Svetoslav683914b2015-01-15 14:22:26 -0800385 String value = values.getAsString(Settings.Secure.VALUE);
386
Svetoslav7ec28e82015-05-20 17:01:10 -0700387 switch (table) {
388 case TABLE_GLOBAL: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700389 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700390 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700391 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700392 } break;
393
394 case TABLE_SECURE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700395 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
397 }
398 } break;
399
400 case TABLE_SYSTEM: {
401 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
402 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
403 }
404 } break;
405
406 default: {
407 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700408 }
409 }
410
Svetoslav683914b2015-01-15 14:22:26 -0800411 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700412 }
413
414 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800415 public int bulkInsert(Uri uri, ContentValues[] allValues) {
416 if (DEBUG) {
417 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700419
Svetoslav683914b2015-01-15 14:22:26 -0800420 int insertionCount = 0;
421 final int valuesCount = allValues.length;
422 for (int i = 0; i < valuesCount; i++) {
423 ContentValues values = allValues[i];
424 if (insert(uri, values) != null) {
425 insertionCount++;
426 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700427 }
Svetoslav683914b2015-01-15 14:22:26 -0800428
429 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430 }
431
432 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800433 public int delete(Uri uri, String where, String[] whereArgs) {
434 if (DEBUG) {
435 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700437
Svetoslav683914b2015-01-15 14:22:26 -0800438 Arguments args = new Arguments(uri, where, whereArgs, false);
439
440 // If a legacy table that is gone, done.
441 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
442 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700443 }
Svetoslav683914b2015-01-15 14:22:26 -0800444
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700445 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800446 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700447 }
Svetoslav683914b2015-01-15 14:22:26 -0800448
Svetoslav7ec28e82015-05-20 17:01:10 -0700449 switch (args.table) {
450 case TABLE_GLOBAL: {
451 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700452 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 }
Svetoslav683914b2015-01-15 14:22:26 -0800454
Svetoslav7ec28e82015-05-20 17:01:10 -0700455 case TABLE_SECURE: {
456 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700457 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700458 }
Svetoslav683914b2015-01-15 14:22:26 -0800459
Svetoslav7ec28e82015-05-20 17:01:10 -0700460 case TABLE_SYSTEM: {
461 final int userId = UserHandle.getCallingUserId();
462 return deleteSystemSetting(args.name, userId) ? 1 : 0;
463 }
464
465 default: {
466 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800467 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700468 }
Svetoslav683914b2015-01-15 14:22:26 -0800469 }
470
471 @Override
472 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
473 if (DEBUG) {
474 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700475 }
Svetoslav683914b2015-01-15 14:22:26 -0800476
477 Arguments args = new Arguments(uri, where, whereArgs, false);
478
479 // If a legacy table that is gone, done.
480 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
481 return 0;
482 }
483
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700484 String name = values.getAsString(Settings.Secure.NAME);
485 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800486 return 0;
487 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700488 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800489
Svetoslav7ec28e82015-05-20 17:01:10 -0700490 switch (args.table) {
491 case TABLE_GLOBAL: {
492 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700493 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700494 }
Svetoslav683914b2015-01-15 14:22:26 -0800495
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 case TABLE_SECURE: {
497 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700498 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700499 }
Svetoslav683914b2015-01-15 14:22:26 -0800500
Svetoslav7ec28e82015-05-20 17:01:10 -0700501 case TABLE_SYSTEM: {
502 final int userId = UserHandle.getCallingUserId();
503 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
504 }
Svetoslav683914b2015-01-15 14:22:26 -0800505
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 default: {
507 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800508 }
509 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700510 }
511
512 @Override
513 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey413573a2016-02-22 17:52:45 -0700514 final String cacheName;
515 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
516 cacheName = Settings.System.RINGTONE_CACHE;
517 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
518 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
519 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
520 cacheName = Settings.System.ALARM_ALERT_CACHE;
521 } else {
522 throw new FileNotFoundException("Direct file access no longer supported; "
523 + "ringtone playback is available through android.media.Ringtone");
524 }
525
526 final File cacheFile = new File(
527 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
528 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
529 }
530
531 private File getRingtoneCacheDir(int userId) {
532 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
533 cacheDir.mkdir();
534 SELinux.restorecon(cacheDir);
535 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700536 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800537
Svetoslavb505ccc2015-02-17 12:41:04 -0800538 @Override
539 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
540 synchronized (mLock) {
541 final long identity = Binder.clearCallingIdentity();
542 try {
543 List<UserInfo> users = mUserManager.getUsers(true);
544 final int userCount = users.size();
545 for (int i = 0; i < userCount; i++) {
546 UserInfo user = users.get(i);
547 dumpForUser(user.id, pw);
548 }
549 } finally {
550 Binder.restoreCallingIdentity(identity);
551 }
552 }
553 }
554
555 private void dumpForUser(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700556 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800557 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700558 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800559 dumpSettings(globalCursor, pw);
560 pw.println();
561 }
562
563 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700564 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800565 dumpSettings(secureCursor, pw);
566 pw.println();
567
568 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700569 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800570 dumpSettings(systemCursor, pw);
571 pw.println();
572 }
573
574 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700575 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800576 return;
577 }
578
579 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
580 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
581 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
582
583 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700584 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
585 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
586 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800587 pw.println();
588 } while (cursor.moveToNext());
589 }
590
Svetoslav7e0683b2015-08-03 16:02:52 -0700591 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700592 if (s != null) {
593 return s;
594 }
595 return "{null}";
596 }
597
Svetoslav683914b2015-01-15 14:22:26 -0800598 private void registerBroadcastReceivers() {
599 IntentFilter userFilter = new IntentFilter();
600 userFilter.addAction(Intent.ACTION_USER_REMOVED);
601 userFilter.addAction(Intent.ACTION_USER_STOPPED);
602
603 getContext().registerReceiver(new BroadcastReceiver() {
604 @Override
605 public void onReceive(Context context, Intent intent) {
606 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700607 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800608
609 switch (intent.getAction()) {
610 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700611 synchronized (mLock) {
612 mSettingsRegistry.removeUserStateLocked(userId, true);
613 }
Svetoslav683914b2015-01-15 14:22:26 -0800614 } break;
615
616 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700617 synchronized (mLock) {
618 mSettingsRegistry.removeUserStateLocked(userId, false);
619 }
Svetoslav683914b2015-01-15 14:22:26 -0800620 } break;
621 }
622 }
623 }, userFilter);
624
625 PackageMonitor monitor = new PackageMonitor() {
626 @Override
627 public void onPackageRemoved(String packageName, int uid) {
628 synchronized (mLock) {
629 mSettingsRegistry.onPackageRemovedLocked(packageName,
630 UserHandle.getUserId(uid));
631 }
632 }
633 };
634
635 // package changes
636 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
637 UserHandle.ALL, true);
638 }
639
Svet Ganov53a441c2016-04-19 19:38:00 -0700640 private void startWatchingUserRestrictionChanges() {
641 // TODO: The current design of settings looking different based on user restrictions
642 // should be reworked to keep them separate and system code should check the setting
643 // first followed by checking the user restriction before performing an operation.
644 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
645 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
646 Bundle prevRestrictions) -> {
647 // We are changing the settings affected by restrictions to their current
648 // value with a forced update to ensure that all cross profile dependencies
649 // are taken into account. Also make sure the settings update to.. the same
650 // value passes the security checks, so clear binder calling id.
651 if (newRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)
652 != prevRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)) {
653 final long identity = Binder.clearCallingIdentity();
654 try {
655 synchronized (mLock) {
656 Setting setting = getSecureSetting(
657 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
658 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
659 setting != null ? setting.getValue() : null, userId, true);
660 }
661 } finally {
662 Binder.restoreCallingIdentity(identity);
663 }
664 }
665 if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
666 != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
667 final long identity = Binder.clearCallingIdentity();
668 try {
669 synchronized (mLock) {
670 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
671 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
672 setting != null ? setting.getValue() : null, userId, true);
673 }
674 } finally {
675 Binder.restoreCallingIdentity(identity);
676 }
677 }
678 if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
679 != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
680 final long identity = Binder.clearCallingIdentity();
681 try {
682 synchronized (mLock) {
683 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
684 updateGlobalSetting(Settings.Global.ADB_ENABLED,
685 setting != null ? setting.getValue() : null, userId, true);
686 }
687 } finally {
688 Binder.restoreCallingIdentity(identity);
689 }
690 }
691 if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
692 != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
693 final long identity = Binder.clearCallingIdentity();
694 try {
695 synchronized (mLock) {
696 Setting enable = getGlobalSetting(
697 Settings.Global.PACKAGE_VERIFIER_ENABLE);
698 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
699 enable != null ? enable.getValue() : null, userId, true);
700 Setting include = getGlobalSetting(
701 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
702 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
703 include != null ? include.getValue() : null, userId, true);
704 }
705 } finally {
706 Binder.restoreCallingIdentity(identity);
707 }
708 }
709 if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
710 != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
711 final long identity = Binder.clearCallingIdentity();
712 try {
713 synchronized (mLock) {
714 Setting setting = getGlobalSetting(
715 Settings.Global.PREFERRED_NETWORK_MODE);
716 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
717 setting != null ? setting.getValue() : null, userId, true);
718 }
719 } finally {
720 Binder.restoreCallingIdentity(identity);
721 }
722 }
723 });
724 }
725
Svetoslav7ec28e82015-05-20 17:01:10 -0700726 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800727 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700728 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800729 }
730
Svetoslav7ec28e82015-05-20 17:01:10 -0700731 synchronized (mLock) {
732 // Get the settings.
733 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700734 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800735
Svetoslav7ec28e82015-05-20 17:01:10 -0700736 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800737
Svetoslav7ec28e82015-05-20 17:01:10 -0700738 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800739
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 String[] normalizedProjection = normalizeProjection(projection);
741 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800742
Svetoslav7ec28e82015-05-20 17:01:10 -0700743 // Anyone can get the global settings, so no security checks.
744 for (int i = 0; i < nameCount; i++) {
745 String name = names.get(i);
746 Setting setting = settingsState.getSettingLocked(name);
747 appendSettingToCursor(result, setting);
748 }
749
750 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800751 }
Svetoslav683914b2015-01-15 14:22:26 -0800752 }
753
Svetoslav7ec28e82015-05-20 17:01:10 -0700754 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800755 if (DEBUG) {
756 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
757 }
758
759 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700760 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700761 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700762 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800763 }
Svetoslav683914b2015-01-15 14:22:26 -0800764 }
765
Svet Ganov53a441c2016-04-19 19:38:00 -0700766 private boolean updateGlobalSetting(String name, String value, int requestingUserId,
767 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800768 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700769 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800770 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700771 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
772 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800773 }
774
Svet Ganov53a441c2016-04-19 19:38:00 -0700775 private boolean insertGlobalSetting(String name, String value, int requestingUserId,
776 boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700777 if (DEBUG) {
778 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
779 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700780 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
781 forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700782 }
783
Svet Ganov53a441c2016-04-19 19:38:00 -0700784 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800785 if (DEBUG) {
786 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
787 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700788 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
789 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800790 }
791
Svetoslav7ec28e82015-05-20 17:01:10 -0700792 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700793 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800794 // Make sure the caller can change the settings - treated as secure.
795 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
796
Svetoslav683914b2015-01-15 14:22:26 -0800797 // Resolve the userId on whose behalf the call is made.
798 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
799
Makoto Onuki28da2e32015-11-20 11:30:44 -0800800 // If this is a setting that is currently restricted for this user, do not allow
801 // unrestricting changes.
Victor Chang9c7b7062016-07-12 23:47:29 +0100802 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
803 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800804 return false;
805 }
806
807 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700808 synchronized (mLock) {
809 switch (operation) {
810 case MUTATION_OPERATION_INSERT: {
811 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700812 .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
813 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700814 }
Svetoslav683914b2015-01-15 14:22:26 -0800815
Svetoslav7ec28e82015-05-20 17:01:10 -0700816 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
818 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700819 }
Svetoslav683914b2015-01-15 14:22:26 -0800820
Svetoslav7ec28e82015-05-20 17:01:10 -0700821 case MUTATION_OPERATION_UPDATE: {
822 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700823 .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
824 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700825 }
Svetoslav683914b2015-01-15 14:22:26 -0800826 }
827 }
828
829 return false;
830 }
831
Svetoslav7ec28e82015-05-20 17:01:10 -0700832 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800833 if (DEBUG) {
834 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
835 }
836
837 // Resolve the userId on whose behalf the call is made.
838 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
839
Svetoslav7ec28e82015-05-20 17:01:10 -0700840 synchronized (mLock) {
841 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700842 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800843
Svetoslav7ec28e82015-05-20 17:01:10 -0700844 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800845
Svetoslav7ec28e82015-05-20 17:01:10 -0700846 String[] normalizedProjection = normalizeProjection(projection);
847 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800848
Svetoslav7ec28e82015-05-20 17:01:10 -0700849 for (int i = 0; i < nameCount; i++) {
850 String name = names.get(i);
851 // Determine the owning user as some profile settings are cloned from the parent.
852 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
853 name);
Svetoslav683914b2015-01-15 14:22:26 -0800854
Svetoslav7ec28e82015-05-20 17:01:10 -0700855 // Special case for location (sigh).
856 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700857 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700858 }
Svetoslav683914b2015-01-15 14:22:26 -0800859
Svetoslav7ec28e82015-05-20 17:01:10 -0700860 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700861 SETTINGS_TYPE_SECURE, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700862 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800863 }
864
Svetoslav7ec28e82015-05-20 17:01:10 -0700865 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800866 }
Svetoslav683914b2015-01-15 14:22:26 -0800867 }
868
Svetoslav7ec28e82015-05-20 17:01:10 -0700869 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800870 if (DEBUG) {
871 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
872 }
873
874 // Resolve the userId on whose behalf the call is made.
875 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
876
877 // Determine the owning user as some profile settings are cloned from the parent.
878 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
879
880 // Special case for location (sigh).
881 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700882 return mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
883 owningUserId).getNullSetting();
Svetoslav683914b2015-01-15 14:22:26 -0800884 }
885
886 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700888 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -0700889 owningUserId, name);
890 }
Svetoslav683914b2015-01-15 14:22:26 -0800891 }
892
Svet Ganov53a441c2016-04-19 19:38:00 -0700893 private boolean insertSecureSetting(String name, String value, int requestingUserId,
894 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800895 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700896 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800897 + requestingUserId + ")");
898 }
899
Svet Ganov53a441c2016-04-19 19:38:00 -0700900 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
901 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800902 }
903
Svet Ganov53a441c2016-04-19 19:38:00 -0700904 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800905 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700906 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800907 }
908
Svet Ganov53a441c2016-04-19 19:38:00 -0700909 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
910 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800911 }
912
Svet Ganov53a441c2016-04-19 19:38:00 -0700913 private boolean updateSecureSetting(String name, String value, int requestingUserId,
914 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800915 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700916 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800917 + requestingUserId + ")");
918 }
919
Svet Ganov53a441c2016-04-19 19:38:00 -0700920 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
921 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800922 }
923
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700925 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800926 // Make sure the caller can change the settings.
927 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
928
Svetoslav683914b2015-01-15 14:22:26 -0800929 // Resolve the userId on whose behalf the call is made.
930 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
931
Makoto Onuki28da2e32015-11-20 11:30:44 -0800932 // If this is a setting that is currently restricted for this user, do not allow
933 // unrestricting changes.
Victor Chang9c7b7062016-07-12 23:47:29 +0100934 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
935 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800936 return false;
937 }
938
939 // Determine the owning user as some profile settings are cloned from the parent.
940 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
941
942 // Only the owning user can change the setting.
943 if (owningUserId != callingUserId) {
944 return false;
945 }
946
947 // Special cases for location providers (sigh).
948 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700949 return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800950 }
951
952 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700953 synchronized (mLock) {
954 switch (operation) {
955 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700956 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
957 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700958 }
Svetoslav683914b2015-01-15 14:22:26 -0800959
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700961 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
962 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700963 }
Svetoslav683914b2015-01-15 14:22:26 -0800964
Svetoslav7ec28e82015-05-20 17:01:10 -0700965 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700966 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
967 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700968 }
Svetoslav683914b2015-01-15 14:22:26 -0800969 }
970 }
971
972 return false;
973 }
974
Svetoslav7ec28e82015-05-20 17:01:10 -0700975 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800976 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700977 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800978 }
979
980 // Resolve the userId on whose behalf the call is made.
981 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
982
Svetoslav7ec28e82015-05-20 17:01:10 -0700983 synchronized (mLock) {
984 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700985 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800986
Svetoslav7ec28e82015-05-20 17:01:10 -0700987 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800988
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 String[] normalizedProjection = normalizeProjection(projection);
990 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800991
Svetoslav7ec28e82015-05-20 17:01:10 -0700992 for (int i = 0; i < nameCount; i++) {
993 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800994
Svetoslav7ec28e82015-05-20 17:01:10 -0700995 // Determine the owning user as some profile settings are cloned from the parent.
996 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
997 name);
Svetoslav683914b2015-01-15 14:22:26 -0800998
Svetoslav7ec28e82015-05-20 17:01:10 -0700999 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001000 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001001 appendSettingToCursor(result, setting);
1002 }
1003
1004 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001005 }
Svetoslav683914b2015-01-15 14:22:26 -08001006 }
1007
Svetoslav7ec28e82015-05-20 17:01:10 -07001008 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001009 if (DEBUG) {
1010 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1011 }
1012
1013 // Resolve the userId on whose behalf the call is made.
1014 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1015
1016 // Determine the owning user as some profile settings are cloned from the parent.
1017 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1018
1019 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001020 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001021 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001022 }
Svetoslav683914b2015-01-15 14:22:26 -08001023 }
1024
Svetoslav7ec28e82015-05-20 17:01:10 -07001025 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001026 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001027 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001028 + requestingUserId + ")");
1029 }
1030
Svetoslav7ec28e82015-05-20 17:01:10 -07001031 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001032 }
1033
Svetoslav7ec28e82015-05-20 17:01:10 -07001034 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001035 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001036 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001037 }
1038
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001040 }
1041
Svetoslav7ec28e82015-05-20 17:01:10 -07001042 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001043 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001044 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001045 + requestingUserId + ")");
1046 }
1047
Svetoslav7ec28e82015-05-20 17:01:10 -07001048 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001049 }
1050
Svetoslav7ec28e82015-05-20 17:01:10 -07001051 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001052 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001053 if (!hasWriteSecureSettingsPermission()) {
1054 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1055 // operation is allowed for the calling package through appops.
1056 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1057 Binder.getCallingUid(), getCallingPackage(), true)) {
1058 return false;
1059 }
Svetoslav683914b2015-01-15 14:22:26 -08001060 }
1061
Svetoslav683914b2015-01-15 14:22:26 -08001062 // Resolve the userId on whose behalf the call is made.
1063 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1064
Svetoslavd8d25e02015-11-20 13:09:26 -08001065 // Enforce what the calling package can mutate the system settings.
1066 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1067
Svetoslav683914b2015-01-15 14:22:26 -08001068 // Determine the owning user as some profile settings are cloned from the parent.
1069 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1070
1071 // Only the owning user id can change the setting.
1072 if (owningUserId != callingUserId) {
1073 return false;
1074 }
1075
Jeff Sharkey413573a2016-02-22 17:52:45 -07001076 // Invalidate any relevant cache files
1077 String cacheName = null;
1078 if (Settings.System.RINGTONE.equals(name)) {
1079 cacheName = Settings.System.RINGTONE_CACHE;
1080 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1081 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1082 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1083 cacheName = Settings.System.ALARM_ALERT_CACHE;
1084 }
1085 if (cacheName != null) {
1086 final File cacheFile = new File(
1087 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
1088 cacheFile.delete();
1089 }
1090
Svetoslav683914b2015-01-15 14:22:26 -08001091 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001092 synchronized (mLock) {
1093 switch (operation) {
1094 case MUTATION_OPERATION_INSERT: {
1095 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001096 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
1097 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001098 }
1099
1100 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001101 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1102 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001103 }
1104
1105 case MUTATION_OPERATION_UPDATE: {
1106 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001107 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1108 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001109 }
Svetoslav683914b2015-01-15 14:22:26 -08001110 }
1111
Svetoslav7ec28e82015-05-20 17:01:10 -07001112 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001113 }
Svetoslav683914b2015-01-15 14:22:26 -08001114 }
1115
Billy Lau6ad2d662015-07-18 00:26:58 +01001116 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001117 // Write secure settings is a more protected permission. If caller has it we are good.
1118 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1119 == PackageManager.PERMISSION_GRANTED) {
1120 return true;
1121 }
1122
Svetoslavf41334b2015-06-23 12:06:03 -07001123 return false;
1124 }
1125
Svetoslav683914b2015-01-15 14:22:26 -08001126 private void validateSystemSettingValue(String name, String value) {
1127 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1128 if (validator != null && !validator.validate(value)) {
1129 throw new IllegalArgumentException("Invalid value: " + value
1130 + " for setting: " + name);
1131 }
1132 }
1133
1134 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1135 int owningUserId) {
1136 // Optimization - location providers are restricted only for managed profiles.
1137 if (callingUserId == owningUserId) {
1138 return false;
1139 }
1140 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1141 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1142 new UserHandle(callingUserId))) {
1143 return true;
1144 }
1145 return false;
1146 }
1147
Makoto Onuki28da2e32015-11-20 11:30:44 -08001148 /**
1149 * Checks whether changing a setting to a value is prohibited by the corresponding user
1150 * restriction.
1151 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001152 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1153 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001154 *
1155 * @return true if the change is prohibited, false if the change is allowed.
1156 */
1157 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001158 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001159 String restriction;
1160 switch (setting) {
1161 case Settings.Secure.LOCATION_MODE:
1162 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1163 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1164 // here normally, but we still protect it here from a direct provider write.
1165 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1166 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1167 break;
1168
1169 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1170 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1171 // a provider, which should be allowed even if the user restriction is set.
1172 if (value != null && value.startsWith("-")) return false;
1173 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1174 break;
1175
1176 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1177 if ("0".equals(value)) return false;
1178 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1179 break;
1180
1181 case Settings.Global.ADB_ENABLED:
1182 if ("0".equals(value)) return false;
1183 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1184 break;
1185
1186 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1187 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1188 if ("1".equals(value)) return false;
1189 restriction = UserManager.ENSURE_VERIFY_APPS;
1190 break;
1191
1192 case Settings.Global.PREFERRED_NETWORK_MODE:
1193 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1194 break;
1195
Victor Chang9c7b7062016-07-12 23:47:29 +01001196 case Settings.Secure.ALWAYS_ON_VPN_APP:
1197 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1198 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
1199 if (callingUid == Process.SYSTEM_UID || callingUid == Process.ROOT_UID) {
1200 return false;
1201 }
1202 restriction = UserManager.DISALLOW_CONFIG_VPN;
1203 break;
1204
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001205 case Settings.Global.SAFE_BOOT_DISALLOWED:
1206 if ("1".equals(value)) return false;
1207 restriction = UserManager.DISALLOW_SAFE_BOOT;
1208 break;
1209
Makoto Onuki28da2e32015-11-20 11:30:44 -08001210 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001211 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001212 if ("0".equals(value)) return false;
1213 restriction = UserManager.DISALLOW_DATA_ROAMING;
1214 break;
1215 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001216 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001217 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001218
1219 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001220 }
1221
1222 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1223 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1224 }
1225
1226 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1227 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1228 }
1229
1230 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1231 final int parentId = getGroupParentLocked(userId);
1232 if (parentId != userId && keys.contains(name)) {
1233 return parentId;
1234 }
1235 return userId;
1236 }
1237
Svetoslavf41334b2015-06-23 12:06:03 -07001238 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001239 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001240 // System/root/shell can mutate whatever secure settings they want.
1241 final int callingUid = Binder.getCallingUid();
1242 if (callingUid == android.os.Process.SYSTEM_UID
1243 || callingUid == Process.SHELL_UID
1244 || callingUid == Process.ROOT_UID) {
1245 return;
1246 }
1247
1248 switch (operation) {
1249 case MUTATION_OPERATION_INSERT:
1250 // Insert updates.
1251 case MUTATION_OPERATION_UPDATE: {
1252 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1253 return;
1254 }
1255
1256 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001257 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001258
1259 // Privileged apps can do whatever they want.
1260 if ((packageInfo.applicationInfo.privateFlags
1261 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1262 return;
1263 }
1264
1265 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1266 packageInfo.applicationInfo.targetSdkVersion, name);
1267 } break;
1268
1269 case MUTATION_OPERATION_DELETE: {
1270 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1271 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1272 throw new IllegalArgumentException("You cannot delete system defined"
1273 + " secure settings.");
1274 }
1275
1276 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001277 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001278
1279 // Privileged apps can do whatever they want.
1280 if ((packageInfo.applicationInfo.privateFlags &
1281 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1282 return;
1283 }
1284
1285 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1286 packageInfo.applicationInfo.targetSdkVersion, name);
1287 } break;
1288 }
1289 }
1290
Xiaohui Chen43765b72015-08-31 10:57:33 -07001291 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001292 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001293 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1294 getCallingPackage(), 0, userId);
1295 if (packageInfo != null) {
1296 return packageInfo;
1297 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001298 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001299 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001300 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001301 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001302 }
1303
1304 private int getGroupParentLocked(int userId) {
1305 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001306 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001307 return userId;
1308 }
1309 // We are in the same process with the user manager and the returned
1310 // user info is a cached instance, so just look up instead of cache.
1311 final long identity = Binder.clearCallingIdentity();
1312 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001313 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001314 UserInfo userInfo = mUserManager.getProfileParent(userId);
1315 return (userInfo != null) ? userInfo.id : userId;
1316 } finally {
1317 Binder.restoreCallingIdentity(identity);
1318 }
1319 }
1320
Svetoslav683914b2015-01-15 14:22:26 -08001321 private void enforceWritePermission(String permission) {
1322 if (getContext().checkCallingOrSelfPermission(permission)
1323 != PackageManager.PERMISSION_GRANTED) {
1324 throw new SecurityException("Permission denial: writing to settings requires:"
1325 + permission);
1326 }
1327 }
1328
1329 /*
1330 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1331 * This setting contains a list of the currently enabled location providers.
1332 * But helper functions in android.providers.Settings can enable or disable
1333 * a single provider by using a "+" or "-" prefix before the provider name.
1334 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001335 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1336 * is set, the said method will only allow values with the "-" prefix.
1337 *
Svetoslav683914b2015-01-15 14:22:26 -08001338 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001339 */
Svet Ganov53a441c2016-04-19 19:38:00 -07001340 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1341 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001342 if (TextUtils.isEmpty(value)) {
1343 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001344 }
1345
Svetoslav683914b2015-01-15 14:22:26 -08001346 final char prefix = value.charAt(0);
1347 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001348 if (forceNotify) {
1349 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1350 mSettingsRegistry.notifyForSettingsChange(key,
1351 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1352 }
Svetoslav683914b2015-01-15 14:22:26 -08001353 return false;
1354 }
1355
1356 // skip prefix
1357 value = value.substring(1);
1358
Svetoslav7ec28e82015-05-20 17:01:10 -07001359 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001360 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1361
1362 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1363
1364 int index = oldProviders.indexOf(value);
1365 int end = index + value.length();
1366
1367 // check for commas to avoid matching on partial string
1368 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1369 index = -1;
1370 }
1371
1372 // check for commas to avoid matching on partial string
1373 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1374 index = -1;
1375 }
1376
1377 String newProviders;
1378
1379 if (prefix == '+' && index < 0) {
1380 // append the provider to the list if not present
1381 if (oldProviders.length() == 0) {
1382 newProviders = value;
1383 } else {
1384 newProviders = oldProviders + ',' + value;
1385 }
1386 } else if (prefix == '-' && index >= 0) {
1387 // remove the provider from the list if present
1388 // remove leading or trailing comma
1389 if (index > 0) {
1390 index--;
1391 } else if (end < oldProviders.length()) {
1392 end++;
1393 }
1394
1395 newProviders = oldProviders.substring(0, index);
1396 if (end < oldProviders.length()) {
1397 newProviders += oldProviders.substring(end);
1398 }
1399 } else {
1400 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001401 if (forceNotify) {
1402 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1403 mSettingsRegistry.notifyForSettingsChange(key,
1404 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1405 }
Svetoslav683914b2015-01-15 14:22:26 -08001406 return false;
1407 }
1408
Svet Ganov53a441c2016-04-19 19:38:00 -07001409 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001410 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svet Ganov53a441c2016-04-19 19:38:00 -07001411 getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001412 }
1413
Svetoslav683914b2015-01-15 14:22:26 -08001414 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1415 int targetSdkVersion, String name) {
1416 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1417 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1418 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1419 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1420 + " This will soon become an error.");
1421 } else {
1422 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1423 + " This will soon become an error.");
1424 }
1425 } else {
1426 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1427 throw new IllegalArgumentException("You cannot change private secure settings.");
1428 } else {
1429 throw new IllegalArgumentException("You cannot keep your settings in"
1430 + " the secure settings.");
1431 }
1432 }
1433 }
1434
1435 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1436 if (requestingUserId == UserHandle.getCallingUserId()) {
1437 return requestingUserId;
1438 }
1439 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1440 Binder.getCallingUid(), requestingUserId, false, true,
1441 "get/set setting for user", null);
1442 }
1443
Svet Ganov53a441c2016-04-19 19:38:00 -07001444 private Bundle packageValueForCallResult(Setting setting,
1445 boolean trackingGeneration) {
1446 if (!trackingGeneration) {
1447 if (setting.isNull()) {
1448 return NULL_SETTING_BUNDLE;
1449 }
1450 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001451 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001452 Bundle result = new Bundle();
1453 result.putString(Settings.NameValueTable.VALUE,
1454 !setting.isNull() ? setting.getValue() : null);
1455 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1456 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001457 }
1458
1459 private static int getRequestingUserId(Bundle args) {
1460 final int callingUserId = UserHandle.getCallingUserId();
1461 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1462 : callingUserId;
1463 }
1464
Svet Ganov53a441c2016-04-19 19:38:00 -07001465 private boolean isTrackingGeneration(Bundle args) {
1466 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1467 }
1468
Svetoslav683914b2015-01-15 14:22:26 -08001469 private static String getSettingValue(Bundle args) {
1470 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1471 }
1472
1473 private static String getValidTableOrThrow(Uri uri) {
1474 if (uri.getPathSegments().size() > 0) {
1475 String table = uri.getPathSegments().get(0);
1476 if (DatabaseHelper.isValidTable(table)) {
1477 return table;
1478 }
1479 throw new IllegalArgumentException("Bad root path: " + table);
1480 }
1481 throw new IllegalArgumentException("Invalid URI:" + uri);
1482 }
1483
1484 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001485 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001486 return new MatrixCursor(projection, 0);
1487 }
1488 MatrixCursor cursor = new MatrixCursor(projection, 1);
1489 appendSettingToCursor(cursor, setting);
1490 return cursor;
1491 }
1492
1493 private static String[] normalizeProjection(String[] projection) {
1494 if (projection == null) {
1495 return ALL_COLUMNS;
1496 }
1497
1498 final int columnCount = projection.length;
1499 for (int i = 0; i < columnCount; i++) {
1500 String column = projection[i];
1501 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1502 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001503 }
1504 }
1505
Svetoslav683914b2015-01-15 14:22:26 -08001506 return projection;
1507 }
1508
1509 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001510 if (setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001511 return;
1512 }
Svetoslav683914b2015-01-15 14:22:26 -08001513 final int columnCount = cursor.getColumnCount();
1514
1515 String[] values = new String[columnCount];
1516
1517 for (int i = 0; i < columnCount; i++) {
1518 String column = cursor.getColumnName(i);
1519
1520 switch (column) {
1521 case Settings.NameValueTable._ID: {
1522 values[i] = setting.getId();
1523 } break;
1524
1525 case Settings.NameValueTable.NAME: {
1526 values[i] = setting.getName();
1527 } break;
1528
1529 case Settings.NameValueTable.VALUE: {
1530 values[i] = setting.getValue();
1531 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001532 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001533 }
1534
Svetoslav683914b2015-01-15 14:22:26 -08001535 cursor.addRow(values);
1536 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001537
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001538 private static boolean isKeyValid(String key) {
1539 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1540 }
1541
Svetoslav683914b2015-01-15 14:22:26 -08001542 private static final class Arguments {
1543 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1544 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1545
1546 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1547 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1548
1549 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1550 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1551
1552 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1553 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1554
1555 public final String table;
1556 public final String name;
1557
1558 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1559 final int segmentSize = uri.getPathSegments().size();
1560 switch (segmentSize) {
1561 case 1: {
1562 if (where != null
1563 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1564 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1565 && whereArgs.length == 1) {
1566 name = whereArgs[0];
1567 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001568 return;
Svetoslav683914b2015-01-15 14:22:26 -08001569 } else if (where != null
1570 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1571 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1572 final int startIndex = Math.max(where.indexOf("'"),
1573 where.indexOf("\"")) + 1;
1574 final int endIndex = Math.max(where.lastIndexOf("'"),
1575 where.lastIndexOf("\""));
1576 name = where.substring(startIndex, endIndex);
1577 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001578 return;
Svetoslav683914b2015-01-15 14:22:26 -08001579 } else if (supportAll && where == null && whereArgs == null) {
1580 name = null;
1581 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001582 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001583 }
Svetoslav683914b2015-01-15 14:22:26 -08001584 } break;
1585
Svetoslav28494652015-02-12 14:11:42 -08001586 case 2: {
1587 if (where == null && whereArgs == null) {
1588 name = uri.getPathSegments().get(1);
1589 table = computeTableForSetting(uri, name);
1590 return;
1591 }
1592 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001593 }
Svetoslav28494652015-02-12 14:11:42 -08001594
1595 EventLogTags.writeUnsupportedSettingsQuery(
1596 uri.toSafeString(), where, Arrays.toString(whereArgs));
1597 String message = String.format( "Supported SQL:\n"
1598 + " uri content://some_table/some_property with null where and where args\n"
1599 + " uri content://some_table with query name=? and single name as arg\n"
1600 + " uri content://some_table with query name=some_name and null args\n"
1601 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1602 Arrays.toString(whereArgs));
1603 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001604 }
1605
Svetoslav28494652015-02-12 14:11:42 -08001606 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001607 String table = getValidTableOrThrow(uri);
1608
1609 if (name != null) {
1610 if (sSystemMovedToSecureSettings.contains(name)) {
1611 table = TABLE_SECURE;
1612 }
1613
1614 if (sSystemMovedToGlobalSettings.contains(name)) {
1615 table = TABLE_GLOBAL;
1616 }
1617
1618 if (sSecureMovedToGlobalSettings.contains(name)) {
1619 table = TABLE_GLOBAL;
1620 }
1621
1622 if (sGlobalMovedToSecureSettings.contains(name)) {
1623 table = TABLE_SECURE;
1624 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001625 }
Svetoslav683914b2015-01-15 14:22:26 -08001626
1627 return table;
1628 }
1629 }
1630
1631 final class SettingsRegistry {
1632 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1633
Svetoslav683914b2015-01-15 14:22:26 -08001634 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1635 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1636 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1637
1638 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1639
Svet Ganov53a441c2016-04-19 19:38:00 -07001640 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001641
Svetoslav7e0683b2015-08-03 16:02:52 -07001642 private final Handler mHandler;
1643
Svet Ganov53a441c2016-04-19 19:38:00 -07001644 private final BackupManager mBackupManager;
1645
Svetoslav683914b2015-01-15 14:22:26 -08001646 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001647 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001648 mGenerationRegistry = new GenerationRegistry(mLock);
1649 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001650 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001651 }
1652
Svetoslav683914b2015-01-15 14:22:26 -08001653 public List<String> getSettingsNamesLocked(int type, int userId) {
1654 final int key = makeKey(type, userId);
1655 SettingsState settingsState = peekSettingsStateLocked(key);
1656 return settingsState.getSettingNamesLocked();
1657 }
1658
1659 public SettingsState getSettingsLocked(int type, int userId) {
1660 final int key = makeKey(type, userId);
1661 return peekSettingsStateLocked(key);
1662 }
1663
1664 public void ensureSettingsForUserLocked(int userId) {
1665 // Migrate the setting for this user if needed.
1666 migrateLegacySettingsForUserIfNeededLocked(userId);
1667
1668 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001669 if (userId == UserHandle.USER_SYSTEM) {
1670 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001671 ensureSettingsStateLocked(globalKey);
1672 }
1673
1674 // Ensure secure settings loaded.
1675 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1676 ensureSettingsStateLocked(secureKey);
1677
1678 // Make sure the secure settings have an Android id set.
1679 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1680 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1681
1682 // Ensure system settings loaded.
1683 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1684 ensureSettingsStateLocked(systemKey);
1685
1686 // Upgrade the settings to the latest version.
1687 UpgradeController upgrader = new UpgradeController(userId);
1688 upgrader.upgradeIfNeededLocked();
1689 }
1690
1691 private void ensureSettingsStateLocked(int key) {
1692 if (mSettingsStates.get(key) == null) {
1693 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1694 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
Svetoslav Ganov92057492016-05-16 12:36:43 -07001695 maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001696 mSettingsStates.put(key, settingsState);
1697 }
1698 }
1699
1700 public void removeUserStateLocked(int userId, boolean permanently) {
1701 // We always keep the global settings in memory.
1702
1703 // Nuke system settings.
1704 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1705 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1706 if (systemSettingsState != null) {
1707 if (permanently) {
1708 mSettingsStates.remove(systemKey);
1709 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001710 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001711 systemSettingsState.destroyLocked(new Runnable() {
1712 @Override
1713 public void run() {
1714 mSettingsStates.remove(systemKey);
1715 }
1716 });
1717 }
1718 }
1719
1720 // Nuke secure settings.
1721 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1722 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1723 if (secureSettingsState != null) {
1724 if (permanently) {
1725 mSettingsStates.remove(secureKey);
1726 secureSettingsState.destroyLocked(null);
1727 } else {
1728 secureSettingsState.destroyLocked(new Runnable() {
1729 @Override
1730 public void run() {
1731 mSettingsStates.remove(secureKey);
1732 }
1733 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001734 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001735 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001736
1737 // Nuke generation tracking data
1738 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001739 }
1740
Svetoslav683914b2015-01-15 14:22:26 -08001741 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001742 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001743 final int key = makeKey(type, userId);
1744
1745 SettingsState settingsState = peekSettingsStateLocked(key);
1746 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1747
Svet Ganov53a441c2016-04-19 19:38:00 -07001748 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001749 notifyForSettingsChange(key, name);
1750 }
1751 return success;
1752 }
1753
Svet Ganov53a441c2016-04-19 19:38:00 -07001754 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001755 final int key = makeKey(type, userId);
1756
1757 SettingsState settingsState = peekSettingsStateLocked(key);
1758 final boolean success = settingsState.deleteSettingLocked(name);
1759
Svet Ganov53a441c2016-04-19 19:38:00 -07001760 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001761 notifyForSettingsChange(key, name);
1762 }
1763 return success;
1764 }
1765
1766 public Setting getSettingLocked(int type, int userId, String name) {
1767 final int key = makeKey(type, userId);
1768
1769 SettingsState settingsState = peekSettingsStateLocked(key);
1770 return settingsState.getSettingLocked(name);
1771 }
1772
1773 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001774 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001775 final int key = makeKey(type, userId);
1776
1777 SettingsState settingsState = peekSettingsStateLocked(key);
1778 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1779
Svet Ganov53a441c2016-04-19 19:38:00 -07001780 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001781 notifyForSettingsChange(key, name);
1782 }
1783
1784 return success;
1785 }
1786
1787 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001788 // Global and secure settings are signature protected. Apps signed
1789 // by the platform certificate are generally not uninstalled and
1790 // the main exception is tests. We trust components signed
1791 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001792
1793 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1794 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001795 if (systemSettings != null) {
1796 systemSettings.onPackageRemovedLocked(packageName);
1797 }
Svetoslav683914b2015-01-15 14:22:26 -08001798 }
1799
1800 private SettingsState peekSettingsStateLocked(int key) {
1801 SettingsState settingsState = mSettingsStates.get(key);
1802 if (settingsState != null) {
1803 return settingsState;
1804 }
1805
1806 ensureSettingsForUserLocked(getUserIdFromKey(key));
1807 return mSettingsStates.get(key);
1808 }
1809
1810 private void migrateAllLegacySettingsIfNeeded() {
1811 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001812 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001813 File globalFile = getSettingsFile(key);
1814 if (globalFile.exists()) {
1815 return;
1816 }
1817
1818 final long identity = Binder.clearCallingIdentity();
1819 try {
1820 List<UserInfo> users = mUserManager.getUsers(true);
1821
1822 final int userCount = users.size();
1823 for (int i = 0; i < userCount; i++) {
1824 final int userId = users.get(i).id;
1825
1826 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1827 SQLiteDatabase database = dbHelper.getWritableDatabase();
1828 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1829
1830 // Upgrade to the latest version.
1831 UpgradeController upgrader = new UpgradeController(userId);
1832 upgrader.upgradeIfNeededLocked();
1833
1834 // Drop from memory if not a running user.
1835 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1836 removeUserStateLocked(userId, false);
1837 }
1838 }
1839 } finally {
1840 Binder.restoreCallingIdentity(identity);
1841 }
1842 }
1843 }
1844
1845 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1846 // Every user has secure settings and if no file we need to migrate.
1847 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1848 File secureFile = getSettingsFile(secureKey);
1849 if (secureFile.exists()) {
1850 return;
1851 }
1852
1853 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1854 SQLiteDatabase database = dbHelper.getWritableDatabase();
1855
1856 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1857 }
1858
1859 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1860 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001861 // Move over the system settings.
1862 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1863 ensureSettingsStateLocked(systemKey);
1864 SettingsState systemSettings = mSettingsStates.get(systemKey);
1865 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1866 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001867
1868 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001869 // Do this after System settings, since this is the first thing we check when deciding
1870 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001871 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1872 ensureSettingsStateLocked(secureKey);
1873 SettingsState secureSettings = mSettingsStates.get(secureKey);
1874 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1875 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1876 secureSettings.persistSyncLocked();
1877
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001878 // Move over the global settings if owner.
1879 // Do this last, since this is the first thing we check when deciding
1880 // to skip over migration from db to xml for owner user.
1881 if (userId == UserHandle.USER_SYSTEM) {
1882 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1883 ensureSettingsStateLocked(globalKey);
1884 SettingsState globalSettings = mSettingsStates.get(globalKey);
1885 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1886 globalSettings.persistSyncLocked();
1887 }
Svetoslav683914b2015-01-15 14:22:26 -08001888
1889 // Drop the database as now all is moved and persisted.
1890 if (DROP_DATABASE_ON_MIGRATION) {
1891 dbHelper.dropDatabase();
1892 } else {
1893 dbHelper.backupDatabase();
1894 }
1895 }
1896
1897 private void migrateLegacySettingsLocked(SettingsState settingsState,
1898 SQLiteDatabase database, String table) {
1899 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1900 queryBuilder.setTables(table);
1901
1902 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1903 null, null, null, null, null);
1904
1905 if (cursor == null) {
1906 return;
1907 }
1908
1909 try {
1910 if (!cursor.moveToFirst()) {
1911 return;
1912 }
1913
1914 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1915 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1916
1917 settingsState.setVersionLocked(database.getVersion());
1918
1919 while (!cursor.isAfterLast()) {
1920 String name = cursor.getString(nameColumnIdx);
1921 String value = cursor.getString(valueColumnIdx);
1922 settingsState.insertSettingLocked(name, value,
1923 SettingsState.SYSTEM_PACKAGE_NAME);
1924 cursor.moveToNext();
1925 }
1926 } finally {
1927 cursor.close();
1928 }
1929 }
1930
1931 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1932 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1933
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09001934 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001935 return;
1936 }
1937
1938 final int userId = getUserIdFromKey(secureSettings.mKey);
1939
1940 final UserInfo user;
1941 final long identity = Binder.clearCallingIdentity();
1942 try {
1943 user = mUserManager.getUserInfo(userId);
1944 } finally {
1945 Binder.restoreCallingIdentity(identity);
1946 }
1947 if (user == null) {
1948 // Can happen due to races when deleting users - treat as benign.
1949 return;
1950 }
1951
1952 String androidId = Long.toHexString(new SecureRandom().nextLong());
1953 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1954 SettingsState.SYSTEM_PACKAGE_NAME);
1955
1956 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1957 + "] for user " + userId);
1958
1959 // Write a drop box entry if it's a restricted profile
1960 if (user.isRestricted()) {
1961 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1962 Context.DROPBOX_SERVICE);
1963 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1964 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1965 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1966 }
1967 }
1968 }
1969
1970 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001971 final int userId = getUserIdFromKey(key);
1972 Uri uri = getNotificationUriFor(key, name);
1973
Phil Weaver83fec002016-05-11 10:55:29 -07001974 mGenerationRegistry.incrementGeneration(key);
1975
Svetoslav7e0683b2015-08-03 16:02:52 -07001976 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1977 userId, 0, uri).sendToTarget();
1978
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001979 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001980 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1981 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001982 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001983 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1984 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001985 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001986
Svet Ganov53a441c2016-04-19 19:38:00 -07001987 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001988 }
1989
Svet Ganov53a441c2016-04-19 19:38:00 -07001990 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001991 Set<String> keysCloned) {
1992 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001993 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001994 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001995 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001996 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001997 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07001998 final int key = makeKey(type, profileId);
1999 mGenerationRegistry.incrementGeneration(key);
2000
2001 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002002 }
2003 }
2004 }
Svetoslav683914b2015-01-15 14:22:26 -08002005 }
2006
Svetoslav683914b2015-01-15 14:22:26 -08002007 private boolean isGlobalSettingsKey(int key) {
2008 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2009 }
2010
2011 private boolean isSystemSettingsKey(int key) {
2012 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2013 }
2014
2015 private boolean isSecureSettingsKey(int key) {
2016 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2017 }
2018
2019 private File getSettingsFile(int key) {
2020 if (isGlobalSettingsKey(key)) {
2021 final int userId = getUserIdFromKey(key);
2022 return new File(Environment.getUserSystemDirectory(userId),
2023 SETTINGS_FILE_GLOBAL);
2024 } else if (isSystemSettingsKey(key)) {
2025 final int userId = getUserIdFromKey(key);
2026 return new File(Environment.getUserSystemDirectory(userId),
2027 SETTINGS_FILE_SYSTEM);
2028 } else if (isSecureSettingsKey(key)) {
2029 final int userId = getUserIdFromKey(key);
2030 return new File(Environment.getUserSystemDirectory(userId),
2031 SETTINGS_FILE_SECURE);
2032 } else {
2033 throw new IllegalArgumentException("Invalid settings key:" + key);
2034 }
2035 }
2036
2037 private Uri getNotificationUriFor(int key, String name) {
2038 if (isGlobalSettingsKey(key)) {
2039 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2040 : Settings.Global.CONTENT_URI;
2041 } else if (isSecureSettingsKey(key)) {
2042 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2043 : Settings.Secure.CONTENT_URI;
2044 } else if (isSystemSettingsKey(key)) {
2045 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2046 : Settings.System.CONTENT_URI;
2047 } else {
2048 throw new IllegalArgumentException("Invalid settings key:" + key);
2049 }
2050 }
2051
2052 private int getMaxBytesPerPackageForType(int type) {
2053 switch (type) {
2054 case SETTINGS_TYPE_GLOBAL:
2055 case SETTINGS_TYPE_SECURE: {
2056 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2057 }
2058
2059 default: {
2060 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2061 }
2062 }
2063 }
2064
Svetoslav7e0683b2015-08-03 16:02:52 -07002065 private final class MyHandler extends Handler {
2066 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2067 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2068
2069 public MyHandler(Looper looper) {
2070 super(looper);
2071 }
2072
2073 @Override
2074 public void handleMessage(Message msg) {
2075 switch (msg.what) {
2076 case MSG_NOTIFY_URI_CHANGED: {
2077 final int userId = msg.arg1;
2078 Uri uri = (Uri) msg.obj;
2079 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2080 if (DEBUG) {
2081 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2082 }
2083 } break;
2084
2085 case MSG_NOTIFY_DATA_CHANGED: {
2086 mBackupManager.dataChanged();
2087 } break;
2088 }
2089 }
2090 }
2091
Svetoslav683914b2015-01-15 14:22:26 -08002092 private final class UpgradeController {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002093 private static final int SETTINGS_VERSION = 131;
Svetoslav683914b2015-01-15 14:22:26 -08002094
2095 private final int mUserId;
2096
2097 public UpgradeController(int userId) {
2098 mUserId = userId;
2099 }
2100
2101 public void upgradeIfNeededLocked() {
2102 // The version of all settings for a user is the same (all users have secure).
2103 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002104 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002105
2106 // Try an update from the current state.
2107 final int oldVersion = secureSettings.getVersionLocked();
2108 final int newVersion = SETTINGS_VERSION;
2109
Svet Ganovc9755bc2015-03-28 13:21:22 -07002110 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002111 if (oldVersion == newVersion) {
2112 return;
2113 }
2114
2115 // Try to upgrade.
2116 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2117
2118 // If upgrade failed start from scratch and upgrade.
2119 if (curVersion != newVersion) {
2120 // Drop state we have for this user.
2121 removeUserStateLocked(mUserId, true);
2122
2123 // Recreate the database.
2124 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2125 SQLiteDatabase database = dbHelper.getWritableDatabase();
2126 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2127
2128 // Migrate the settings for this user.
2129 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2130
2131 // Now upgrade should work fine.
2132 onUpgradeLocked(mUserId, oldVersion, newVersion);
2133 }
2134
2135 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002136 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002137 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002138 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002139 globalSettings.setVersionLocked(newVersion);
2140 }
2141
2142 // Set the secure settings version.
2143 secureSettings.setVersionLocked(newVersion);
2144
2145 // Set the system settings version.
2146 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002147 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002148 systemSettings.setVersionLocked(newVersion);
2149 }
2150
2151 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002152 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002153 }
2154
2155 private SettingsState getSecureSettingsLocked(int userId) {
2156 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2157 }
2158
2159 private SettingsState getSystemSettingsLocked(int userId) {
2160 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2161 }
2162
Jeff Brown503cffc2015-03-26 18:08:51 -07002163 /**
2164 * You must perform all necessary mutations to bring the settings
2165 * for this user from the old to the new version. When you add a new
2166 * upgrade step you *must* update SETTINGS_VERSION.
2167 *
2168 * This is an example of moving a setting from secure to global.
2169 *
2170 * // v119: Example settings changes.
2171 * if (currentVersion == 118) {
2172 * if (userId == UserHandle.USER_OWNER) {
2173 * // Remove from the secure settings.
2174 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2175 * String name = "example_setting_to_move";
2176 * String value = secureSettings.getSetting(name);
2177 * secureSettings.deleteSetting(name);
2178 *
2179 * // Add to the global settings.
2180 * SettingsState globalSettings = getGlobalSettingsLocked();
2181 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2182 * }
2183 *
2184 * // Update the current version.
2185 * currentVersion = 119;
2186 * }
2187 */
Svetoslav683914b2015-01-15 14:22:26 -08002188 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2189 if (DEBUG) {
2190 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2191 + oldVersion + " to version: " + newVersion);
2192 }
2193
Jeff Brown503cffc2015-03-26 18:08:51 -07002194 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002195
John Spurlocke11ae112015-05-11 16:09:03 -04002196 // v119: Reset zen + ringer mode.
2197 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002198 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002199 final SettingsState globalSettings = getGlobalSettingsLocked();
2200 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2201 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2202 SettingsState.SYSTEM_PACKAGE_NAME);
2203 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2204 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2205 SettingsState.SYSTEM_PACKAGE_NAME);
2206 }
2207 currentVersion = 119;
2208 }
2209
Jason Monk27bbb2d2015-03-31 16:46:39 -04002210 // v120: Add double tap to wake setting.
2211 if (currentVersion == 119) {
2212 SettingsState secureSettings = getSecureSettingsLocked(userId);
2213 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2214 getContext().getResources().getBoolean(
2215 R.bool.def_double_tap_to_wake) ? "1" : "0",
2216 SettingsState.SYSTEM_PACKAGE_NAME);
2217
2218 currentVersion = 120;
2219 }
2220
Svetoslav7e0683b2015-08-03 16:02:52 -07002221 if (currentVersion == 120) {
2222 // Before 121, we used a different string encoding logic. We just bump the
2223 // version here; SettingsState knows how to handle pre-version 120 files.
2224 currentVersion = 121;
2225 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002226
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002227 if (currentVersion == 121) {
2228 // Version 122: allow OEMs to set a default payment component in resources.
2229 // Note that we only write the default if no default has been set;
2230 // if there is, we just leave the default at whatever it currently is.
2231 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2232 String defaultComponent = (getContext().getResources().getString(
2233 R.string.def_nfc_payment_component));
2234 Setting currentSetting = secureSettings.getSettingLocked(
2235 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2236 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002237 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002238 secureSettings.insertSettingLocked(
2239 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2240 defaultComponent,
2241 SettingsState.SYSTEM_PACKAGE_NAME);
2242 }
2243 currentVersion = 122;
2244 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002245
2246 if (currentVersion == 122) {
2247 // Version 123: Adding a default value for the ability to add a user from
2248 // the lock screen.
2249 if (userId == UserHandle.USER_SYSTEM) {
2250 final SettingsState globalSettings = getGlobalSettingsLocked();
2251 Setting currentSetting = globalSettings.getSettingLocked(
2252 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002253 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002254 globalSettings.insertSettingLocked(
2255 Settings.Global.ADD_USERS_WHEN_LOCKED,
2256 getContext().getResources().getBoolean(
2257 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2258 SettingsState.SYSTEM_PACKAGE_NAME);
2259 }
2260 }
2261 currentVersion = 123;
2262 }
Bryce Leebd179282015-12-17 19:01:37 -08002263
2264 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002265 final SettingsState globalSettings = getGlobalSettingsLocked();
2266 String defaultDisabledProfiles = (getContext().getResources().getString(
2267 R.string.def_bluetooth_disabled_profiles));
2268 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2269 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002270 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002271 }
2272
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002273 if (currentVersion == 124) {
2274 // Version 124: allow OEMs to set a default value for whether IME should be
2275 // shown when a physical keyboard is connected.
2276 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2277 Setting currentSetting = secureSettings.getSettingLocked(
2278 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002279 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002280 secureSettings.insertSettingLocked(
2281 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2282 getContext().getResources().getBoolean(
2283 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2284 SettingsState.SYSTEM_PACKAGE_NAME);
2285 }
2286 currentVersion = 125;
2287 }
2288
Ruben Brunk98576cf2016-03-07 18:54:28 -08002289 if (currentVersion == 125) {
2290 // Version 125: Allow OEMs to set the default VR service.
2291 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2292
2293 Setting currentSetting = secureSettings.getSettingLocked(
2294 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002295 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002296 ArraySet<ComponentName> l =
2297 SystemConfig.getInstance().getDefaultVrComponents();
2298
2299 if (l != null && !l.isEmpty()) {
2300 StringBuilder b = new StringBuilder();
2301 boolean start = true;
2302 for (ComponentName c : l) {
2303 if (!start) {
2304 b.append(':');
2305 }
2306 b.append(c.flattenToString());
2307 start = false;
2308 }
2309 secureSettings.insertSettingLocked(
2310 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2311 SettingsState.SYSTEM_PACKAGE_NAME);
2312 }
2313
2314 }
2315 currentVersion = 126;
2316 }
2317
Daniel U02ba6122016-04-01 18:41:42 +01002318 if (currentVersion == 126) {
2319 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2320 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2321 if (mUserManager.isManagedProfile(userId)) {
2322 final SettingsState systemSecureSettings =
2323 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2324
2325 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2326 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002327 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002328 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2329 secureSettings.insertSettingLocked(
2330 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2331 showNotifications.getValue(),
2332 SettingsState.SYSTEM_PACKAGE_NAME);
2333 }
2334
2335 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2336 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002337 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002338 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2339 secureSettings.insertSettingLocked(
2340 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2341 allowPrivate.getValue(),
2342 SettingsState.SYSTEM_PACKAGE_NAME);
2343 }
2344 }
2345 currentVersion = 127;
2346 }
2347
Steven Ngdc20ba62016-04-26 18:19:04 +01002348 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002349 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002350 currentVersion = 128;
2351 }
2352
Julia Reynolds1f721e12016-07-11 08:50:58 -04002353 if (currentVersion == 128) {
2354 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2355 // the new apps are appended to the list of already approved apps.
2356 final SettingsState systemSecureSettings =
2357 getSecureSettingsLocked(userId);
2358
2359 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2360 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2361 String defaultPolicyAccess = getContext().getResources().getString(
2362 com.android.internal.R.string.config_defaultDndAccessPackages);
2363 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2364 if (policyAccess.isNull()) {
2365 systemSecureSettings.insertSettingLocked(
2366 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2367 defaultPolicyAccess,
2368 SettingsState.SYSTEM_PACKAGE_NAME);
2369 } else {
2370 StringBuilder currentSetting =
2371 new StringBuilder(policyAccess.getValue());
2372 currentSetting.append(":");
2373 currentSetting.append(defaultPolicyAccess);
2374 systemSecureSettings.updateSettingLocked(
2375 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2376 currentSetting.toString(),
2377 SettingsState.SYSTEM_PACKAGE_NAME);
2378 }
2379 }
2380
2381 currentVersion = 129;
2382 }
2383
Dan Sandler71f85e92016-07-20 13:46:05 -04002384 if (currentVersion == 129) {
2385 // default longpress timeout changed from 500 to 400. If unchanged from the old
2386 // default, update to the new default.
2387 final SettingsState systemSecureSettings =
2388 getSecureSettingsLocked(userId);
2389 final String oldValue = systemSecureSettings.getSettingLocked(
2390 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2391 if (TextUtils.equals("500", oldValue)) {
2392 systemSecureSettings.insertSettingLocked(
2393 Settings.Secure.LONG_PRESS_TIMEOUT,
2394 String.valueOf(getContext().getResources().getInteger(
2395 R.integer.def_long_press_timeout_millis)),
2396 SettingsState.SYSTEM_PACKAGE_NAME);
2397 }
2398 currentVersion = 130;
2399 }
2400
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002401 if (currentVersion == 130) {
2402 // Initialize new multi-press timeout to default value
2403 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2404 final String oldValue = systemSecureSettings.getSettingLocked(
2405 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2406 if (TextUtils.equals(null, oldValue)) {
2407 systemSecureSettings.insertSettingLocked(
2408 Settings.Secure.MULTI_PRESS_TIMEOUT,
2409 String.valueOf(getContext().getResources().getInteger(
2410 R.integer.def_multi_press_timeout_millis)),
2411 SettingsState.SYSTEM_PACKAGE_NAME);
2412 }
2413
2414 currentVersion = 131;
2415 }
2416
Dan Sandler71f85e92016-07-20 13:46:05 -04002417 if (currentVersion != newVersion) {
2418 Slog.w("SettingsProvider", "warning: upgrading settings database to version "
2419 + newVersion + " left it at "
2420 + currentVersion + " instead; this is probably a bug", new Throwable());
2421 if (DEBUG) {
2422 throw new RuntimeException("db upgrade error");
2423 }
2424 }
2425
Jeff Brown503cffc2015-03-26 18:08:51 -07002426 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002427
Jeff Brown503cffc2015-03-26 18:08:51 -07002428 // Return the current version.
2429 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002430 }
2431 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002432 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002433}