blob: bcb459a174a014b30fe053c4f49ac8a4a36ac623 [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;
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;
Xiaohui Chen43765b72015-08-31 10:57:33 -070030import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080031import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070033import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080035import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.sqlite.SQLiteDatabase;
37import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040039import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070041import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070044import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080045import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070046import android.os.Handler;
47import android.os.Looper;
48import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070050import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070051import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070053import android.os.UserHandle;
54import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070055import android.provider.Settings;
56import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080057import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070058import android.util.Slog;
59import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040060
Svetoslav683914b2015-01-15 14:22:26 -080061import com.android.internal.annotations.GuardedBy;
62import com.android.internal.content.PackageMonitor;
63import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080064import com.android.providers.settings.SettingsState.Setting;
John Spurlocke11ae112015-05-11 16:09:03 -040065
Svetoslav683914b2015-01-15 14:22:26 -080066import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080067import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080068import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080069import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080070import java.security.SecureRandom;
71import java.util.Arrays;
72import java.util.List;
Svetoslav683914b2015-01-15 14:22:26 -080073import java.util.Set;
74import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075
Svetoslav683914b2015-01-15 14:22:26 -080076/**
77 * <p>
78 * This class is a content provider that publishes the system settings.
79 * It can be accessed via the content provider APIs or via custom call
80 * commands. The latter is a bit faster and is the preferred way to access
81 * the platform settings.
82 * </p>
83 * <p>
84 * There are three settings types, global (with signature level protection
85 * and shared across users), secure (with signature permission level
86 * protection and per user), and system (with dangerous permission level
87 * protection and per user). Global settings are stored under the device owner.
88 * Each of these settings is represented by a {@link
89 * com.android.providers.settings.SettingsState} object mapped to an integer
90 * key derived from the setting type in the most significant bits and user
91 * id in the least significant bits. Settings are synchronously loaded on
92 * instantiation of a SettingsState and asynchronously persisted on mutation.
93 * Settings are stored in the user specific system directory.
94 * </p>
95 * <p>
96 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
97 * and get a warning. Targeting higher API version prohibits this as the
98 * system settings are not a place for apps to save their state. When a package
99 * is removed the settings it added are deleted. Apps cannot delete system
100 * settings added by the platform. System settings values are validated to
101 * ensure the clients do not put bad values. Global and secure settings are
102 * changed only by trusted parties, therefore no validation is performed. Also
103 * there is a limit on the amount of app specific settings that can be added
104 * to prevent unlimited growth of the system process memory footprint.
105 * </p>
106 */
107@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700108public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800109 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110
Svetoslav683914b2015-01-15 14:22:26 -0800111 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
112
113 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700114
Christopher Tate06efb532012-08-24 15:29:27 -0700115 private static final String TABLE_SYSTEM = "system";
116 private static final String TABLE_SECURE = "secure";
117 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800118
119 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private static final String TABLE_FAVORITES = "favorites";
121 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800122 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
123 private static final String TABLE_BOOKMARKS = "bookmarks";
124 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Svetoslav683914b2015-01-15 14:22:26 -0800126 // The set of removed legacy tables.
127 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700128 static {
Svetoslav683914b2015-01-15 14:22:26 -0800129 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
130 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
131 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
132 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
133 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
134 }
Christopher Tate06efb532012-08-24 15:29:27 -0700135
Svetoslav683914b2015-01-15 14:22:26 -0800136 private static final int MUTATION_OPERATION_INSERT = 1;
137 private static final int MUTATION_OPERATION_DELETE = 2;
138 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400139
Svetoslav683914b2015-01-15 14:22:26 -0800140 private static final String[] ALL_COLUMNS = new String[] {
141 Settings.NameValueTable._ID,
142 Settings.NameValueTable.NAME,
143 Settings.NameValueTable.VALUE
144 };
145
146 private static final Bundle NULL_SETTING = Bundle.forPair(Settings.NameValueTable.VALUE, null);
147
Christopher Tate06efb532012-08-24 15:29:27 -0700148
Svetoslav683914b2015-01-15 14:22:26 -0800149 // Per user secure settings that moved to the for all users global settings.
150 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
151 static {
152 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700153 }
154
Svetoslav683914b2015-01-15 14:22:26 -0800155 // Per user system settings that moved to the for all users global settings.
156 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
157 static {
158 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700159 }
160
Svetoslav683914b2015-01-15 14:22:26 -0800161 // Per user system settings that moved to the per user secure settings.
162 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
163 static {
164 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700165 }
166
Svetoslav683914b2015-01-15 14:22:26 -0800167 // Per all users global settings that moved to the per user secure settings.
168 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
169 static {
170 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700171 }
172
Svetoslav683914b2015-01-15 14:22:26 -0800173 // Per user secure settings that are cloned for the managed profiles of the user.
174 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
175 static {
176 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700177 }
178
Svetoslav683914b2015-01-15 14:22:26 -0800179 // Per user system settings that are cloned for the managed profiles of the user.
180 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
181 static {
182 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400183 }
184
Svetoslav683914b2015-01-15 14:22:26 -0800185 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700186
Svetoslav683914b2015-01-15 14:22:26 -0800187 @GuardedBy("mLock")
188 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700189
Svetoslav7ec28e82015-05-20 17:01:10 -0700190 // We have to call in the user manager with no lock held,
191 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800192
Svetoslav7ec28e82015-05-20 17:01:10 -0700193 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700194 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700195
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196 @Override
197 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800198 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700199 mUserManager = UserManager.get(getContext());
200 mPackageManager = AppGlobals.getPackageManager();
Svetoslav683914b2015-01-15 14:22:26 -0800201 mSettingsRegistry = new SettingsRegistry();
202 }
203 registerBroadcastReceivers();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700204 return true;
205 }
206
Svetoslav683914b2015-01-15 14:22:26 -0800207 @Override
208 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700209 final int requestingUserId = getRequestingUserId(args);
210 switch (method) {
211 case Settings.CALL_METHOD_GET_GLOBAL: {
212 Setting setting = getGlobalSetting(name);
213 return packageValueForCallResult(setting);
Svetoslav683914b2015-01-15 14:22:26 -0800214 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700215
216 case Settings.CALL_METHOD_GET_SECURE: {
217 Setting setting = getSecureSetting(name, requestingUserId);
218 return packageValueForCallResult(setting);
219 }
220
221 case Settings.CALL_METHOD_GET_SYSTEM: {
222 Setting setting = getSystemSetting(name, requestingUserId);
223 return packageValueForCallResult(setting);
224 }
225
226 case Settings.CALL_METHOD_PUT_GLOBAL: {
227 String value = getSettingValue(args);
228 insertGlobalSetting(name, value, requestingUserId);
229 break;
230 }
231
232 case Settings.CALL_METHOD_PUT_SECURE: {
233 String value = getSettingValue(args);
234 insertSecureSetting(name, value, requestingUserId);
235 break;
236 }
237
238 case Settings.CALL_METHOD_PUT_SYSTEM: {
239 String value = getSettingValue(args);
240 insertSystemSetting(name, value, requestingUserId);
241 break;
242 }
243
244 default: {
245 Slog.w(LOG_TAG, "call() with invalid method: " + method);
246 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700247 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700248
Christopher Tate06efb532012-08-24 15:29:27 -0700249 return null;
250 }
251
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800252 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800253 public String getType(Uri uri) {
254 Arguments args = new Arguments(uri, null, null, true);
255 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700256 return "vnd.android.cursor.dir/" + args.table;
257 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700258 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700259 }
260 }
261
262 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800263 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
264 String order) {
265 if (DEBUG) {
266 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 }
268
Svetoslav683914b2015-01-15 14:22:26 -0800269 Arguments args = new Arguments(uri, where, whereArgs, true);
270 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700271
Svetoslav683914b2015-01-15 14:22:26 -0800272 // If a legacy table that is gone, done.
273 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
274 return new MatrixCursor(normalizedProjection, 0);
275 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700276
Svetoslav7ec28e82015-05-20 17:01:10 -0700277 switch (args.table) {
278 case TABLE_GLOBAL: {
279 if (args.name != null) {
280 Setting setting = getGlobalSetting(args.name);
281 return packageSettingForQuery(setting, normalizedProjection);
282 } else {
283 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700284 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700285 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700286
Svetoslav7ec28e82015-05-20 17:01:10 -0700287 case TABLE_SECURE: {
288 final int userId = UserHandle.getCallingUserId();
289 if (args.name != null) {
290 Setting setting = getSecureSetting(args.name, userId);
291 return packageSettingForQuery(setting, normalizedProjection);
292 } else {
293 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800294 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700295 }
Svetoslav683914b2015-01-15 14:22:26 -0800296
Svetoslav7ec28e82015-05-20 17:01:10 -0700297 case TABLE_SYSTEM: {
298 final int userId = UserHandle.getCallingUserId();
299 if (args.name != null) {
300 Setting setting = getSystemSetting(args.name, userId);
301 return packageSettingForQuery(setting, normalizedProjection);
302 } else {
303 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800304 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700305 }
Svetoslav683914b2015-01-15 14:22:26 -0800306
Svetoslav7ec28e82015-05-20 17:01:10 -0700307 default: {
308 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700309 }
310 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700311 }
312
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700313 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800314 public Uri insert(Uri uri, ContentValues values) {
315 if (DEBUG) {
316 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700317 }
318
Svetoslav683914b2015-01-15 14:22:26 -0800319 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700320
Svetoslav683914b2015-01-15 14:22:26 -0800321 // If a legacy table that is gone, done.
322 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 return null;
324 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325
Svetoslav683914b2015-01-15 14:22:26 -0800326 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700327 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800328 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700329 }
330
Svetoslav683914b2015-01-15 14:22:26 -0800331 String value = values.getAsString(Settings.Secure.VALUE);
332
Svetoslav7ec28e82015-05-20 17:01:10 -0700333 switch (table) {
334 case TABLE_GLOBAL: {
335 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId())) {
336 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700337 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700338 } break;
339
340 case TABLE_SECURE: {
341 if (insertSecureSetting(name, value, UserHandle.getCallingUserId())) {
342 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
343 }
344 } break;
345
346 case TABLE_SYSTEM: {
347 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
348 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
349 }
350 } break;
351
352 default: {
353 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700354 }
355 }
356
Svetoslav683914b2015-01-15 14:22:26 -0800357 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700358 }
359
360 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800361 public int bulkInsert(Uri uri, ContentValues[] allValues) {
362 if (DEBUG) {
363 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700365
Svetoslav683914b2015-01-15 14:22:26 -0800366 int insertionCount = 0;
367 final int valuesCount = allValues.length;
368 for (int i = 0; i < valuesCount; i++) {
369 ContentValues values = allValues[i];
370 if (insert(uri, values) != null) {
371 insertionCount++;
372 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700373 }
Svetoslav683914b2015-01-15 14:22:26 -0800374
375 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376 }
377
378 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800379 public int delete(Uri uri, String where, String[] whereArgs) {
380 if (DEBUG) {
381 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700383
Svetoslav683914b2015-01-15 14:22:26 -0800384 Arguments args = new Arguments(uri, where, whereArgs, false);
385
386 // If a legacy table that is gone, done.
387 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
388 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700389 }
Svetoslav683914b2015-01-15 14:22:26 -0800390
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700391 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800392 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700393 }
Svetoslav683914b2015-01-15 14:22:26 -0800394
Svetoslav7ec28e82015-05-20 17:01:10 -0700395 switch (args.table) {
396 case TABLE_GLOBAL: {
397 final int userId = UserHandle.getCallingUserId();
398 return deleteGlobalSetting(args.name, userId) ? 1 : 0;
399 }
Svetoslav683914b2015-01-15 14:22:26 -0800400
Svetoslav7ec28e82015-05-20 17:01:10 -0700401 case TABLE_SECURE: {
402 final int userId = UserHandle.getCallingUserId();
403 return deleteSecureSetting(args.name, userId) ? 1 : 0;
404 }
Svetoslav683914b2015-01-15 14:22:26 -0800405
Svetoslav7ec28e82015-05-20 17:01:10 -0700406 case TABLE_SYSTEM: {
407 final int userId = UserHandle.getCallingUserId();
408 return deleteSystemSetting(args.name, userId) ? 1 : 0;
409 }
410
411 default: {
412 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800413 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700414 }
Svetoslav683914b2015-01-15 14:22:26 -0800415 }
416
417 @Override
418 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
419 if (DEBUG) {
420 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700421 }
Svetoslav683914b2015-01-15 14:22:26 -0800422
423 Arguments args = new Arguments(uri, where, whereArgs, false);
424
425 // If a legacy table that is gone, done.
426 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
427 return 0;
428 }
429
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700430 String name = values.getAsString(Settings.Secure.NAME);
431 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800432 return 0;
433 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700434 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800435
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 switch (args.table) {
437 case TABLE_GLOBAL: {
438 final int userId = UserHandle.getCallingUserId();
439 return updateGlobalSetting(args.name, value, userId) ? 1 : 0;
440 }
Svetoslav683914b2015-01-15 14:22:26 -0800441
Svetoslav7ec28e82015-05-20 17:01:10 -0700442 case TABLE_SECURE: {
443 final int userId = UserHandle.getCallingUserId();
444 return updateSecureSetting(args.name, value, userId) ? 1 : 0;
445 }
Svetoslav683914b2015-01-15 14:22:26 -0800446
Svetoslav7ec28e82015-05-20 17:01:10 -0700447 case TABLE_SYSTEM: {
448 final int userId = UserHandle.getCallingUserId();
449 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
450 }
Svetoslav683914b2015-01-15 14:22:26 -0800451
Svetoslav7ec28e82015-05-20 17:01:10 -0700452 default: {
453 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800454 }
455 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700456 }
457
458 @Override
459 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey3b566b82014-11-12 10:39:56 -0800460 throw new FileNotFoundException("Direct file access no longer supported; "
461 + "ringtone playback is available through android.media.Ringtone");
Marco Nelissen69f593c2009-07-28 09:55:04 -0700462 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800463
Svetoslavb505ccc2015-02-17 12:41:04 -0800464 @Override
465 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
466 synchronized (mLock) {
467 final long identity = Binder.clearCallingIdentity();
468 try {
469 List<UserInfo> users = mUserManager.getUsers(true);
470 final int userCount = users.size();
471 for (int i = 0; i < userCount; i++) {
472 UserInfo user = users.get(i);
473 dumpForUser(user.id, pw);
474 }
475 } finally {
476 Binder.restoreCallingIdentity(identity);
477 }
478 }
479 }
480
481 private void dumpForUser(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700482 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800483 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700484 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800485 dumpSettings(globalCursor, pw);
486 pw.println();
487 }
488
489 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700490 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800491 dumpSettings(secureCursor, pw);
492 pw.println();
493
494 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700495 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800496 dumpSettings(systemCursor, pw);
497 pw.println();
498 }
499
500 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700501 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800502 return;
503 }
504
505 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
506 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
507 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
508
509 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700510 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
511 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
512 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800513 pw.println();
514 } while (cursor.moveToNext());
515 }
516
Svetoslav7e0683b2015-08-03 16:02:52 -0700517 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700518 if (s != null) {
519 return s;
520 }
521 return "{null}";
522 }
523
Svetoslav683914b2015-01-15 14:22:26 -0800524 private void registerBroadcastReceivers() {
525 IntentFilter userFilter = new IntentFilter();
526 userFilter.addAction(Intent.ACTION_USER_REMOVED);
527 userFilter.addAction(Intent.ACTION_USER_STOPPED);
528
529 getContext().registerReceiver(new BroadcastReceiver() {
530 @Override
531 public void onReceive(Context context, Intent intent) {
532 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700533 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800534
535 switch (intent.getAction()) {
536 case Intent.ACTION_USER_REMOVED: {
537 mSettingsRegistry.removeUserStateLocked(userId, true);
538 } break;
539
540 case Intent.ACTION_USER_STOPPED: {
541 mSettingsRegistry.removeUserStateLocked(userId, false);
542 } break;
543 }
544 }
545 }, userFilter);
546
547 PackageMonitor monitor = new PackageMonitor() {
548 @Override
549 public void onPackageRemoved(String packageName, int uid) {
550 synchronized (mLock) {
551 mSettingsRegistry.onPackageRemovedLocked(packageName,
552 UserHandle.getUserId(uid));
553 }
554 }
555 };
556
557 // package changes
558 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
559 UserHandle.ALL, true);
560 }
561
Svetoslav7ec28e82015-05-20 17:01:10 -0700562 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800563 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700564 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800565 }
566
Svetoslav7ec28e82015-05-20 17:01:10 -0700567 synchronized (mLock) {
568 // Get the settings.
569 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Xiaohui Chen43765b72015-08-31 10:57:33 -0700570 SettingsRegistry.SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800571
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800573
Svetoslav7ec28e82015-05-20 17:01:10 -0700574 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800575
Svetoslav7ec28e82015-05-20 17:01:10 -0700576 String[] normalizedProjection = normalizeProjection(projection);
577 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800578
Svetoslav7ec28e82015-05-20 17:01:10 -0700579 // Anyone can get the global settings, so no security checks.
580 for (int i = 0; i < nameCount; i++) {
581 String name = names.get(i);
582 Setting setting = settingsState.getSettingLocked(name);
583 appendSettingToCursor(result, setting);
584 }
585
586 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800587 }
Svetoslav683914b2015-01-15 14:22:26 -0800588 }
589
Svetoslav7ec28e82015-05-20 17:01:10 -0700590 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800591 if (DEBUG) {
592 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
593 }
594
595 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700596 synchronized (mLock) {
597 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700598 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800599 }
Svetoslav683914b2015-01-15 14:22:26 -0800600 }
601
Svetoslav7ec28e82015-05-20 17:01:10 -0700602 private boolean updateGlobalSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800603 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700604 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800605 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700606 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800607 }
608
Svetoslav7ec28e82015-05-20 17:01:10 -0700609 private boolean insertGlobalSetting(String name, String value, int requestingUserId) {
610 if (DEBUG) {
611 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
612 }
613 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
614 }
615
616 private boolean deleteGlobalSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800617 if (DEBUG) {
618 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
619 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700620 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800621 }
622
Svetoslav7ec28e82015-05-20 17:01:10 -0700623 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800624 int operation) {
625 // Make sure the caller can change the settings - treated as secure.
626 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
627
Svetoslav683914b2015-01-15 14:22:26 -0800628 // Resolve the userId on whose behalf the call is made.
629 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
630
Makoto Onuki28da2e32015-11-20 11:30:44 -0800631 // If this is a setting that is currently restricted for this user, do not allow
632 // unrestricting changes.
633 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800634 return false;
635 }
636
637 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700638 synchronized (mLock) {
639 switch (operation) {
640 case MUTATION_OPERATION_INSERT: {
641 return mSettingsRegistry
642 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700643 UserHandle.USER_SYSTEM, name, value, getCallingPackage());
Svetoslav7ec28e82015-05-20 17:01:10 -0700644 }
Svetoslav683914b2015-01-15 14:22:26 -0800645
Svetoslav7ec28e82015-05-20 17:01:10 -0700646 case MUTATION_OPERATION_DELETE: {
647 return mSettingsRegistry.deleteSettingLocked(
648 SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700649 UserHandle.USER_SYSTEM, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700650 }
Svetoslav683914b2015-01-15 14:22:26 -0800651
Svetoslav7ec28e82015-05-20 17:01:10 -0700652 case MUTATION_OPERATION_UPDATE: {
653 return mSettingsRegistry
654 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700655 UserHandle.USER_SYSTEM, name, value, getCallingPackage());
Svetoslav7ec28e82015-05-20 17:01:10 -0700656 }
Svetoslav683914b2015-01-15 14:22:26 -0800657 }
658 }
659
660 return false;
661 }
662
Svetoslav7ec28e82015-05-20 17:01:10 -0700663 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800664 if (DEBUG) {
665 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
666 }
667
668 // Resolve the userId on whose behalf the call is made.
669 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
670
Svetoslav7ec28e82015-05-20 17:01:10 -0700671 synchronized (mLock) {
672 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
673 SettingsRegistry.SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800674
Svetoslav7ec28e82015-05-20 17:01:10 -0700675 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800676
Svetoslav7ec28e82015-05-20 17:01:10 -0700677 String[] normalizedProjection = normalizeProjection(projection);
678 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800679
Svetoslav7ec28e82015-05-20 17:01:10 -0700680 for (int i = 0; i < nameCount; i++) {
681 String name = names.get(i);
682 // Determine the owning user as some profile settings are cloned from the parent.
683 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
684 name);
Svetoslav683914b2015-01-15 14:22:26 -0800685
Svetoslav7ec28e82015-05-20 17:01:10 -0700686 // Special case for location (sigh).
687 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
688 return null;
689 }
Svetoslav683914b2015-01-15 14:22:26 -0800690
Svetoslav7ec28e82015-05-20 17:01:10 -0700691 Setting setting = mSettingsRegistry.getSettingLocked(
692 SettingsRegistry.SETTINGS_TYPE_SECURE, owningUserId, name);
693 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800694 }
695
Svetoslav7ec28e82015-05-20 17:01:10 -0700696 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800697 }
Svetoslav683914b2015-01-15 14:22:26 -0800698 }
699
Svetoslav7ec28e82015-05-20 17:01:10 -0700700 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800701 if (DEBUG) {
702 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
703 }
704
705 // Resolve the userId on whose behalf the call is made.
706 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
707
708 // Determine the owning user as some profile settings are cloned from the parent.
709 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
710
711 // Special case for location (sigh).
712 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
713 return null;
714 }
715
716 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700717 synchronized (mLock) {
718 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
719 owningUserId, name);
720 }
Svetoslav683914b2015-01-15 14:22:26 -0800721 }
722
Svetoslav7ec28e82015-05-20 17:01:10 -0700723 private boolean insertSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800724 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700725 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800726 + requestingUserId + ")");
727 }
728
Svetoslav7ec28e82015-05-20 17:01:10 -0700729 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800730 }
731
Svetoslav7ec28e82015-05-20 17:01:10 -0700732 private boolean deleteSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800733 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700734 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800735 }
736
Svetoslav7ec28e82015-05-20 17:01:10 -0700737 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800738 }
739
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 private boolean updateSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800741 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700742 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800743 + requestingUserId + ")");
744 }
745
Svetoslav7ec28e82015-05-20 17:01:10 -0700746 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800747 }
748
Svetoslav7ec28e82015-05-20 17:01:10 -0700749 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800750 int operation) {
751 // Make sure the caller can change the settings.
752 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
753
Svetoslav683914b2015-01-15 14:22:26 -0800754 // Resolve the userId on whose behalf the call is made.
755 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
756
Makoto Onuki28da2e32015-11-20 11:30:44 -0800757 // If this is a setting that is currently restricted for this user, do not allow
758 // unrestricting changes.
759 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800760 return false;
761 }
762
763 // Determine the owning user as some profile settings are cloned from the parent.
764 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
765
766 // Only the owning user can change the setting.
767 if (owningUserId != callingUserId) {
768 return false;
769 }
770
771 // Special cases for location providers (sigh).
772 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslavb596a2c2015-02-17 21:37:09 -0800773 return updateLocationProvidersAllowedLocked(value, owningUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800774 }
775
776 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700777 synchronized (mLock) {
778 switch (operation) {
779 case MUTATION_OPERATION_INSERT: {
780 return mSettingsRegistry
781 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
782 owningUserId, name, value, getCallingPackage());
783 }
Svetoslav683914b2015-01-15 14:22:26 -0800784
Svetoslav7ec28e82015-05-20 17:01:10 -0700785 case MUTATION_OPERATION_DELETE: {
786 return mSettingsRegistry.deleteSettingLocked(
787 SettingsRegistry.SETTINGS_TYPE_SECURE,
788 owningUserId, name);
789 }
Svetoslav683914b2015-01-15 14:22:26 -0800790
Svetoslav7ec28e82015-05-20 17:01:10 -0700791 case MUTATION_OPERATION_UPDATE: {
792 return mSettingsRegistry
793 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
794 owningUserId, name, value, getCallingPackage());
795 }
Svetoslav683914b2015-01-15 14:22:26 -0800796 }
797 }
798
799 return false;
800 }
801
Svetoslav7ec28e82015-05-20 17:01:10 -0700802 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800803 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700804 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800805 }
806
807 // Resolve the userId on whose behalf the call is made.
808 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
809
Svetoslav7ec28e82015-05-20 17:01:10 -0700810 synchronized (mLock) {
811 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
812 SettingsRegistry.SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800813
Svetoslav7ec28e82015-05-20 17:01:10 -0700814 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800815
Svetoslav7ec28e82015-05-20 17:01:10 -0700816 String[] normalizedProjection = normalizeProjection(projection);
817 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800818
Svetoslav7ec28e82015-05-20 17:01:10 -0700819 for (int i = 0; i < nameCount; i++) {
820 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800821
Svetoslav7ec28e82015-05-20 17:01:10 -0700822 // Determine the owning user as some profile settings are cloned from the parent.
823 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
824 name);
Svetoslav683914b2015-01-15 14:22:26 -0800825
Svetoslav7ec28e82015-05-20 17:01:10 -0700826 Setting setting = mSettingsRegistry.getSettingLocked(
827 SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name);
828 appendSettingToCursor(result, setting);
829 }
830
831 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800832 }
Svetoslav683914b2015-01-15 14:22:26 -0800833 }
834
Svetoslav7ec28e82015-05-20 17:01:10 -0700835 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800836 if (DEBUG) {
837 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
838 }
839
840 // Resolve the userId on whose behalf the call is made.
841 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
842
843 // Determine the owning user as some profile settings are cloned from the parent.
844 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
845
846 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700847 synchronized (mLock) {
848 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
849 owningUserId, name);
850 }
Svetoslav683914b2015-01-15 14:22:26 -0800851 }
852
Svetoslav7ec28e82015-05-20 17:01:10 -0700853 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800854 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700855 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800856 + requestingUserId + ")");
857 }
858
Svetoslav7ec28e82015-05-20 17:01:10 -0700859 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800860 }
861
Svetoslav7ec28e82015-05-20 17:01:10 -0700862 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800863 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700864 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800865 }
866
Svetoslav7ec28e82015-05-20 17:01:10 -0700867 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800868 }
869
Svetoslav7ec28e82015-05-20 17:01:10 -0700870 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800871 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800873 + requestingUserId + ")");
874 }
875
Svetoslav7ec28e82015-05-20 17:01:10 -0700876 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800877 }
878
Svetoslav7ec28e82015-05-20 17:01:10 -0700879 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800880 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +0100881 if (!hasWriteSecureSettingsPermission()) {
882 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
883 // operation is allowed for the calling package through appops.
884 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
885 Binder.getCallingUid(), getCallingPackage(), true)) {
886 return false;
887 }
Svetoslav683914b2015-01-15 14:22:26 -0800888 }
889
Svetoslav683914b2015-01-15 14:22:26 -0800890 // Resolve the userId on whose behalf the call is made.
891 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
892
Svetoslavd8d25e02015-11-20 13:09:26 -0800893 // Enforce what the calling package can mutate the system settings.
894 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
895
Svetoslav683914b2015-01-15 14:22:26 -0800896 // Determine the owning user as some profile settings are cloned from the parent.
897 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
898
899 // Only the owning user id can change the setting.
900 if (owningUserId != callingUserId) {
901 return false;
902 }
903
904 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700905 synchronized (mLock) {
906 switch (operation) {
907 case MUTATION_OPERATION_INSERT: {
908 validateSystemSettingValue(name, value);
909 return mSettingsRegistry
910 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
911 owningUserId, name, value, getCallingPackage());
912 }
913
914 case MUTATION_OPERATION_DELETE: {
915 return mSettingsRegistry.deleteSettingLocked(
916 SettingsRegistry.SETTINGS_TYPE_SYSTEM,
917 owningUserId, name);
918 }
919
920 case MUTATION_OPERATION_UPDATE: {
921 validateSystemSettingValue(name, value);
922 return mSettingsRegistry
923 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
924 owningUserId, name, value, getCallingPackage());
925 }
Svetoslav683914b2015-01-15 14:22:26 -0800926 }
927
Svetoslav7ec28e82015-05-20 17:01:10 -0700928 return false;
Svetoslav683914b2015-01-15 14:22:26 -0800929 }
Svetoslav683914b2015-01-15 14:22:26 -0800930 }
931
Billy Lau6ad2d662015-07-18 00:26:58 +0100932 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -0700933 // Write secure settings is a more protected permission. If caller has it we are good.
934 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
935 == PackageManager.PERMISSION_GRANTED) {
936 return true;
937 }
938
Svetoslavf41334b2015-06-23 12:06:03 -0700939 return false;
940 }
941
Svetoslav683914b2015-01-15 14:22:26 -0800942 private void validateSystemSettingValue(String name, String value) {
943 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
944 if (validator != null && !validator.validate(value)) {
945 throw new IllegalArgumentException("Invalid value: " + value
946 + " for setting: " + name);
947 }
948 }
949
950 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
951 int owningUserId) {
952 // Optimization - location providers are restricted only for managed profiles.
953 if (callingUserId == owningUserId) {
954 return false;
955 }
956 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
957 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
958 new UserHandle(callingUserId))) {
959 return true;
960 }
961 return false;
962 }
963
Makoto Onuki28da2e32015-11-20 11:30:44 -0800964 /**
965 * Checks whether changing a setting to a value is prohibited by the corresponding user
966 * restriction.
967 *
968 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestrictionLR},
969 * which should be in sync with this method.
970 *
971 * @return true if the change is prohibited, false if the change is allowed.
972 */
973 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
974 String value) {
975 String restriction;
976 switch (setting) {
977 case Settings.Secure.LOCATION_MODE:
978 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
979 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
980 // here normally, but we still protect it here from a direct provider write.
981 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
982 restriction = UserManager.DISALLOW_SHARE_LOCATION;
983 break;
984
985 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
986 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
987 // a provider, which should be allowed even if the user restriction is set.
988 if (value != null && value.startsWith("-")) return false;
989 restriction = UserManager.DISALLOW_SHARE_LOCATION;
990 break;
991
992 case Settings.Secure.INSTALL_NON_MARKET_APPS:
993 if ("0".equals(value)) return false;
994 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
995 break;
996
997 case Settings.Global.ADB_ENABLED:
998 if ("0".equals(value)) return false;
999 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1000 break;
1001
1002 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1003 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1004 if ("1".equals(value)) return false;
1005 restriction = UserManager.ENSURE_VERIFY_APPS;
1006 break;
1007
1008 case Settings.Global.PREFERRED_NETWORK_MODE:
1009 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1010 break;
1011
1012 default:
1013 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001014 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001015
1016 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001017 }
1018
1019 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1020 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1021 }
1022
1023 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1024 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1025 }
1026
1027 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1028 final int parentId = getGroupParentLocked(userId);
1029 if (parentId != userId && keys.contains(name)) {
1030 return parentId;
1031 }
1032 return userId;
1033 }
1034
Svetoslavf41334b2015-06-23 12:06:03 -07001035 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001036 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001037 // System/root/shell can mutate whatever secure settings they want.
1038 final int callingUid = Binder.getCallingUid();
1039 if (callingUid == android.os.Process.SYSTEM_UID
1040 || callingUid == Process.SHELL_UID
1041 || callingUid == Process.ROOT_UID) {
1042 return;
1043 }
1044
1045 switch (operation) {
1046 case MUTATION_OPERATION_INSERT:
1047 // Insert updates.
1048 case MUTATION_OPERATION_UPDATE: {
1049 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1050 return;
1051 }
1052
1053 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001054 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001055
1056 // Privileged apps can do whatever they want.
1057 if ((packageInfo.applicationInfo.privateFlags
1058 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1059 return;
1060 }
1061
1062 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1063 packageInfo.applicationInfo.targetSdkVersion, name);
1064 } break;
1065
1066 case MUTATION_OPERATION_DELETE: {
1067 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1068 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1069 throw new IllegalArgumentException("You cannot delete system defined"
1070 + " secure settings.");
1071 }
1072
1073 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001074 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001075
1076 // Privileged apps can do whatever they want.
1077 if ((packageInfo.applicationInfo.privateFlags &
1078 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1079 return;
1080 }
1081
1082 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1083 packageInfo.applicationInfo.targetSdkVersion, name);
1084 } break;
1085 }
1086 }
1087
Xiaohui Chen43765b72015-08-31 10:57:33 -07001088 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001089 try {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001090 return mPackageManager.getPackageInfo(getCallingPackage(), 0, userId);
1091 } catch (RemoteException e) {
Svetoslav683914b2015-01-15 14:22:26 -08001092 throw new IllegalStateException("Calling package doesn't exist");
1093 }
1094 }
1095
1096 private int getGroupParentLocked(int userId) {
1097 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001098 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001099 return userId;
1100 }
1101 // We are in the same process with the user manager and the returned
1102 // user info is a cached instance, so just look up instead of cache.
1103 final long identity = Binder.clearCallingIdentity();
1104 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001105 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001106 UserInfo userInfo = mUserManager.getProfileParent(userId);
1107 return (userInfo != null) ? userInfo.id : userId;
1108 } finally {
1109 Binder.restoreCallingIdentity(identity);
1110 }
1111 }
1112
Svetoslav683914b2015-01-15 14:22:26 -08001113 private void enforceWritePermission(String permission) {
1114 if (getContext().checkCallingOrSelfPermission(permission)
1115 != PackageManager.PERMISSION_GRANTED) {
1116 throw new SecurityException("Permission denial: writing to settings requires:"
1117 + permission);
1118 }
1119 }
1120
1121 /*
1122 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1123 * This setting contains a list of the currently enabled location providers.
1124 * But helper functions in android.providers.Settings can enable or disable
1125 * a single provider by using a "+" or "-" prefix before the provider name.
1126 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001127 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1128 * is set, the said method will only allow values with the "-" prefix.
1129 *
Svetoslav683914b2015-01-15 14:22:26 -08001130 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001131 */
Svetoslavb596a2c2015-02-17 21:37:09 -08001132 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001133 if (TextUtils.isEmpty(value)) {
1134 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001135 }
1136
Svetoslav683914b2015-01-15 14:22:26 -08001137 final char prefix = value.charAt(0);
1138 if (prefix != '+' && prefix != '-') {
1139 return false;
1140 }
1141
1142 // skip prefix
1143 value = value.substring(1);
1144
Svetoslav7ec28e82015-05-20 17:01:10 -07001145 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001146 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1147
1148 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1149
1150 int index = oldProviders.indexOf(value);
1151 int end = index + value.length();
1152
1153 // check for commas to avoid matching on partial string
1154 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1155 index = -1;
1156 }
1157
1158 // check for commas to avoid matching on partial string
1159 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1160 index = -1;
1161 }
1162
1163 String newProviders;
1164
1165 if (prefix == '+' && index < 0) {
1166 // append the provider to the list if not present
1167 if (oldProviders.length() == 0) {
1168 newProviders = value;
1169 } else {
1170 newProviders = oldProviders + ',' + value;
1171 }
1172 } else if (prefix == '-' && index >= 0) {
1173 // remove the provider from the list if present
1174 // remove leading or trailing comma
1175 if (index > 0) {
1176 index--;
1177 } else if (end < oldProviders.length()) {
1178 end++;
1179 }
1180
1181 newProviders = oldProviders.substring(0, index);
1182 if (end < oldProviders.length()) {
1183 newProviders += oldProviders.substring(end);
1184 }
1185 } else {
1186 // nothing changed, so no need to update the database
1187 return false;
1188 }
1189
Svetoslavb596a2c2015-02-17 21:37:09 -08001190 return mSettingsRegistry.insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
1191 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1192 getCallingPackage());
Svetoslav683914b2015-01-15 14:22:26 -08001193 }
1194
Svetoslav683914b2015-01-15 14:22:26 -08001195 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1196 int targetSdkVersion, String name) {
1197 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1198 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1199 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1200 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1201 + " This will soon become an error.");
1202 } else {
1203 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1204 + " This will soon become an error.");
1205 }
1206 } else {
1207 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1208 throw new IllegalArgumentException("You cannot change private secure settings.");
1209 } else {
1210 throw new IllegalArgumentException("You cannot keep your settings in"
1211 + " the secure settings.");
1212 }
1213 }
1214 }
1215
1216 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1217 if (requestingUserId == UserHandle.getCallingUserId()) {
1218 return requestingUserId;
1219 }
1220 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1221 Binder.getCallingUid(), requestingUserId, false, true,
1222 "get/set setting for user", null);
1223 }
1224
1225 private static Bundle packageValueForCallResult(Setting setting) {
1226 if (setting == null) {
1227 return NULL_SETTING;
1228 }
1229 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1230 }
1231
1232 private static int getRequestingUserId(Bundle args) {
1233 final int callingUserId = UserHandle.getCallingUserId();
1234 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1235 : callingUserId;
1236 }
1237
1238 private static String getSettingValue(Bundle args) {
1239 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1240 }
1241
1242 private static String getValidTableOrThrow(Uri uri) {
1243 if (uri.getPathSegments().size() > 0) {
1244 String table = uri.getPathSegments().get(0);
1245 if (DatabaseHelper.isValidTable(table)) {
1246 return table;
1247 }
1248 throw new IllegalArgumentException("Bad root path: " + table);
1249 }
1250 throw new IllegalArgumentException("Invalid URI:" + uri);
1251 }
1252
1253 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1254 if (setting == null) {
1255 return new MatrixCursor(projection, 0);
1256 }
1257 MatrixCursor cursor = new MatrixCursor(projection, 1);
1258 appendSettingToCursor(cursor, setting);
1259 return cursor;
1260 }
1261
1262 private static String[] normalizeProjection(String[] projection) {
1263 if (projection == null) {
1264 return ALL_COLUMNS;
1265 }
1266
1267 final int columnCount = projection.length;
1268 for (int i = 0; i < columnCount; i++) {
1269 String column = projection[i];
1270 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1271 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001272 }
1273 }
1274
Svetoslav683914b2015-01-15 14:22:26 -08001275 return projection;
1276 }
1277
1278 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1279 final int columnCount = cursor.getColumnCount();
1280
1281 String[] values = new String[columnCount];
1282
1283 for (int i = 0; i < columnCount; i++) {
1284 String column = cursor.getColumnName(i);
1285
1286 switch (column) {
1287 case Settings.NameValueTable._ID: {
1288 values[i] = setting.getId();
1289 } break;
1290
1291 case Settings.NameValueTable.NAME: {
1292 values[i] = setting.getName();
1293 } break;
1294
1295 case Settings.NameValueTable.VALUE: {
1296 values[i] = setting.getValue();
1297 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001298 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001299 }
1300
Svetoslav683914b2015-01-15 14:22:26 -08001301 cursor.addRow(values);
1302 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001303
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001304 private static boolean isKeyValid(String key) {
1305 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1306 }
1307
Svetoslav683914b2015-01-15 14:22:26 -08001308 private static final class Arguments {
1309 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1310 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1311
1312 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1313 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1314
1315 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1316 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1317
1318 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1319 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1320
1321 public final String table;
1322 public final String name;
1323
1324 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1325 final int segmentSize = uri.getPathSegments().size();
1326 switch (segmentSize) {
1327 case 1: {
1328 if (where != null
1329 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1330 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1331 && whereArgs.length == 1) {
1332 name = whereArgs[0];
1333 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001334 return;
Svetoslav683914b2015-01-15 14:22:26 -08001335 } else if (where != null
1336 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1337 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1338 final int startIndex = Math.max(where.indexOf("'"),
1339 where.indexOf("\"")) + 1;
1340 final int endIndex = Math.max(where.lastIndexOf("'"),
1341 where.lastIndexOf("\""));
1342 name = where.substring(startIndex, endIndex);
1343 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001344 return;
Svetoslav683914b2015-01-15 14:22:26 -08001345 } else if (supportAll && where == null && whereArgs == null) {
1346 name = null;
1347 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001348 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001349 }
Svetoslav683914b2015-01-15 14:22:26 -08001350 } break;
1351
Svetoslav28494652015-02-12 14:11:42 -08001352 case 2: {
1353 if (where == null && whereArgs == null) {
1354 name = uri.getPathSegments().get(1);
1355 table = computeTableForSetting(uri, name);
1356 return;
1357 }
1358 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001359 }
Svetoslav28494652015-02-12 14:11:42 -08001360
1361 EventLogTags.writeUnsupportedSettingsQuery(
1362 uri.toSafeString(), where, Arrays.toString(whereArgs));
1363 String message = String.format( "Supported SQL:\n"
1364 + " uri content://some_table/some_property with null where and where args\n"
1365 + " uri content://some_table with query name=? and single name as arg\n"
1366 + " uri content://some_table with query name=some_name and null args\n"
1367 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1368 Arrays.toString(whereArgs));
1369 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001370 }
1371
Svetoslav28494652015-02-12 14:11:42 -08001372 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001373 String table = getValidTableOrThrow(uri);
1374
1375 if (name != null) {
1376 if (sSystemMovedToSecureSettings.contains(name)) {
1377 table = TABLE_SECURE;
1378 }
1379
1380 if (sSystemMovedToGlobalSettings.contains(name)) {
1381 table = TABLE_GLOBAL;
1382 }
1383
1384 if (sSecureMovedToGlobalSettings.contains(name)) {
1385 table = TABLE_GLOBAL;
1386 }
1387
1388 if (sGlobalMovedToSecureSettings.contains(name)) {
1389 table = TABLE_SECURE;
1390 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001391 }
Svetoslav683914b2015-01-15 14:22:26 -08001392
1393 return table;
1394 }
1395 }
1396
1397 final class SettingsRegistry {
1398 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1399
1400 private static final int SETTINGS_TYPE_GLOBAL = 0;
1401 private static final int SETTINGS_TYPE_SYSTEM = 1;
1402 private static final int SETTINGS_TYPE_SECURE = 2;
1403
1404 private static final int SETTINGS_TYPE_MASK = 0xF0000000;
1405 private static final int SETTINGS_TYPE_SHIFT = 28;
1406
1407 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1408 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1409 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1410
1411 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1412
1413 private final BackupManager mBackupManager;
1414
Svetoslav7e0683b2015-08-03 16:02:52 -07001415 private final Handler mHandler;
1416
Svetoslav683914b2015-01-15 14:22:26 -08001417 public SettingsRegistry() {
1418 mBackupManager = new BackupManager(getContext());
Svetoslav7e0683b2015-08-03 16:02:52 -07001419 mHandler = new MyHandler(getContext().getMainLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001420 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001421 }
1422
Svetoslav683914b2015-01-15 14:22:26 -08001423 public List<String> getSettingsNamesLocked(int type, int userId) {
1424 final int key = makeKey(type, userId);
1425 SettingsState settingsState = peekSettingsStateLocked(key);
1426 return settingsState.getSettingNamesLocked();
1427 }
1428
1429 public SettingsState getSettingsLocked(int type, int userId) {
1430 final int key = makeKey(type, userId);
1431 return peekSettingsStateLocked(key);
1432 }
1433
1434 public void ensureSettingsForUserLocked(int userId) {
1435 // Migrate the setting for this user if needed.
1436 migrateLegacySettingsForUserIfNeededLocked(userId);
1437
1438 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001439 if (userId == UserHandle.USER_SYSTEM) {
1440 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001441 ensureSettingsStateLocked(globalKey);
1442 }
1443
1444 // Ensure secure settings loaded.
1445 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1446 ensureSettingsStateLocked(secureKey);
1447
1448 // Make sure the secure settings have an Android id set.
1449 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1450 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1451
1452 // Ensure system settings loaded.
1453 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1454 ensureSettingsStateLocked(systemKey);
1455
1456 // Upgrade the settings to the latest version.
1457 UpgradeController upgrader = new UpgradeController(userId);
1458 upgrader.upgradeIfNeededLocked();
1459 }
1460
1461 private void ensureSettingsStateLocked(int key) {
1462 if (mSettingsStates.get(key) == null) {
1463 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1464 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1465 maxBytesPerPackage);
1466 mSettingsStates.put(key, settingsState);
1467 }
1468 }
1469
1470 public void removeUserStateLocked(int userId, boolean permanently) {
1471 // We always keep the global settings in memory.
1472
1473 // Nuke system settings.
1474 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1475 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1476 if (systemSettingsState != null) {
1477 if (permanently) {
1478 mSettingsStates.remove(systemKey);
1479 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001480 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001481 systemSettingsState.destroyLocked(new Runnable() {
1482 @Override
1483 public void run() {
1484 mSettingsStates.remove(systemKey);
1485 }
1486 });
1487 }
1488 }
1489
1490 // Nuke secure settings.
1491 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1492 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1493 if (secureSettingsState != null) {
1494 if (permanently) {
1495 mSettingsStates.remove(secureKey);
1496 secureSettingsState.destroyLocked(null);
1497 } else {
1498 secureSettingsState.destroyLocked(new Runnable() {
1499 @Override
1500 public void run() {
1501 mSettingsStates.remove(secureKey);
1502 }
1503 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001504 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001505 }
1506 }
1507
Svetoslav683914b2015-01-15 14:22:26 -08001508 public boolean insertSettingLocked(int type, int userId, String name, String value,
1509 String packageName) {
1510 final int key = makeKey(type, userId);
1511
1512 SettingsState settingsState = peekSettingsStateLocked(key);
1513 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1514
1515 if (success) {
1516 notifyForSettingsChange(key, name);
1517 }
1518 return success;
1519 }
1520
1521 public boolean deleteSettingLocked(int type, int userId, String name) {
1522 final int key = makeKey(type, userId);
1523
1524 SettingsState settingsState = peekSettingsStateLocked(key);
1525 final boolean success = settingsState.deleteSettingLocked(name);
1526
1527 if (success) {
1528 notifyForSettingsChange(key, name);
1529 }
1530 return success;
1531 }
1532
1533 public Setting getSettingLocked(int type, int userId, String name) {
1534 final int key = makeKey(type, userId);
1535
1536 SettingsState settingsState = peekSettingsStateLocked(key);
1537 return settingsState.getSettingLocked(name);
1538 }
1539
1540 public boolean updateSettingLocked(int type, int userId, String name, String value,
1541 String packageName) {
1542 final int key = makeKey(type, userId);
1543
1544 SettingsState settingsState = peekSettingsStateLocked(key);
1545 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1546
1547 if (success) {
1548 notifyForSettingsChange(key, name);
1549 }
1550
1551 return success;
1552 }
1553
1554 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001555 // Global and secure settings are signature protected. Apps signed
1556 // by the platform certificate are generally not uninstalled and
1557 // the main exception is tests. We trust components signed
1558 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001559
1560 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1561 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001562 if (systemSettings != null) {
1563 systemSettings.onPackageRemovedLocked(packageName);
1564 }
Svetoslav683914b2015-01-15 14:22:26 -08001565 }
1566
1567 private SettingsState peekSettingsStateLocked(int key) {
1568 SettingsState settingsState = mSettingsStates.get(key);
1569 if (settingsState != null) {
1570 return settingsState;
1571 }
1572
1573 ensureSettingsForUserLocked(getUserIdFromKey(key));
1574 return mSettingsStates.get(key);
1575 }
1576
1577 private void migrateAllLegacySettingsIfNeeded() {
1578 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001579 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001580 File globalFile = getSettingsFile(key);
1581 if (globalFile.exists()) {
1582 return;
1583 }
1584
1585 final long identity = Binder.clearCallingIdentity();
1586 try {
1587 List<UserInfo> users = mUserManager.getUsers(true);
1588
1589 final int userCount = users.size();
1590 for (int i = 0; i < userCount; i++) {
1591 final int userId = users.get(i).id;
1592
1593 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1594 SQLiteDatabase database = dbHelper.getWritableDatabase();
1595 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1596
1597 // Upgrade to the latest version.
1598 UpgradeController upgrader = new UpgradeController(userId);
1599 upgrader.upgradeIfNeededLocked();
1600
1601 // Drop from memory if not a running user.
1602 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1603 removeUserStateLocked(userId, false);
1604 }
1605 }
1606 } finally {
1607 Binder.restoreCallingIdentity(identity);
1608 }
1609 }
1610 }
1611
1612 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1613 // Every user has secure settings and if no file we need to migrate.
1614 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1615 File secureFile = getSettingsFile(secureKey);
1616 if (secureFile.exists()) {
1617 return;
1618 }
1619
1620 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1621 SQLiteDatabase database = dbHelper.getWritableDatabase();
1622
1623 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1624 }
1625
1626 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1627 SQLiteDatabase database, int userId) {
1628 // Move over the global settings if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001629 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001630 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1631 ensureSettingsStateLocked(globalKey);
1632 SettingsState globalSettings = mSettingsStates.get(globalKey);
1633 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1634 globalSettings.persistSyncLocked();
1635 }
1636
1637 // Move over the secure settings.
1638 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1639 ensureSettingsStateLocked(secureKey);
1640 SettingsState secureSettings = mSettingsStates.get(secureKey);
1641 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1642 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1643 secureSettings.persistSyncLocked();
1644
1645 // Move over the system settings.
1646 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1647 ensureSettingsStateLocked(systemKey);
1648 SettingsState systemSettings = mSettingsStates.get(systemKey);
1649 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1650 systemSettings.persistSyncLocked();
1651
1652 // Drop the database as now all is moved and persisted.
1653 if (DROP_DATABASE_ON_MIGRATION) {
1654 dbHelper.dropDatabase();
1655 } else {
1656 dbHelper.backupDatabase();
1657 }
1658 }
1659
1660 private void migrateLegacySettingsLocked(SettingsState settingsState,
1661 SQLiteDatabase database, String table) {
1662 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1663 queryBuilder.setTables(table);
1664
1665 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1666 null, null, null, null, null);
1667
1668 if (cursor == null) {
1669 return;
1670 }
1671
1672 try {
1673 if (!cursor.moveToFirst()) {
1674 return;
1675 }
1676
1677 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1678 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1679
1680 settingsState.setVersionLocked(database.getVersion());
1681
1682 while (!cursor.isAfterLast()) {
1683 String name = cursor.getString(nameColumnIdx);
1684 String value = cursor.getString(valueColumnIdx);
1685 settingsState.insertSettingLocked(name, value,
1686 SettingsState.SYSTEM_PACKAGE_NAME);
1687 cursor.moveToNext();
1688 }
1689 } finally {
1690 cursor.close();
1691 }
1692 }
1693
1694 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1695 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1696
1697 if (value != null) {
1698 return;
1699 }
1700
1701 final int userId = getUserIdFromKey(secureSettings.mKey);
1702
1703 final UserInfo user;
1704 final long identity = Binder.clearCallingIdentity();
1705 try {
1706 user = mUserManager.getUserInfo(userId);
1707 } finally {
1708 Binder.restoreCallingIdentity(identity);
1709 }
1710 if (user == null) {
1711 // Can happen due to races when deleting users - treat as benign.
1712 return;
1713 }
1714
1715 String androidId = Long.toHexString(new SecureRandom().nextLong());
1716 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1717 SettingsState.SYSTEM_PACKAGE_NAME);
1718
1719 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1720 + "] for user " + userId);
1721
1722 // Write a drop box entry if it's a restricted profile
1723 if (user.isRestricted()) {
1724 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1725 Context.DROPBOX_SERVICE);
1726 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1727 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1728 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1729 }
1730 }
1731 }
1732
1733 private void notifyForSettingsChange(int key, String name) {
1734 // Update the system property *first*, so if someone is listening for
1735 // a notification and then using the contract class to get their data,
1736 // the system property will be updated and they'll get the new data.
1737
1738 boolean backedUpDataChanged = false;
1739 String property = null;
1740 if (isGlobalSettingsKey(key)) {
1741 property = Settings.Global.SYS_PROP_SETTING_VERSION;
1742 backedUpDataChanged = true;
1743 } else if (isSecureSettingsKey(key)) {
1744 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
1745 backedUpDataChanged = true;
1746 } else if (isSystemSettingsKey(key)) {
1747 property = Settings.System.SYS_PROP_SETTING_VERSION;
1748 backedUpDataChanged = true;
1749 }
1750
1751 if (property != null) {
1752 final long version = SystemProperties.getLong(property, 0) + 1;
1753 SystemProperties.set(property, Long.toString(version));
1754 if (DEBUG) {
1755 Slog.v(LOG_TAG, "System property " + property + "=" + version);
1756 }
1757 }
1758
1759 // Inform the backup manager about a data change
1760 if (backedUpDataChanged) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001761 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Svetoslav683914b2015-01-15 14:22:26 -08001762 }
1763
1764 // Now send the notification through the content framework.
1765
1766 final int userId = getUserIdFromKey(key);
1767 Uri uri = getNotificationUriFor(key, name);
1768
Svetoslav7e0683b2015-08-03 16:02:52 -07001769 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1770 userId, 0, uri).sendToTarget();
1771
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001772 if (isSecureSettingsKey(key)) {
1773 maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
1774 } else if (isSystemSettingsKey(key)) {
1775 maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
1776 }
1777 }
1778
1779 private void maybeNotifyProfiles(int userId, Uri uri, String name,
1780 Set<String> keysCloned) {
1781 if (keysCloned.contains(name)) {
1782 List<UserInfo> profiles = mUserManager.getProfiles(userId);
1783 int size = profiles.size();
1784 for (int i = 0; i < size; i++) {
1785 UserInfo profile = profiles.get(i);
1786 // the notification for userId has already been sent.
1787 if (profile.id != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001788 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1789 profile.id, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001790 }
1791 }
1792 }
Svetoslav683914b2015-01-15 14:22:26 -08001793 }
1794
1795 private int makeKey(int type, int userId) {
1796 return (type << SETTINGS_TYPE_SHIFT) | userId;
1797 }
1798
1799 private int getTypeFromKey(int key) {
1800 return key >> SETTINGS_TYPE_SHIFT;
1801 }
1802
1803 private int getUserIdFromKey(int key) {
1804 return key & ~SETTINGS_TYPE_MASK;
1805 }
1806
1807 private boolean isGlobalSettingsKey(int key) {
1808 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1809 }
1810
1811 private boolean isSystemSettingsKey(int key) {
1812 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1813 }
1814
1815 private boolean isSecureSettingsKey(int key) {
1816 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1817 }
1818
1819 private File getSettingsFile(int key) {
1820 if (isGlobalSettingsKey(key)) {
1821 final int userId = getUserIdFromKey(key);
1822 return new File(Environment.getUserSystemDirectory(userId),
1823 SETTINGS_FILE_GLOBAL);
1824 } else if (isSystemSettingsKey(key)) {
1825 final int userId = getUserIdFromKey(key);
1826 return new File(Environment.getUserSystemDirectory(userId),
1827 SETTINGS_FILE_SYSTEM);
1828 } else if (isSecureSettingsKey(key)) {
1829 final int userId = getUserIdFromKey(key);
1830 return new File(Environment.getUserSystemDirectory(userId),
1831 SETTINGS_FILE_SECURE);
1832 } else {
1833 throw new IllegalArgumentException("Invalid settings key:" + key);
1834 }
1835 }
1836
1837 private Uri getNotificationUriFor(int key, String name) {
1838 if (isGlobalSettingsKey(key)) {
1839 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
1840 : Settings.Global.CONTENT_URI;
1841 } else if (isSecureSettingsKey(key)) {
1842 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
1843 : Settings.Secure.CONTENT_URI;
1844 } else if (isSystemSettingsKey(key)) {
1845 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
1846 : Settings.System.CONTENT_URI;
1847 } else {
1848 throw new IllegalArgumentException("Invalid settings key:" + key);
1849 }
1850 }
1851
1852 private int getMaxBytesPerPackageForType(int type) {
1853 switch (type) {
1854 case SETTINGS_TYPE_GLOBAL:
1855 case SETTINGS_TYPE_SECURE: {
1856 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
1857 }
1858
1859 default: {
1860 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
1861 }
1862 }
1863 }
1864
Svetoslav7e0683b2015-08-03 16:02:52 -07001865 private final class MyHandler extends Handler {
1866 private static final int MSG_NOTIFY_URI_CHANGED = 1;
1867 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
1868
1869 public MyHandler(Looper looper) {
1870 super(looper);
1871 }
1872
1873 @Override
1874 public void handleMessage(Message msg) {
1875 switch (msg.what) {
1876 case MSG_NOTIFY_URI_CHANGED: {
1877 final int userId = msg.arg1;
1878 Uri uri = (Uri) msg.obj;
1879 getContext().getContentResolver().notifyChange(uri, null, true, userId);
1880 if (DEBUG) {
1881 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
1882 }
1883 } break;
1884
1885 case MSG_NOTIFY_DATA_CHANGED: {
1886 mBackupManager.dataChanged();
1887 } break;
1888 }
1889 }
1890 }
1891
Svetoslav683914b2015-01-15 14:22:26 -08001892 private final class UpgradeController {
Bryce Leebd179282015-12-17 19:01:37 -08001893 private static final int SETTINGS_VERSION = 124;
Svetoslav683914b2015-01-15 14:22:26 -08001894
1895 private final int mUserId;
1896
1897 public UpgradeController(int userId) {
1898 mUserId = userId;
1899 }
1900
1901 public void upgradeIfNeededLocked() {
1902 // The version of all settings for a user is the same (all users have secure).
1903 SettingsState secureSettings = getSettingsLocked(
1904 SettingsRegistry.SETTINGS_TYPE_SECURE, mUserId);
1905
1906 // Try an update from the current state.
1907 final int oldVersion = secureSettings.getVersionLocked();
1908 final int newVersion = SETTINGS_VERSION;
1909
Svet Ganovc9755bc2015-03-28 13:21:22 -07001910 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08001911 if (oldVersion == newVersion) {
1912 return;
1913 }
1914
1915 // Try to upgrade.
1916 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
1917
1918 // If upgrade failed start from scratch and upgrade.
1919 if (curVersion != newVersion) {
1920 // Drop state we have for this user.
1921 removeUserStateLocked(mUserId, true);
1922
1923 // Recreate the database.
1924 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
1925 SQLiteDatabase database = dbHelper.getWritableDatabase();
1926 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
1927
1928 // Migrate the settings for this user.
1929 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
1930
1931 // Now upgrade should work fine.
1932 onUpgradeLocked(mUserId, oldVersion, newVersion);
1933 }
1934
1935 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001936 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001937 SettingsState globalSettings = getSettingsLocked(
1938 SettingsRegistry.SETTINGS_TYPE_GLOBAL, mUserId);
1939 globalSettings.setVersionLocked(newVersion);
1940 }
1941
1942 // Set the secure settings version.
1943 secureSettings.setVersionLocked(newVersion);
1944
1945 // Set the system settings version.
1946 SettingsState systemSettings = getSettingsLocked(
1947 SettingsRegistry.SETTINGS_TYPE_SYSTEM, mUserId);
1948 systemSettings.setVersionLocked(newVersion);
1949 }
1950
1951 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001952 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001953 }
1954
1955 private SettingsState getSecureSettingsLocked(int userId) {
1956 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1957 }
1958
1959 private SettingsState getSystemSettingsLocked(int userId) {
1960 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
1961 }
1962
Jeff Brown503cffc2015-03-26 18:08:51 -07001963 /**
1964 * You must perform all necessary mutations to bring the settings
1965 * for this user from the old to the new version. When you add a new
1966 * upgrade step you *must* update SETTINGS_VERSION.
1967 *
1968 * This is an example of moving a setting from secure to global.
1969 *
1970 * // v119: Example settings changes.
1971 * if (currentVersion == 118) {
1972 * if (userId == UserHandle.USER_OWNER) {
1973 * // Remove from the secure settings.
1974 * SettingsState secureSettings = getSecureSettingsLocked(userId);
1975 * String name = "example_setting_to_move";
1976 * String value = secureSettings.getSetting(name);
1977 * secureSettings.deleteSetting(name);
1978 *
1979 * // Add to the global settings.
1980 * SettingsState globalSettings = getGlobalSettingsLocked();
1981 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
1982 * }
1983 *
1984 * // Update the current version.
1985 * currentVersion = 119;
1986 * }
1987 */
Svetoslav683914b2015-01-15 14:22:26 -08001988 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
1989 if (DEBUG) {
1990 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
1991 + oldVersion + " to version: " + newVersion);
1992 }
1993
Jeff Brown503cffc2015-03-26 18:08:51 -07001994 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08001995
John Spurlocke11ae112015-05-11 16:09:03 -04001996 // v119: Reset zen + ringer mode.
1997 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001998 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04001999 final SettingsState globalSettings = getGlobalSettingsLocked();
2000 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2001 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2002 SettingsState.SYSTEM_PACKAGE_NAME);
2003 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2004 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2005 SettingsState.SYSTEM_PACKAGE_NAME);
2006 }
2007 currentVersion = 119;
2008 }
2009
Jason Monk27bbb2d2015-03-31 16:46:39 -04002010 // v120: Add double tap to wake setting.
2011 if (currentVersion == 119) {
2012 SettingsState secureSettings = getSecureSettingsLocked(userId);
2013 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2014 getContext().getResources().getBoolean(
2015 R.bool.def_double_tap_to_wake) ? "1" : "0",
2016 SettingsState.SYSTEM_PACKAGE_NAME);
2017
2018 currentVersion = 120;
2019 }
2020
Svetoslav7e0683b2015-08-03 16:02:52 -07002021 if (currentVersion == 120) {
2022 // Before 121, we used a different string encoding logic. We just bump the
2023 // version here; SettingsState knows how to handle pre-version 120 files.
2024 currentVersion = 121;
2025 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002026
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002027 if (currentVersion == 121) {
2028 // Version 122: allow OEMs to set a default payment component in resources.
2029 // Note that we only write the default if no default has been set;
2030 // if there is, we just leave the default at whatever it currently is.
2031 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2032 String defaultComponent = (getContext().getResources().getString(
2033 R.string.def_nfc_payment_component));
2034 Setting currentSetting = secureSettings.getSettingLocked(
2035 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2036 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2037 currentSetting == null) {
2038 secureSettings.insertSettingLocked(
2039 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2040 defaultComponent,
2041 SettingsState.SYSTEM_PACKAGE_NAME);
2042 }
2043 currentVersion = 122;
2044 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002045
2046 if (currentVersion == 122) {
2047 // Version 123: Adding a default value for the ability to add a user from
2048 // the lock screen.
2049 if (userId == UserHandle.USER_SYSTEM) {
2050 final SettingsState globalSettings = getGlobalSettingsLocked();
2051 Setting currentSetting = globalSettings.getSettingLocked(
2052 Settings.Global.ADD_USERS_WHEN_LOCKED);
2053 if (currentSetting == null) {
2054 globalSettings.insertSettingLocked(
2055 Settings.Global.ADD_USERS_WHEN_LOCKED,
2056 getContext().getResources().getBoolean(
2057 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2058 SettingsState.SYSTEM_PACKAGE_NAME);
2059 }
2060 }
2061 currentVersion = 123;
2062 }
Bryce Leebd179282015-12-17 19:01:37 -08002063
2064 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002065 final SettingsState globalSettings = getGlobalSettingsLocked();
2066 String defaultDisabledProfiles = (getContext().getResources().getString(
2067 R.string.def_bluetooth_disabled_profiles));
2068 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2069 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002070 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002071 }
2072
Jeff Brown503cffc2015-03-26 18:08:51 -07002073 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002074
Jeff Brown503cffc2015-03-26 18:08:51 -07002075 // Return the current version.
2076 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002077 }
2078 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002079 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002080}