blob: 73971adaca0c4484d54527311b4fcaee018f1fbe [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;
Dianne Hackborn961321f2013-02-05 17:22:41 -080021import android.app.AppOpsManager;
Christopher Tate45281862010-03-05 15:46:30 -080022import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070023import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070024import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentValues;
26import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070027import android.content.Intent;
28import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080029import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070032import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080034import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080037import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040038import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070040import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080041import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080042import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070043import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080044import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070045import android.os.Handler;
46import android.os.Looper;
47import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070049import android.os.Process;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070051import android.os.UserHandle;
52import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070053import android.provider.Settings;
54import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080055import android.util.ArrayMap;
56import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070057import android.util.Slog;
58import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040059
Svetoslav683914b2015-01-15 14:22:26 -080060import com.android.internal.annotations.GuardedBy;
61import com.android.internal.content.PackageMonitor;
62import com.android.internal.os.BackgroundThread;
John Spurlocke11ae112015-05-11 16:09:03 -040063
Svetoslav683914b2015-01-15 14:22:26 -080064import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080065import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080066import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080067import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080068import java.security.SecureRandom;
69import java.util.Arrays;
70import java.util.List;
71import java.util.Map;
72import java.util.Set;
73import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070074
Svetoslav683914b2015-01-15 14:22:26 -080075import com.android.providers.settings.SettingsState.Setting;
76
77/**
78 * <p>
79 * This class is a content provider that publishes the system settings.
80 * It can be accessed via the content provider APIs or via custom call
81 * commands. The latter is a bit faster and is the preferred way to access
82 * the platform settings.
83 * </p>
84 * <p>
85 * There are three settings types, global (with signature level protection
86 * and shared across users), secure (with signature permission level
87 * protection and per user), and system (with dangerous permission level
88 * protection and per user). Global settings are stored under the device owner.
89 * Each of these settings is represented by a {@link
90 * com.android.providers.settings.SettingsState} object mapped to an integer
91 * key derived from the setting type in the most significant bits and user
92 * id in the least significant bits. Settings are synchronously loaded on
93 * instantiation of a SettingsState and asynchronously persisted on mutation.
94 * Settings are stored in the user specific system directory.
95 * </p>
96 * <p>
97 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
98 * and get a warning. Targeting higher API version prohibits this as the
99 * system settings are not a place for apps to save their state. When a package
100 * is removed the settings it added are deleted. Apps cannot delete system
101 * settings added by the platform. System settings values are validated to
102 * ensure the clients do not put bad values. Global and secure settings are
103 * changed only by trusted parties, therefore no validation is performed. Also
104 * there is a limit on the amount of app specific settings that can be added
105 * to prevent unlimited growth of the system process memory footprint.
106 * </p>
107 */
108@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700109public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800110 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700111
Svetoslav683914b2015-01-15 14:22:26 -0800112 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
113
114 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700115
Christopher Tate06efb532012-08-24 15:29:27 -0700116 private static final String TABLE_SYSTEM = "system";
117 private static final String TABLE_SECURE = "secure";
118 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800119
120 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private static final String TABLE_FAVORITES = "favorites";
122 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800123 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
124 private static final String TABLE_BOOKMARKS = "bookmarks";
125 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126
Svetoslav683914b2015-01-15 14:22:26 -0800127 // The set of removed legacy tables.
128 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700129 static {
Svetoslav683914b2015-01-15 14:22:26 -0800130 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
131 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
132 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
133 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
134 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
135 }
Christopher Tate06efb532012-08-24 15:29:27 -0700136
Svetoslav683914b2015-01-15 14:22:26 -0800137 private static final int MUTATION_OPERATION_INSERT = 1;
138 private static final int MUTATION_OPERATION_DELETE = 2;
139 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400140
Svetoslav683914b2015-01-15 14:22:26 -0800141 private static final String[] ALL_COLUMNS = new String[] {
142 Settings.NameValueTable._ID,
143 Settings.NameValueTable.NAME,
144 Settings.NameValueTable.VALUE
145 };
146
147 private static final Bundle NULL_SETTING = Bundle.forPair(Settings.NameValueTable.VALUE, null);
148
149 // Per user settings that cannot be modified if associated user restrictions are enabled.
150 private static final Map<String, String> sSettingToUserRestrictionMap = new ArrayMap<>();
151 static {
152 sSettingToUserRestrictionMap.put(Settings.Secure.LOCATION_MODE,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400153 UserManager.DISALLOW_SHARE_LOCATION);
Svetoslav683914b2015-01-15 14:22:26 -0800154 sSettingToUserRestrictionMap.put(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
155 UserManager.DISALLOW_SHARE_LOCATION);
156 sSettingToUserRestrictionMap.put(Settings.Secure.INSTALL_NON_MARKET_APPS,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400157 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Svetoslav683914b2015-01-15 14:22:26 -0800158 sSettingToUserRestrictionMap.put(Settings.Global.ADB_ENABLED,
159 UserManager.DISALLOW_DEBUGGING_FEATURES);
160 sSettingToUserRestrictionMap.put(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400161 UserManager.ENSURE_VERIFY_APPS);
Svetoslav683914b2015-01-15 14:22:26 -0800162 sSettingToUserRestrictionMap.put(Settings.Global.PREFERRED_NETWORK_MODE,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400163 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Christopher Tate06efb532012-08-24 15:29:27 -0700164 }
165
Svetoslav683914b2015-01-15 14:22:26 -0800166 // Per user secure settings that moved to the for all users global settings.
167 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
168 static {
169 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700170 }
171
Svetoslav683914b2015-01-15 14:22:26 -0800172 // Per user system settings that moved to the for all users global settings.
173 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
174 static {
175 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700176 }
177
Svetoslav683914b2015-01-15 14:22:26 -0800178 // Per user system settings that moved to the per user secure settings.
179 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
180 static {
181 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700182 }
183
Svetoslav683914b2015-01-15 14:22:26 -0800184 // Per all users global settings that moved to the per user secure settings.
185 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
186 static {
187 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700188 }
189
Svetoslav683914b2015-01-15 14:22:26 -0800190 // Per user secure settings that are cloned for the managed profiles of the user.
191 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
192 static {
193 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700194 }
195
Svetoslav683914b2015-01-15 14:22:26 -0800196 // Per user system settings that are cloned for the managed profiles of the user.
197 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
198 static {
199 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400200 }
201
Svetoslav683914b2015-01-15 14:22:26 -0800202 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700203
Svetoslav683914b2015-01-15 14:22:26 -0800204 @GuardedBy("mLock")
205 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700206
Svetoslav7ec28e82015-05-20 17:01:10 -0700207 // We have to call in the user manager with no lock held,
208 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800209
Svetoslav7ec28e82015-05-20 17:01:10 -0700210 // We have to call in the package manager with no lock held,
211 private volatile PackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700212
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700213 @Override
214 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800215 synchronized (mLock) {
216 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Svetoslav683914b2015-01-15 14:22:26 -0800217 mPackageManager = getContext().getPackageManager();
218 mSettingsRegistry = new SettingsRegistry();
219 }
220 registerBroadcastReceivers();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700221 return true;
222 }
223
Svetoslav683914b2015-01-15 14:22:26 -0800224 @Override
225 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700226 final int requestingUserId = getRequestingUserId(args);
227 switch (method) {
228 case Settings.CALL_METHOD_GET_GLOBAL: {
229 Setting setting = getGlobalSetting(name);
230 return packageValueForCallResult(setting);
Svetoslav683914b2015-01-15 14:22:26 -0800231 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700232
233 case Settings.CALL_METHOD_GET_SECURE: {
234 Setting setting = getSecureSetting(name, requestingUserId);
235 return packageValueForCallResult(setting);
236 }
237
238 case Settings.CALL_METHOD_GET_SYSTEM: {
239 Setting setting = getSystemSetting(name, requestingUserId);
240 return packageValueForCallResult(setting);
241 }
242
243 case Settings.CALL_METHOD_PUT_GLOBAL: {
244 String value = getSettingValue(args);
245 insertGlobalSetting(name, value, requestingUserId);
246 break;
247 }
248
249 case Settings.CALL_METHOD_PUT_SECURE: {
250 String value = getSettingValue(args);
251 insertSecureSetting(name, value, requestingUserId);
252 break;
253 }
254
255 case Settings.CALL_METHOD_PUT_SYSTEM: {
256 String value = getSettingValue(args);
257 insertSystemSetting(name, value, requestingUserId);
258 break;
259 }
260
261 default: {
262 Slog.w(LOG_TAG, "call() with invalid method: " + method);
263 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700264 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700265
Christopher Tate06efb532012-08-24 15:29:27 -0700266 return null;
267 }
268
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800269 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800270 public String getType(Uri uri) {
271 Arguments args = new Arguments(uri, null, null, true);
272 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700273 return "vnd.android.cursor.dir/" + args.table;
274 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700275 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 }
277 }
278
279 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800280 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
281 String order) {
282 if (DEBUG) {
283 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700284 }
285
Svetoslav683914b2015-01-15 14:22:26 -0800286 Arguments args = new Arguments(uri, where, whereArgs, true);
287 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288
Svetoslav683914b2015-01-15 14:22:26 -0800289 // If a legacy table that is gone, done.
290 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
291 return new MatrixCursor(normalizedProjection, 0);
292 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700293
Svetoslav7ec28e82015-05-20 17:01:10 -0700294 switch (args.table) {
295 case TABLE_GLOBAL: {
296 if (args.name != null) {
297 Setting setting = getGlobalSetting(args.name);
298 return packageSettingForQuery(setting, normalizedProjection);
299 } else {
300 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700301 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700302 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700303
Svetoslav7ec28e82015-05-20 17:01:10 -0700304 case TABLE_SECURE: {
305 final int userId = UserHandle.getCallingUserId();
306 if (args.name != null) {
307 Setting setting = getSecureSetting(args.name, userId);
308 return packageSettingForQuery(setting, normalizedProjection);
309 } else {
310 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800311 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700312 }
Svetoslav683914b2015-01-15 14:22:26 -0800313
Svetoslav7ec28e82015-05-20 17:01:10 -0700314 case TABLE_SYSTEM: {
315 final int userId = UserHandle.getCallingUserId();
316 if (args.name != null) {
317 Setting setting = getSystemSetting(args.name, userId);
318 return packageSettingForQuery(setting, normalizedProjection);
319 } else {
320 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800321 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700322 }
Svetoslav683914b2015-01-15 14:22:26 -0800323
Svetoslav7ec28e82015-05-20 17:01:10 -0700324 default: {
325 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700326 }
327 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700328 }
329
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800331 public Uri insert(Uri uri, ContentValues values) {
332 if (DEBUG) {
333 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700334 }
335
Svetoslav683914b2015-01-15 14:22:26 -0800336 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700337
Svetoslav683914b2015-01-15 14:22:26 -0800338 // If a legacy table that is gone, done.
339 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 return null;
341 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700342
Svetoslav683914b2015-01-15 14:22:26 -0800343 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700344 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800345 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700346 }
347
Svetoslav683914b2015-01-15 14:22:26 -0800348 String value = values.getAsString(Settings.Secure.VALUE);
349
Svetoslav7ec28e82015-05-20 17:01:10 -0700350 switch (table) {
351 case TABLE_GLOBAL: {
352 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId())) {
353 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700354 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700355 } break;
356
357 case TABLE_SECURE: {
358 if (insertSecureSetting(name, value, UserHandle.getCallingUserId())) {
359 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
360 }
361 } break;
362
363 case TABLE_SYSTEM: {
364 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
365 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
366 }
367 } break;
368
369 default: {
370 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700371 }
372 }
373
Svetoslav683914b2015-01-15 14:22:26 -0800374 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700375 }
376
377 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800378 public int bulkInsert(Uri uri, ContentValues[] allValues) {
379 if (DEBUG) {
380 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700382
Svetoslav683914b2015-01-15 14:22:26 -0800383 int insertionCount = 0;
384 final int valuesCount = allValues.length;
385 for (int i = 0; i < valuesCount; i++) {
386 ContentValues values = allValues[i];
387 if (insert(uri, values) != null) {
388 insertionCount++;
389 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700390 }
Svetoslav683914b2015-01-15 14:22:26 -0800391
392 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393 }
394
395 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800396 public int delete(Uri uri, String where, String[] whereArgs) {
397 if (DEBUG) {
398 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400
Svetoslav683914b2015-01-15 14:22:26 -0800401 Arguments args = new Arguments(uri, where, whereArgs, false);
402
403 // If a legacy table that is gone, done.
404 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
405 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700406 }
Svetoslav683914b2015-01-15 14:22:26 -0800407
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700408 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800409 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700410 }
Svetoslav683914b2015-01-15 14:22:26 -0800411
Svetoslav7ec28e82015-05-20 17:01:10 -0700412 switch (args.table) {
413 case TABLE_GLOBAL: {
414 final int userId = UserHandle.getCallingUserId();
415 return deleteGlobalSetting(args.name, userId) ? 1 : 0;
416 }
Svetoslav683914b2015-01-15 14:22:26 -0800417
Svetoslav7ec28e82015-05-20 17:01:10 -0700418 case TABLE_SECURE: {
419 final int userId = UserHandle.getCallingUserId();
420 return deleteSecureSetting(args.name, userId) ? 1 : 0;
421 }
Svetoslav683914b2015-01-15 14:22:26 -0800422
Svetoslav7ec28e82015-05-20 17:01:10 -0700423 case TABLE_SYSTEM: {
424 final int userId = UserHandle.getCallingUserId();
425 return deleteSystemSetting(args.name, userId) ? 1 : 0;
426 }
427
428 default: {
429 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800430 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700431 }
Svetoslav683914b2015-01-15 14:22:26 -0800432 }
433
434 @Override
435 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
436 if (DEBUG) {
437 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700438 }
Svetoslav683914b2015-01-15 14:22:26 -0800439
440 Arguments args = new Arguments(uri, where, whereArgs, false);
441
442 // If a legacy table that is gone, done.
443 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
444 return 0;
445 }
446
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700447 String name = values.getAsString(Settings.Secure.NAME);
448 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800449 return 0;
450 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700451 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800452
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 switch (args.table) {
454 case TABLE_GLOBAL: {
455 final int userId = UserHandle.getCallingUserId();
456 return updateGlobalSetting(args.name, value, userId) ? 1 : 0;
457 }
Svetoslav683914b2015-01-15 14:22:26 -0800458
Svetoslav7ec28e82015-05-20 17:01:10 -0700459 case TABLE_SECURE: {
460 final int userId = UserHandle.getCallingUserId();
461 return updateSecureSetting(args.name, value, userId) ? 1 : 0;
462 }
Svetoslav683914b2015-01-15 14:22:26 -0800463
Svetoslav7ec28e82015-05-20 17:01:10 -0700464 case TABLE_SYSTEM: {
465 final int userId = UserHandle.getCallingUserId();
466 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
467 }
Svetoslav683914b2015-01-15 14:22:26 -0800468
Svetoslav7ec28e82015-05-20 17:01:10 -0700469 default: {
470 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800471 }
472 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700473 }
474
475 @Override
476 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey3b566b82014-11-12 10:39:56 -0800477 throw new FileNotFoundException("Direct file access no longer supported; "
478 + "ringtone playback is available through android.media.Ringtone");
Marco Nelissen69f593c2009-07-28 09:55:04 -0700479 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800480
Svetoslavb505ccc2015-02-17 12:41:04 -0800481 @Override
482 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
483 synchronized (mLock) {
484 final long identity = Binder.clearCallingIdentity();
485 try {
486 List<UserInfo> users = mUserManager.getUsers(true);
487 final int userCount = users.size();
488 for (int i = 0; i < userCount; i++) {
489 UserInfo user = users.get(i);
490 dumpForUser(user.id, pw);
491 }
492 } finally {
493 Binder.restoreCallingIdentity(identity);
494 }
495 }
496 }
497
498 private void dumpForUser(int userId, PrintWriter pw) {
499 if (userId == UserHandle.USER_OWNER) {
500 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700501 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800502 dumpSettings(globalCursor, pw);
503 pw.println();
504 }
505
506 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700507 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800508 dumpSettings(secureCursor, pw);
509 pw.println();
510
511 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700512 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800513 dumpSettings(systemCursor, pw);
514 pw.println();
515 }
516
517 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700518 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800519 return;
520 }
521
522 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
523 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
524 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
525
526 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700527 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
528 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
529 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800530 pw.println();
531 } while (cursor.moveToNext());
532 }
533
Svetoslav7e0683b2015-08-03 16:02:52 -0700534 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700535 if (s != null) {
536 return s;
537 }
538 return "{null}";
539 }
540
Svetoslav683914b2015-01-15 14:22:26 -0800541 private void registerBroadcastReceivers() {
542 IntentFilter userFilter = new IntentFilter();
543 userFilter.addAction(Intent.ACTION_USER_REMOVED);
544 userFilter.addAction(Intent.ACTION_USER_STOPPED);
545
546 getContext().registerReceiver(new BroadcastReceiver() {
547 @Override
548 public void onReceive(Context context, Intent intent) {
549 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
550 UserHandle.USER_OWNER);
551
552 switch (intent.getAction()) {
553 case Intent.ACTION_USER_REMOVED: {
554 mSettingsRegistry.removeUserStateLocked(userId, true);
555 } break;
556
557 case Intent.ACTION_USER_STOPPED: {
558 mSettingsRegistry.removeUserStateLocked(userId, false);
559 } break;
560 }
561 }
562 }, userFilter);
563
564 PackageMonitor monitor = new PackageMonitor() {
565 @Override
566 public void onPackageRemoved(String packageName, int uid) {
567 synchronized (mLock) {
568 mSettingsRegistry.onPackageRemovedLocked(packageName,
569 UserHandle.getUserId(uid));
570 }
571 }
572 };
573
574 // package changes
575 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
576 UserHandle.ALL, true);
577 }
578
Svetoslav7ec28e82015-05-20 17:01:10 -0700579 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800580 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700581 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800582 }
583
Svetoslav7ec28e82015-05-20 17:01:10 -0700584 synchronized (mLock) {
585 // Get the settings.
586 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
587 SettingsRegistry.SETTINGS_TYPE_GLOBAL, UserHandle.USER_OWNER);
Svetoslav683914b2015-01-15 14:22:26 -0800588
Svetoslav7ec28e82015-05-20 17:01:10 -0700589 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800590
Svetoslav7ec28e82015-05-20 17:01:10 -0700591 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800592
Svetoslav7ec28e82015-05-20 17:01:10 -0700593 String[] normalizedProjection = normalizeProjection(projection);
594 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800595
Svetoslav7ec28e82015-05-20 17:01:10 -0700596 // Anyone can get the global settings, so no security checks.
597 for (int i = 0; i < nameCount; i++) {
598 String name = names.get(i);
599 Setting setting = settingsState.getSettingLocked(name);
600 appendSettingToCursor(result, setting);
601 }
602
603 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800604 }
Svetoslav683914b2015-01-15 14:22:26 -0800605 }
606
Svetoslav7ec28e82015-05-20 17:01:10 -0700607 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800608 if (DEBUG) {
609 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
610 }
611
612 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700613 synchronized (mLock) {
614 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
615 UserHandle.USER_OWNER, name);
Svetoslav683914b2015-01-15 14:22:26 -0800616 }
Svetoslav683914b2015-01-15 14:22:26 -0800617 }
618
Svetoslav7ec28e82015-05-20 17:01:10 -0700619 private boolean updateGlobalSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800620 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700621 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800622 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700623 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800624 }
625
Svetoslav7ec28e82015-05-20 17:01:10 -0700626 private boolean insertGlobalSetting(String name, String value, int requestingUserId) {
627 if (DEBUG) {
628 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
629 }
630 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
631 }
632
633 private boolean deleteGlobalSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800634 if (DEBUG) {
635 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
636 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700637 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800638 }
639
Svetoslav7ec28e82015-05-20 17:01:10 -0700640 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800641 int operation) {
642 // Make sure the caller can change the settings - treated as secure.
643 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
644
Svetoslav683914b2015-01-15 14:22:26 -0800645 // Resolve the userId on whose behalf the call is made.
646 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
647
648 // If this is a setting that is currently restricted for this user, done.
649 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId)) {
650 return false;
651 }
652
653 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700654 synchronized (mLock) {
655 switch (operation) {
656 case MUTATION_OPERATION_INSERT: {
657 return mSettingsRegistry
658 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
659 UserHandle.USER_OWNER, name, value, getCallingPackage());
660 }
Svetoslav683914b2015-01-15 14:22:26 -0800661
Svetoslav7ec28e82015-05-20 17:01:10 -0700662 case MUTATION_OPERATION_DELETE: {
663 return mSettingsRegistry.deleteSettingLocked(
664 SettingsRegistry.SETTINGS_TYPE_GLOBAL,
665 UserHandle.USER_OWNER, name);
666 }
Svetoslav683914b2015-01-15 14:22:26 -0800667
Svetoslav7ec28e82015-05-20 17:01:10 -0700668 case MUTATION_OPERATION_UPDATE: {
669 return mSettingsRegistry
670 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
671 UserHandle.USER_OWNER, name, value, getCallingPackage());
672 }
Svetoslav683914b2015-01-15 14:22:26 -0800673 }
674 }
675
676 return false;
677 }
678
Svetoslav7ec28e82015-05-20 17:01:10 -0700679 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800680 if (DEBUG) {
681 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
682 }
683
684 // Resolve the userId on whose behalf the call is made.
685 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
686
Svetoslav7ec28e82015-05-20 17:01:10 -0700687 synchronized (mLock) {
688 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
689 SettingsRegistry.SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800690
Svetoslav7ec28e82015-05-20 17:01:10 -0700691 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800692
Svetoslav7ec28e82015-05-20 17:01:10 -0700693 String[] normalizedProjection = normalizeProjection(projection);
694 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800695
Svetoslav7ec28e82015-05-20 17:01:10 -0700696 for (int i = 0; i < nameCount; i++) {
697 String name = names.get(i);
698 // Determine the owning user as some profile settings are cloned from the parent.
699 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
700 name);
Svetoslav683914b2015-01-15 14:22:26 -0800701
Svetoslav7ec28e82015-05-20 17:01:10 -0700702 // Special case for location (sigh).
703 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
704 return null;
705 }
Svetoslav683914b2015-01-15 14:22:26 -0800706
Svetoslav7ec28e82015-05-20 17:01:10 -0700707 Setting setting = mSettingsRegistry.getSettingLocked(
708 SettingsRegistry.SETTINGS_TYPE_SECURE, owningUserId, name);
709 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800710 }
711
Svetoslav7ec28e82015-05-20 17:01:10 -0700712 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800713 }
Svetoslav683914b2015-01-15 14:22:26 -0800714 }
715
Svetoslav7ec28e82015-05-20 17:01:10 -0700716 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800717 if (DEBUG) {
718 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
719 }
720
721 // Resolve the userId on whose behalf the call is made.
722 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
723
724 // Determine the owning user as some profile settings are cloned from the parent.
725 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
726
727 // Special case for location (sigh).
728 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
729 return null;
730 }
731
732 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700733 synchronized (mLock) {
734 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
735 owningUserId, name);
736 }
Svetoslav683914b2015-01-15 14:22:26 -0800737 }
738
Svetoslav7ec28e82015-05-20 17:01:10 -0700739 private boolean insertSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800740 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700741 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800742 + requestingUserId + ")");
743 }
744
Svetoslav7ec28e82015-05-20 17:01:10 -0700745 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800746 }
747
Svetoslav7ec28e82015-05-20 17:01:10 -0700748 private boolean deleteSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800749 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700750 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800751 }
752
Svetoslav7ec28e82015-05-20 17:01:10 -0700753 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800754 }
755
Svetoslav7ec28e82015-05-20 17:01:10 -0700756 private boolean updateSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800757 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700758 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800759 + requestingUserId + ")");
760 }
761
Svetoslav7ec28e82015-05-20 17:01:10 -0700762 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800763 }
764
Svetoslav7ec28e82015-05-20 17:01:10 -0700765 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800766 int operation) {
767 // Make sure the caller can change the settings.
768 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
769
Svetoslav683914b2015-01-15 14:22:26 -0800770 // Resolve the userId on whose behalf the call is made.
771 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
772
773 // If this is a setting that is currently restricted for this user, done.
774 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId)) {
775 return false;
776 }
777
778 // Determine the owning user as some profile settings are cloned from the parent.
779 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
780
781 // Only the owning user can change the setting.
782 if (owningUserId != callingUserId) {
783 return false;
784 }
785
786 // Special cases for location providers (sigh).
787 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslavb596a2c2015-02-17 21:37:09 -0800788 return updateLocationProvidersAllowedLocked(value, owningUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800789 }
790
791 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700792 synchronized (mLock) {
793 switch (operation) {
794 case MUTATION_OPERATION_INSERT: {
795 return mSettingsRegistry
796 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
797 owningUserId, name, value, getCallingPackage());
798 }
Svetoslav683914b2015-01-15 14:22:26 -0800799
Svetoslav7ec28e82015-05-20 17:01:10 -0700800 case MUTATION_OPERATION_DELETE: {
801 return mSettingsRegistry.deleteSettingLocked(
802 SettingsRegistry.SETTINGS_TYPE_SECURE,
803 owningUserId, name);
804 }
Svetoslav683914b2015-01-15 14:22:26 -0800805
Svetoslav7ec28e82015-05-20 17:01:10 -0700806 case MUTATION_OPERATION_UPDATE: {
807 return mSettingsRegistry
808 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
809 owningUserId, name, value, getCallingPackage());
810 }
Svetoslav683914b2015-01-15 14:22:26 -0800811 }
812 }
813
814 return false;
815 }
816
Svetoslav7ec28e82015-05-20 17:01:10 -0700817 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800818 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700819 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800820 }
821
822 // Resolve the userId on whose behalf the call is made.
823 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
824
Svetoslav7ec28e82015-05-20 17:01:10 -0700825 synchronized (mLock) {
826 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
827 SettingsRegistry.SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800828
Svetoslav7ec28e82015-05-20 17:01:10 -0700829 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800830
Svetoslav7ec28e82015-05-20 17:01:10 -0700831 String[] normalizedProjection = normalizeProjection(projection);
832 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800833
Svetoslav7ec28e82015-05-20 17:01:10 -0700834 for (int i = 0; i < nameCount; i++) {
835 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800836
Svetoslav7ec28e82015-05-20 17:01:10 -0700837 // Determine the owning user as some profile settings are cloned from the parent.
838 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
839 name);
Svetoslav683914b2015-01-15 14:22:26 -0800840
Svetoslav7ec28e82015-05-20 17:01:10 -0700841 Setting setting = mSettingsRegistry.getSettingLocked(
842 SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name);
843 appendSettingToCursor(result, setting);
844 }
845
846 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800847 }
Svetoslav683914b2015-01-15 14:22:26 -0800848 }
849
Svetoslav7ec28e82015-05-20 17:01:10 -0700850 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800851 if (DEBUG) {
852 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
853 }
854
855 // Resolve the userId on whose behalf the call is made.
856 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
857
858 // Determine the owning user as some profile settings are cloned from the parent.
859 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
860
861 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700862 synchronized (mLock) {
863 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
864 owningUserId, name);
865 }
Svetoslav683914b2015-01-15 14:22:26 -0800866 }
867
Svetoslav7ec28e82015-05-20 17:01:10 -0700868 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800869 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700870 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800871 + requestingUserId + ")");
872 }
873
Svetoslav7ec28e82015-05-20 17:01:10 -0700874 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800875 }
876
Svetoslav7ec28e82015-05-20 17:01:10 -0700877 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800878 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700879 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800880 }
881
Svetoslav7ec28e82015-05-20 17:01:10 -0700882 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800883 }
884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800886 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800888 + requestingUserId + ")");
889 }
890
Svetoslav7ec28e82015-05-20 17:01:10 -0700891 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800892 }
893
Svetoslav7ec28e82015-05-20 17:01:10 -0700894 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800895 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +0100896 if (!hasWriteSecureSettingsPermission()) {
897 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
898 // operation is allowed for the calling package through appops.
899 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
900 Binder.getCallingUid(), getCallingPackage(), true)) {
901 return false;
902 }
Svetoslav683914b2015-01-15 14:22:26 -0800903 }
904
Svetoslavf41334b2015-06-23 12:06:03 -0700905 // Enforce what the calling package can mutate the system settings.
906 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name);
Svetoslav683914b2015-01-15 14:22:26 -0800907
908 // Resolve the userId on whose behalf the call is made.
909 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
910
911 // Determine the owning user as some profile settings are cloned from the parent.
912 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
913
914 // Only the owning user id can change the setting.
915 if (owningUserId != callingUserId) {
916 return false;
917 }
918
919 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700920 synchronized (mLock) {
921 switch (operation) {
922 case MUTATION_OPERATION_INSERT: {
923 validateSystemSettingValue(name, value);
924 return mSettingsRegistry
925 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
926 owningUserId, name, value, getCallingPackage());
927 }
928
929 case MUTATION_OPERATION_DELETE: {
930 return mSettingsRegistry.deleteSettingLocked(
931 SettingsRegistry.SETTINGS_TYPE_SYSTEM,
932 owningUserId, name);
933 }
934
935 case MUTATION_OPERATION_UPDATE: {
936 validateSystemSettingValue(name, value);
937 return mSettingsRegistry
938 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
939 owningUserId, name, value, getCallingPackage());
940 }
Svetoslav683914b2015-01-15 14:22:26 -0800941 }
942
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 return false;
Svetoslav683914b2015-01-15 14:22:26 -0800944 }
Svetoslav683914b2015-01-15 14:22:26 -0800945 }
946
Billy Lau6ad2d662015-07-18 00:26:58 +0100947 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -0700948 // Write secure settings is a more protected permission. If caller has it we are good.
949 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
950 == PackageManager.PERMISSION_GRANTED) {
951 return true;
952 }
953
Svetoslavf41334b2015-06-23 12:06:03 -0700954 return false;
955 }
956
Svetoslav683914b2015-01-15 14:22:26 -0800957 private void validateSystemSettingValue(String name, String value) {
958 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
959 if (validator != null && !validator.validate(value)) {
960 throw new IllegalArgumentException("Invalid value: " + value
961 + " for setting: " + name);
962 }
963 }
964
965 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
966 int owningUserId) {
967 // Optimization - location providers are restricted only for managed profiles.
968 if (callingUserId == owningUserId) {
969 return false;
970 }
971 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
972 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
973 new UserHandle(callingUserId))) {
974 return true;
975 }
976 return false;
977 }
978
979 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId) {
980 String restriction = sSettingToUserRestrictionMap.get(setting);
981 if (restriction == null) {
982 return false;
983 }
984 return mUserManager.hasUserRestriction(restriction, new UserHandle(userId));
985 }
986
987 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
988 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
989 }
990
991 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
992 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
993 }
994
995 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
996 final int parentId = getGroupParentLocked(userId);
997 if (parentId != userId && keys.contains(name)) {
998 return parentId;
999 }
1000 return userId;
1001 }
1002
Svetoslavf41334b2015-06-23 12:06:03 -07001003 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Svetoslav683914b2015-01-15 14:22:26 -08001004 String name) {
1005 // System/root/shell can mutate whatever secure settings they want.
1006 final int callingUid = Binder.getCallingUid();
1007 if (callingUid == android.os.Process.SYSTEM_UID
1008 || callingUid == Process.SHELL_UID
1009 || callingUid == Process.ROOT_UID) {
1010 return;
1011 }
1012
1013 switch (operation) {
1014 case MUTATION_OPERATION_INSERT:
1015 // Insert updates.
1016 case MUTATION_OPERATION_UPDATE: {
1017 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1018 return;
1019 }
1020
1021 // The calling package is already verified.
1022 PackageInfo packageInfo = getCallingPackageInfoOrThrow();
1023
1024 // Privileged apps can do whatever they want.
1025 if ((packageInfo.applicationInfo.privateFlags
1026 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1027 return;
1028 }
1029
1030 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1031 packageInfo.applicationInfo.targetSdkVersion, name);
1032 } break;
1033
1034 case MUTATION_OPERATION_DELETE: {
1035 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1036 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1037 throw new IllegalArgumentException("You cannot delete system defined"
1038 + " secure settings.");
1039 }
1040
1041 // The calling package is already verified.
1042 PackageInfo packageInfo = getCallingPackageInfoOrThrow();
1043
1044 // Privileged apps can do whatever they want.
1045 if ((packageInfo.applicationInfo.privateFlags &
1046 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1047 return;
1048 }
1049
1050 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1051 packageInfo.applicationInfo.targetSdkVersion, name);
1052 } break;
1053 }
1054 }
1055
1056 private PackageInfo getCallingPackageInfoOrThrow() {
1057 try {
1058 return mPackageManager.getPackageInfo(getCallingPackage(), 0);
1059 } catch (PackageManager.NameNotFoundException e) {
1060 throw new IllegalStateException("Calling package doesn't exist");
1061 }
1062 }
1063
1064 private int getGroupParentLocked(int userId) {
1065 // Most frequent use case.
1066 if (userId == UserHandle.USER_OWNER) {
1067 return userId;
1068 }
1069 // We are in the same process with the user manager and the returned
1070 // user info is a cached instance, so just look up instead of cache.
1071 final long identity = Binder.clearCallingIdentity();
1072 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001073 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001074 UserInfo userInfo = mUserManager.getProfileParent(userId);
1075 return (userInfo != null) ? userInfo.id : userId;
1076 } finally {
1077 Binder.restoreCallingIdentity(identity);
1078 }
1079 }
1080
Svetoslav683914b2015-01-15 14:22:26 -08001081 private void enforceWritePermission(String permission) {
1082 if (getContext().checkCallingOrSelfPermission(permission)
1083 != PackageManager.PERMISSION_GRANTED) {
1084 throw new SecurityException("Permission denial: writing to settings requires:"
1085 + permission);
1086 }
1087 }
1088
1089 /*
1090 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1091 * This setting contains a list of the currently enabled location providers.
1092 * But helper functions in android.providers.Settings can enable or disable
1093 * a single provider by using a "+" or "-" prefix before the provider name.
1094 *
1095 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001096 */
Svetoslavb596a2c2015-02-17 21:37:09 -08001097 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001098 if (TextUtils.isEmpty(value)) {
1099 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001100 }
1101
Svetoslav683914b2015-01-15 14:22:26 -08001102 final char prefix = value.charAt(0);
1103 if (prefix != '+' && prefix != '-') {
1104 return false;
1105 }
1106
1107 // skip prefix
1108 value = value.substring(1);
1109
Svetoslav7ec28e82015-05-20 17:01:10 -07001110 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001111 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1112
1113 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1114
1115 int index = oldProviders.indexOf(value);
1116 int end = index + value.length();
1117
1118 // check for commas to avoid matching on partial string
1119 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1120 index = -1;
1121 }
1122
1123 // check for commas to avoid matching on partial string
1124 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1125 index = -1;
1126 }
1127
1128 String newProviders;
1129
1130 if (prefix == '+' && index < 0) {
1131 // append the provider to the list if not present
1132 if (oldProviders.length() == 0) {
1133 newProviders = value;
1134 } else {
1135 newProviders = oldProviders + ',' + value;
1136 }
1137 } else if (prefix == '-' && index >= 0) {
1138 // remove the provider from the list if present
1139 // remove leading or trailing comma
1140 if (index > 0) {
1141 index--;
1142 } else if (end < oldProviders.length()) {
1143 end++;
1144 }
1145
1146 newProviders = oldProviders.substring(0, index);
1147 if (end < oldProviders.length()) {
1148 newProviders += oldProviders.substring(end);
1149 }
1150 } else {
1151 // nothing changed, so no need to update the database
1152 return false;
1153 }
1154
Svetoslavb596a2c2015-02-17 21:37:09 -08001155 return mSettingsRegistry.insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
1156 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1157 getCallingPackage());
Svetoslav683914b2015-01-15 14:22:26 -08001158 }
1159
Svetoslav683914b2015-01-15 14:22:26 -08001160 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1161 int targetSdkVersion, String name) {
1162 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1163 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1164 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1165 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1166 + " This will soon become an error.");
1167 } else {
1168 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1169 + " This will soon become an error.");
1170 }
1171 } else {
1172 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1173 throw new IllegalArgumentException("You cannot change private secure settings.");
1174 } else {
1175 throw new IllegalArgumentException("You cannot keep your settings in"
1176 + " the secure settings.");
1177 }
1178 }
1179 }
1180
1181 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1182 if (requestingUserId == UserHandle.getCallingUserId()) {
1183 return requestingUserId;
1184 }
1185 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1186 Binder.getCallingUid(), requestingUserId, false, true,
1187 "get/set setting for user", null);
1188 }
1189
1190 private static Bundle packageValueForCallResult(Setting setting) {
1191 if (setting == null) {
1192 return NULL_SETTING;
1193 }
1194 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1195 }
1196
1197 private static int getRequestingUserId(Bundle args) {
1198 final int callingUserId = UserHandle.getCallingUserId();
1199 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1200 : callingUserId;
1201 }
1202
1203 private static String getSettingValue(Bundle args) {
1204 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1205 }
1206
1207 private static String getValidTableOrThrow(Uri uri) {
1208 if (uri.getPathSegments().size() > 0) {
1209 String table = uri.getPathSegments().get(0);
1210 if (DatabaseHelper.isValidTable(table)) {
1211 return table;
1212 }
1213 throw new IllegalArgumentException("Bad root path: " + table);
1214 }
1215 throw new IllegalArgumentException("Invalid URI:" + uri);
1216 }
1217
1218 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1219 if (setting == null) {
1220 return new MatrixCursor(projection, 0);
1221 }
1222 MatrixCursor cursor = new MatrixCursor(projection, 1);
1223 appendSettingToCursor(cursor, setting);
1224 return cursor;
1225 }
1226
1227 private static String[] normalizeProjection(String[] projection) {
1228 if (projection == null) {
1229 return ALL_COLUMNS;
1230 }
1231
1232 final int columnCount = projection.length;
1233 for (int i = 0; i < columnCount; i++) {
1234 String column = projection[i];
1235 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1236 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001237 }
1238 }
1239
Svetoslav683914b2015-01-15 14:22:26 -08001240 return projection;
1241 }
1242
1243 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1244 final int columnCount = cursor.getColumnCount();
1245
1246 String[] values = new String[columnCount];
1247
1248 for (int i = 0; i < columnCount; i++) {
1249 String column = cursor.getColumnName(i);
1250
1251 switch (column) {
1252 case Settings.NameValueTable._ID: {
1253 values[i] = setting.getId();
1254 } break;
1255
1256 case Settings.NameValueTable.NAME: {
1257 values[i] = setting.getName();
1258 } break;
1259
1260 case Settings.NameValueTable.VALUE: {
1261 values[i] = setting.getValue();
1262 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001263 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001264 }
1265
Svetoslav683914b2015-01-15 14:22:26 -08001266 cursor.addRow(values);
1267 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001268
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001269 private static boolean isKeyValid(String key) {
1270 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1271 }
1272
Svetoslav683914b2015-01-15 14:22:26 -08001273 private static final class Arguments {
1274 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1275 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1276
1277 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1278 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1279
1280 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1281 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1282
1283 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1284 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1285
1286 public final String table;
1287 public final String name;
1288
1289 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1290 final int segmentSize = uri.getPathSegments().size();
1291 switch (segmentSize) {
1292 case 1: {
1293 if (where != null
1294 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1295 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1296 && whereArgs.length == 1) {
1297 name = whereArgs[0];
1298 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001299 return;
Svetoslav683914b2015-01-15 14:22:26 -08001300 } else if (where != null
1301 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1302 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1303 final int startIndex = Math.max(where.indexOf("'"),
1304 where.indexOf("\"")) + 1;
1305 final int endIndex = Math.max(where.lastIndexOf("'"),
1306 where.lastIndexOf("\""));
1307 name = where.substring(startIndex, endIndex);
1308 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001309 return;
Svetoslav683914b2015-01-15 14:22:26 -08001310 } else if (supportAll && where == null && whereArgs == null) {
1311 name = null;
1312 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001313 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001314 }
Svetoslav683914b2015-01-15 14:22:26 -08001315 } break;
1316
Svetoslav28494652015-02-12 14:11:42 -08001317 case 2: {
1318 if (where == null && whereArgs == null) {
1319 name = uri.getPathSegments().get(1);
1320 table = computeTableForSetting(uri, name);
1321 return;
1322 }
1323 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001324 }
Svetoslav28494652015-02-12 14:11:42 -08001325
1326 EventLogTags.writeUnsupportedSettingsQuery(
1327 uri.toSafeString(), where, Arrays.toString(whereArgs));
1328 String message = String.format( "Supported SQL:\n"
1329 + " uri content://some_table/some_property with null where and where args\n"
1330 + " uri content://some_table with query name=? and single name as arg\n"
1331 + " uri content://some_table with query name=some_name and null args\n"
1332 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1333 Arrays.toString(whereArgs));
1334 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001335 }
1336
Svetoslav28494652015-02-12 14:11:42 -08001337 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001338 String table = getValidTableOrThrow(uri);
1339
1340 if (name != null) {
1341 if (sSystemMovedToSecureSettings.contains(name)) {
1342 table = TABLE_SECURE;
1343 }
1344
1345 if (sSystemMovedToGlobalSettings.contains(name)) {
1346 table = TABLE_GLOBAL;
1347 }
1348
1349 if (sSecureMovedToGlobalSettings.contains(name)) {
1350 table = TABLE_GLOBAL;
1351 }
1352
1353 if (sGlobalMovedToSecureSettings.contains(name)) {
1354 table = TABLE_SECURE;
1355 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001356 }
Svetoslav683914b2015-01-15 14:22:26 -08001357
1358 return table;
1359 }
1360 }
1361
1362 final class SettingsRegistry {
1363 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1364
1365 private static final int SETTINGS_TYPE_GLOBAL = 0;
1366 private static final int SETTINGS_TYPE_SYSTEM = 1;
1367 private static final int SETTINGS_TYPE_SECURE = 2;
1368
1369 private static final int SETTINGS_TYPE_MASK = 0xF0000000;
1370 private static final int SETTINGS_TYPE_SHIFT = 28;
1371
1372 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1373 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1374 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1375
1376 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1377
1378 private final BackupManager mBackupManager;
1379
Svetoslav7e0683b2015-08-03 16:02:52 -07001380 private final Handler mHandler;
1381
Svetoslav683914b2015-01-15 14:22:26 -08001382 public SettingsRegistry() {
1383 mBackupManager = new BackupManager(getContext());
Svetoslav7e0683b2015-08-03 16:02:52 -07001384 mHandler = new MyHandler(getContext().getMainLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001385 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001386 }
1387
Svetoslav683914b2015-01-15 14:22:26 -08001388 public List<String> getSettingsNamesLocked(int type, int userId) {
1389 final int key = makeKey(type, userId);
1390 SettingsState settingsState = peekSettingsStateLocked(key);
1391 return settingsState.getSettingNamesLocked();
1392 }
1393
1394 public SettingsState getSettingsLocked(int type, int userId) {
1395 final int key = makeKey(type, userId);
1396 return peekSettingsStateLocked(key);
1397 }
1398
1399 public void ensureSettingsForUserLocked(int userId) {
1400 // Migrate the setting for this user if needed.
1401 migrateLegacySettingsForUserIfNeededLocked(userId);
1402
1403 // Ensure global settings loaded if owner.
1404 if (userId == UserHandle.USER_OWNER) {
1405 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_OWNER);
1406 ensureSettingsStateLocked(globalKey);
1407 }
1408
1409 // Ensure secure settings loaded.
1410 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1411 ensureSettingsStateLocked(secureKey);
1412
1413 // Make sure the secure settings have an Android id set.
1414 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1415 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1416
1417 // Ensure system settings loaded.
1418 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1419 ensureSettingsStateLocked(systemKey);
1420
1421 // Upgrade the settings to the latest version.
1422 UpgradeController upgrader = new UpgradeController(userId);
1423 upgrader.upgradeIfNeededLocked();
1424 }
1425
1426 private void ensureSettingsStateLocked(int key) {
1427 if (mSettingsStates.get(key) == null) {
1428 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1429 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1430 maxBytesPerPackage);
1431 mSettingsStates.put(key, settingsState);
1432 }
1433 }
1434
1435 public void removeUserStateLocked(int userId, boolean permanently) {
1436 // We always keep the global settings in memory.
1437
1438 // Nuke system settings.
1439 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1440 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1441 if (systemSettingsState != null) {
1442 if (permanently) {
1443 mSettingsStates.remove(systemKey);
1444 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001445 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001446 systemSettingsState.destroyLocked(new Runnable() {
1447 @Override
1448 public void run() {
1449 mSettingsStates.remove(systemKey);
1450 }
1451 });
1452 }
1453 }
1454
1455 // Nuke secure settings.
1456 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1457 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1458 if (secureSettingsState != null) {
1459 if (permanently) {
1460 mSettingsStates.remove(secureKey);
1461 secureSettingsState.destroyLocked(null);
1462 } else {
1463 secureSettingsState.destroyLocked(new Runnable() {
1464 @Override
1465 public void run() {
1466 mSettingsStates.remove(secureKey);
1467 }
1468 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001469 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001470 }
1471 }
1472
Svetoslav683914b2015-01-15 14:22:26 -08001473 public boolean insertSettingLocked(int type, int userId, String name, String value,
1474 String packageName) {
1475 final int key = makeKey(type, userId);
1476
1477 SettingsState settingsState = peekSettingsStateLocked(key);
1478 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1479
1480 if (success) {
1481 notifyForSettingsChange(key, name);
1482 }
1483 return success;
1484 }
1485
1486 public boolean deleteSettingLocked(int type, int userId, String name) {
1487 final int key = makeKey(type, userId);
1488
1489 SettingsState settingsState = peekSettingsStateLocked(key);
1490 final boolean success = settingsState.deleteSettingLocked(name);
1491
1492 if (success) {
1493 notifyForSettingsChange(key, name);
1494 }
1495 return success;
1496 }
1497
1498 public Setting getSettingLocked(int type, int userId, String name) {
1499 final int key = makeKey(type, userId);
1500
1501 SettingsState settingsState = peekSettingsStateLocked(key);
1502 return settingsState.getSettingLocked(name);
1503 }
1504
1505 public boolean updateSettingLocked(int type, int userId, String name, String value,
1506 String packageName) {
1507 final int key = makeKey(type, userId);
1508
1509 SettingsState settingsState = peekSettingsStateLocked(key);
1510 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1511
1512 if (success) {
1513 notifyForSettingsChange(key, name);
1514 }
1515
1516 return success;
1517 }
1518
1519 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001520 // Global and secure settings are signature protected. Apps signed
1521 // by the platform certificate are generally not uninstalled and
1522 // the main exception is tests. We trust components signed
1523 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001524
1525 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1526 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001527 if (systemSettings != null) {
1528 systemSettings.onPackageRemovedLocked(packageName);
1529 }
Svetoslav683914b2015-01-15 14:22:26 -08001530 }
1531
1532 private SettingsState peekSettingsStateLocked(int key) {
1533 SettingsState settingsState = mSettingsStates.get(key);
1534 if (settingsState != null) {
1535 return settingsState;
1536 }
1537
1538 ensureSettingsForUserLocked(getUserIdFromKey(key));
1539 return mSettingsStates.get(key);
1540 }
1541
1542 private void migrateAllLegacySettingsIfNeeded() {
1543 synchronized (mLock) {
1544 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_OWNER);
1545 File globalFile = getSettingsFile(key);
1546 if (globalFile.exists()) {
1547 return;
1548 }
1549
1550 final long identity = Binder.clearCallingIdentity();
1551 try {
1552 List<UserInfo> users = mUserManager.getUsers(true);
1553
1554 final int userCount = users.size();
1555 for (int i = 0; i < userCount; i++) {
1556 final int userId = users.get(i).id;
1557
1558 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1559 SQLiteDatabase database = dbHelper.getWritableDatabase();
1560 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1561
1562 // Upgrade to the latest version.
1563 UpgradeController upgrader = new UpgradeController(userId);
1564 upgrader.upgradeIfNeededLocked();
1565
1566 // Drop from memory if not a running user.
1567 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1568 removeUserStateLocked(userId, false);
1569 }
1570 }
1571 } finally {
1572 Binder.restoreCallingIdentity(identity);
1573 }
1574 }
1575 }
1576
1577 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1578 // Every user has secure settings and if no file we need to migrate.
1579 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1580 File secureFile = getSettingsFile(secureKey);
1581 if (secureFile.exists()) {
1582 return;
1583 }
1584
1585 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1586 SQLiteDatabase database = dbHelper.getWritableDatabase();
1587
1588 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1589 }
1590
1591 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1592 SQLiteDatabase database, int userId) {
1593 // Move over the global settings if owner.
1594 if (userId == UserHandle.USER_OWNER) {
1595 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1596 ensureSettingsStateLocked(globalKey);
1597 SettingsState globalSettings = mSettingsStates.get(globalKey);
1598 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1599 globalSettings.persistSyncLocked();
1600 }
1601
1602 // Move over the secure settings.
1603 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1604 ensureSettingsStateLocked(secureKey);
1605 SettingsState secureSettings = mSettingsStates.get(secureKey);
1606 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1607 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1608 secureSettings.persistSyncLocked();
1609
1610 // Move over the system settings.
1611 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1612 ensureSettingsStateLocked(systemKey);
1613 SettingsState systemSettings = mSettingsStates.get(systemKey);
1614 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1615 systemSettings.persistSyncLocked();
1616
1617 // Drop the database as now all is moved and persisted.
1618 if (DROP_DATABASE_ON_MIGRATION) {
1619 dbHelper.dropDatabase();
1620 } else {
1621 dbHelper.backupDatabase();
1622 }
1623 }
1624
1625 private void migrateLegacySettingsLocked(SettingsState settingsState,
1626 SQLiteDatabase database, String table) {
1627 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1628 queryBuilder.setTables(table);
1629
1630 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1631 null, null, null, null, null);
1632
1633 if (cursor == null) {
1634 return;
1635 }
1636
1637 try {
1638 if (!cursor.moveToFirst()) {
1639 return;
1640 }
1641
1642 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1643 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1644
1645 settingsState.setVersionLocked(database.getVersion());
1646
1647 while (!cursor.isAfterLast()) {
1648 String name = cursor.getString(nameColumnIdx);
1649 String value = cursor.getString(valueColumnIdx);
1650 settingsState.insertSettingLocked(name, value,
1651 SettingsState.SYSTEM_PACKAGE_NAME);
1652 cursor.moveToNext();
1653 }
1654 } finally {
1655 cursor.close();
1656 }
1657 }
1658
1659 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1660 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1661
1662 if (value != null) {
1663 return;
1664 }
1665
1666 final int userId = getUserIdFromKey(secureSettings.mKey);
1667
1668 final UserInfo user;
1669 final long identity = Binder.clearCallingIdentity();
1670 try {
1671 user = mUserManager.getUserInfo(userId);
1672 } finally {
1673 Binder.restoreCallingIdentity(identity);
1674 }
1675 if (user == null) {
1676 // Can happen due to races when deleting users - treat as benign.
1677 return;
1678 }
1679
1680 String androidId = Long.toHexString(new SecureRandom().nextLong());
1681 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1682 SettingsState.SYSTEM_PACKAGE_NAME);
1683
1684 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1685 + "] for user " + userId);
1686
1687 // Write a drop box entry if it's a restricted profile
1688 if (user.isRestricted()) {
1689 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1690 Context.DROPBOX_SERVICE);
1691 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1692 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1693 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1694 }
1695 }
1696 }
1697
1698 private void notifyForSettingsChange(int key, String name) {
1699 // Update the system property *first*, so if someone is listening for
1700 // a notification and then using the contract class to get their data,
1701 // the system property will be updated and they'll get the new data.
1702
1703 boolean backedUpDataChanged = false;
1704 String property = null;
1705 if (isGlobalSettingsKey(key)) {
1706 property = Settings.Global.SYS_PROP_SETTING_VERSION;
1707 backedUpDataChanged = true;
1708 } else if (isSecureSettingsKey(key)) {
1709 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
1710 backedUpDataChanged = true;
1711 } else if (isSystemSettingsKey(key)) {
1712 property = Settings.System.SYS_PROP_SETTING_VERSION;
1713 backedUpDataChanged = true;
1714 }
1715
1716 if (property != null) {
1717 final long version = SystemProperties.getLong(property, 0) + 1;
1718 SystemProperties.set(property, Long.toString(version));
1719 if (DEBUG) {
1720 Slog.v(LOG_TAG, "System property " + property + "=" + version);
1721 }
1722 }
1723
1724 // Inform the backup manager about a data change
1725 if (backedUpDataChanged) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001726 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Svetoslav683914b2015-01-15 14:22:26 -08001727 }
1728
1729 // Now send the notification through the content framework.
1730
1731 final int userId = getUserIdFromKey(key);
1732 Uri uri = getNotificationUriFor(key, name);
1733
Svetoslav7e0683b2015-08-03 16:02:52 -07001734 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1735 userId, 0, uri).sendToTarget();
1736
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001737 if (isSecureSettingsKey(key)) {
1738 maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
1739 } else if (isSystemSettingsKey(key)) {
1740 maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
1741 }
1742 }
1743
1744 private void maybeNotifyProfiles(int userId, Uri uri, String name,
1745 Set<String> keysCloned) {
1746 if (keysCloned.contains(name)) {
1747 List<UserInfo> profiles = mUserManager.getProfiles(userId);
1748 int size = profiles.size();
1749 for (int i = 0; i < size; i++) {
1750 UserInfo profile = profiles.get(i);
1751 // the notification for userId has already been sent.
1752 if (profile.id != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001753 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1754 profile.id, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001755 }
1756 }
1757 }
Svetoslav683914b2015-01-15 14:22:26 -08001758 }
1759
1760 private int makeKey(int type, int userId) {
1761 return (type << SETTINGS_TYPE_SHIFT) | userId;
1762 }
1763
1764 private int getTypeFromKey(int key) {
1765 return key >> SETTINGS_TYPE_SHIFT;
1766 }
1767
1768 private int getUserIdFromKey(int key) {
1769 return key & ~SETTINGS_TYPE_MASK;
1770 }
1771
1772 private boolean isGlobalSettingsKey(int key) {
1773 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1774 }
1775
1776 private boolean isSystemSettingsKey(int key) {
1777 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1778 }
1779
1780 private boolean isSecureSettingsKey(int key) {
1781 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1782 }
1783
1784 private File getSettingsFile(int key) {
1785 if (isGlobalSettingsKey(key)) {
1786 final int userId = getUserIdFromKey(key);
1787 return new File(Environment.getUserSystemDirectory(userId),
1788 SETTINGS_FILE_GLOBAL);
1789 } else if (isSystemSettingsKey(key)) {
1790 final int userId = getUserIdFromKey(key);
1791 return new File(Environment.getUserSystemDirectory(userId),
1792 SETTINGS_FILE_SYSTEM);
1793 } else if (isSecureSettingsKey(key)) {
1794 final int userId = getUserIdFromKey(key);
1795 return new File(Environment.getUserSystemDirectory(userId),
1796 SETTINGS_FILE_SECURE);
1797 } else {
1798 throw new IllegalArgumentException("Invalid settings key:" + key);
1799 }
1800 }
1801
1802 private Uri getNotificationUriFor(int key, String name) {
1803 if (isGlobalSettingsKey(key)) {
1804 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
1805 : Settings.Global.CONTENT_URI;
1806 } else if (isSecureSettingsKey(key)) {
1807 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
1808 : Settings.Secure.CONTENT_URI;
1809 } else if (isSystemSettingsKey(key)) {
1810 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
1811 : Settings.System.CONTENT_URI;
1812 } else {
1813 throw new IllegalArgumentException("Invalid settings key:" + key);
1814 }
1815 }
1816
1817 private int getMaxBytesPerPackageForType(int type) {
1818 switch (type) {
1819 case SETTINGS_TYPE_GLOBAL:
1820 case SETTINGS_TYPE_SECURE: {
1821 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
1822 }
1823
1824 default: {
1825 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
1826 }
1827 }
1828 }
1829
Svetoslav7e0683b2015-08-03 16:02:52 -07001830 private final class MyHandler extends Handler {
1831 private static final int MSG_NOTIFY_URI_CHANGED = 1;
1832 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
1833
1834 public MyHandler(Looper looper) {
1835 super(looper);
1836 }
1837
1838 @Override
1839 public void handleMessage(Message msg) {
1840 switch (msg.what) {
1841 case MSG_NOTIFY_URI_CHANGED: {
1842 final int userId = msg.arg1;
1843 Uri uri = (Uri) msg.obj;
1844 getContext().getContentResolver().notifyChange(uri, null, true, userId);
1845 if (DEBUG) {
1846 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
1847 }
1848 } break;
1849
1850 case MSG_NOTIFY_DATA_CHANGED: {
1851 mBackupManager.dataChanged();
1852 } break;
1853 }
1854 }
1855 }
1856
Svetoslav683914b2015-01-15 14:22:26 -08001857 private final class UpgradeController {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02001858 private static final int SETTINGS_VERSION = 122;
Svetoslav683914b2015-01-15 14:22:26 -08001859
1860 private final int mUserId;
1861
1862 public UpgradeController(int userId) {
1863 mUserId = userId;
1864 }
1865
1866 public void upgradeIfNeededLocked() {
1867 // The version of all settings for a user is the same (all users have secure).
1868 SettingsState secureSettings = getSettingsLocked(
1869 SettingsRegistry.SETTINGS_TYPE_SECURE, mUserId);
1870
1871 // Try an update from the current state.
1872 final int oldVersion = secureSettings.getVersionLocked();
1873 final int newVersion = SETTINGS_VERSION;
1874
Svet Ganovc9755bc2015-03-28 13:21:22 -07001875 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08001876 if (oldVersion == newVersion) {
1877 return;
1878 }
1879
1880 // Try to upgrade.
1881 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
1882
1883 // If upgrade failed start from scratch and upgrade.
1884 if (curVersion != newVersion) {
1885 // Drop state we have for this user.
1886 removeUserStateLocked(mUserId, true);
1887
1888 // Recreate the database.
1889 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
1890 SQLiteDatabase database = dbHelper.getWritableDatabase();
1891 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
1892
1893 // Migrate the settings for this user.
1894 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
1895
1896 // Now upgrade should work fine.
1897 onUpgradeLocked(mUserId, oldVersion, newVersion);
1898 }
1899
1900 // Set the global settings version if owner.
1901 if (mUserId == UserHandle.USER_OWNER) {
1902 SettingsState globalSettings = getSettingsLocked(
1903 SettingsRegistry.SETTINGS_TYPE_GLOBAL, mUserId);
1904 globalSettings.setVersionLocked(newVersion);
1905 }
1906
1907 // Set the secure settings version.
1908 secureSettings.setVersionLocked(newVersion);
1909
1910 // Set the system settings version.
1911 SettingsState systemSettings = getSettingsLocked(
1912 SettingsRegistry.SETTINGS_TYPE_SYSTEM, mUserId);
1913 systemSettings.setVersionLocked(newVersion);
1914 }
1915
1916 private SettingsState getGlobalSettingsLocked() {
1917 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_OWNER);
1918 }
1919
1920 private SettingsState getSecureSettingsLocked(int userId) {
1921 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1922 }
1923
1924 private SettingsState getSystemSettingsLocked(int userId) {
1925 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
1926 }
1927
Jeff Brown503cffc2015-03-26 18:08:51 -07001928 /**
1929 * You must perform all necessary mutations to bring the settings
1930 * for this user from the old to the new version. When you add a new
1931 * upgrade step you *must* update SETTINGS_VERSION.
1932 *
1933 * This is an example of moving a setting from secure to global.
1934 *
1935 * // v119: Example settings changes.
1936 * if (currentVersion == 118) {
1937 * if (userId == UserHandle.USER_OWNER) {
1938 * // Remove from the secure settings.
1939 * SettingsState secureSettings = getSecureSettingsLocked(userId);
1940 * String name = "example_setting_to_move";
1941 * String value = secureSettings.getSetting(name);
1942 * secureSettings.deleteSetting(name);
1943 *
1944 * // Add to the global settings.
1945 * SettingsState globalSettings = getGlobalSettingsLocked();
1946 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
1947 * }
1948 *
1949 * // Update the current version.
1950 * currentVersion = 119;
1951 * }
1952 */
Svetoslav683914b2015-01-15 14:22:26 -08001953 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
1954 if (DEBUG) {
1955 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
1956 + oldVersion + " to version: " + newVersion);
1957 }
1958
Jeff Brown503cffc2015-03-26 18:08:51 -07001959 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08001960
John Spurlocke11ae112015-05-11 16:09:03 -04001961 // v119: Reset zen + ringer mode.
1962 if (currentVersion == 118) {
1963 if (userId == UserHandle.USER_OWNER) {
1964 final SettingsState globalSettings = getGlobalSettingsLocked();
1965 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
1966 Integer.toString(Settings.Global.ZEN_MODE_OFF),
1967 SettingsState.SYSTEM_PACKAGE_NAME);
1968 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
1969 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
1970 SettingsState.SYSTEM_PACKAGE_NAME);
1971 }
1972 currentVersion = 119;
1973 }
1974
Jason Monk27bbb2d2015-03-31 16:46:39 -04001975 // v120: Add double tap to wake setting.
1976 if (currentVersion == 119) {
1977 SettingsState secureSettings = getSecureSettingsLocked(userId);
1978 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
1979 getContext().getResources().getBoolean(
1980 R.bool.def_double_tap_to_wake) ? "1" : "0",
1981 SettingsState.SYSTEM_PACKAGE_NAME);
1982
1983 currentVersion = 120;
1984 }
1985
Svetoslav7e0683b2015-08-03 16:02:52 -07001986 if (currentVersion == 120) {
1987 // Before 121, we used a different string encoding logic. We just bump the
1988 // version here; SettingsState knows how to handle pre-version 120 files.
1989 currentVersion = 121;
1990 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001991
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02001992 if (currentVersion == 121) {
1993 // Version 122: allow OEMs to set a default payment component in resources.
1994 // Note that we only write the default if no default has been set;
1995 // if there is, we just leave the default at whatever it currently is.
1996 final SettingsState secureSettings = getSecureSettingsLocked(userId);
1997 String defaultComponent = (getContext().getResources().getString(
1998 R.string.def_nfc_payment_component));
1999 Setting currentSetting = secureSettings.getSettingLocked(
2000 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2001 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2002 currentSetting == null) {
2003 secureSettings.insertSettingLocked(
2004 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2005 defaultComponent,
2006 SettingsState.SYSTEM_PACKAGE_NAME);
2007 }
2008 currentVersion = 122;
2009 }
Jeff Brown503cffc2015-03-26 18:08:51 -07002010 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002011
Jeff Brown503cffc2015-03-26 18:08:51 -07002012 // Return the current version.
2013 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002014 }
2015 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002016 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002017}