blob: 57d495f6f93614e75bf60cd6636d4cf0dd1e4466 [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:
Mahaver Chopra87648752016-01-08 19:23:57 +00001013 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001014 if ("0".equals(value)) return false;
1015 restriction = UserManager.DISALLOW_DATA_ROAMING;
1016 break;
1017 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001018 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001019 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001020
1021 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001022 }
1023
1024 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1025 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1026 }
1027
1028 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1029 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1030 }
1031
1032 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1033 final int parentId = getGroupParentLocked(userId);
1034 if (parentId != userId && keys.contains(name)) {
1035 return parentId;
1036 }
1037 return userId;
1038 }
1039
Svetoslavf41334b2015-06-23 12:06:03 -07001040 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001041 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001042 // System/root/shell can mutate whatever secure settings they want.
1043 final int callingUid = Binder.getCallingUid();
1044 if (callingUid == android.os.Process.SYSTEM_UID
1045 || callingUid == Process.SHELL_UID
1046 || callingUid == Process.ROOT_UID) {
1047 return;
1048 }
1049
1050 switch (operation) {
1051 case MUTATION_OPERATION_INSERT:
1052 // Insert updates.
1053 case MUTATION_OPERATION_UPDATE: {
1054 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1055 return;
1056 }
1057
1058 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001059 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001060
1061 // Privileged apps can do whatever they want.
1062 if ((packageInfo.applicationInfo.privateFlags
1063 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1064 return;
1065 }
1066
1067 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1068 packageInfo.applicationInfo.targetSdkVersion, name);
1069 } break;
1070
1071 case MUTATION_OPERATION_DELETE: {
1072 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1073 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1074 throw new IllegalArgumentException("You cannot delete system defined"
1075 + " secure settings.");
1076 }
1077
1078 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001079 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001080
1081 // Privileged apps can do whatever they want.
1082 if ((packageInfo.applicationInfo.privateFlags &
1083 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1084 return;
1085 }
1086
1087 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1088 packageInfo.applicationInfo.targetSdkVersion, name);
1089 } break;
1090 }
1091 }
1092
Xiaohui Chen43765b72015-08-31 10:57:33 -07001093 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001094 try {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001095 return mPackageManager.getPackageInfo(getCallingPackage(), 0, userId);
1096 } catch (RemoteException e) {
Svetoslav683914b2015-01-15 14:22:26 -08001097 throw new IllegalStateException("Calling package doesn't exist");
1098 }
1099 }
1100
1101 private int getGroupParentLocked(int userId) {
1102 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001103 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001104 return userId;
1105 }
1106 // We are in the same process with the user manager and the returned
1107 // user info is a cached instance, so just look up instead of cache.
1108 final long identity = Binder.clearCallingIdentity();
1109 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001110 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001111 UserInfo userInfo = mUserManager.getProfileParent(userId);
1112 return (userInfo != null) ? userInfo.id : userId;
1113 } finally {
1114 Binder.restoreCallingIdentity(identity);
1115 }
1116 }
1117
Svetoslav683914b2015-01-15 14:22:26 -08001118 private void enforceWritePermission(String permission) {
1119 if (getContext().checkCallingOrSelfPermission(permission)
1120 != PackageManager.PERMISSION_GRANTED) {
1121 throw new SecurityException("Permission denial: writing to settings requires:"
1122 + permission);
1123 }
1124 }
1125
1126 /*
1127 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1128 * This setting contains a list of the currently enabled location providers.
1129 * But helper functions in android.providers.Settings can enable or disable
1130 * a single provider by using a "+" or "-" prefix before the provider name.
1131 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001132 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1133 * is set, the said method will only allow values with the "-" prefix.
1134 *
Svetoslav683914b2015-01-15 14:22:26 -08001135 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001136 */
Svetoslavb596a2c2015-02-17 21:37:09 -08001137 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001138 if (TextUtils.isEmpty(value)) {
1139 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001140 }
1141
Svetoslav683914b2015-01-15 14:22:26 -08001142 final char prefix = value.charAt(0);
1143 if (prefix != '+' && prefix != '-') {
1144 return false;
1145 }
1146
1147 // skip prefix
1148 value = value.substring(1);
1149
Svetoslav7ec28e82015-05-20 17:01:10 -07001150 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001151 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1152
1153 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1154
1155 int index = oldProviders.indexOf(value);
1156 int end = index + value.length();
1157
1158 // check for commas to avoid matching on partial string
1159 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1160 index = -1;
1161 }
1162
1163 // check for commas to avoid matching on partial string
1164 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1165 index = -1;
1166 }
1167
1168 String newProviders;
1169
1170 if (prefix == '+' && index < 0) {
1171 // append the provider to the list if not present
1172 if (oldProviders.length() == 0) {
1173 newProviders = value;
1174 } else {
1175 newProviders = oldProviders + ',' + value;
1176 }
1177 } else if (prefix == '-' && index >= 0) {
1178 // remove the provider from the list if present
1179 // remove leading or trailing comma
1180 if (index > 0) {
1181 index--;
1182 } else if (end < oldProviders.length()) {
1183 end++;
1184 }
1185
1186 newProviders = oldProviders.substring(0, index);
1187 if (end < oldProviders.length()) {
1188 newProviders += oldProviders.substring(end);
1189 }
1190 } else {
1191 // nothing changed, so no need to update the database
1192 return false;
1193 }
1194
Svetoslavb596a2c2015-02-17 21:37:09 -08001195 return mSettingsRegistry.insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
1196 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1197 getCallingPackage());
Svetoslav683914b2015-01-15 14:22:26 -08001198 }
1199
Svetoslav683914b2015-01-15 14:22:26 -08001200 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1201 int targetSdkVersion, String name) {
1202 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1203 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1204 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1205 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1206 + " This will soon become an error.");
1207 } else {
1208 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1209 + " This will soon become an error.");
1210 }
1211 } else {
1212 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1213 throw new IllegalArgumentException("You cannot change private secure settings.");
1214 } else {
1215 throw new IllegalArgumentException("You cannot keep your settings in"
1216 + " the secure settings.");
1217 }
1218 }
1219 }
1220
1221 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1222 if (requestingUserId == UserHandle.getCallingUserId()) {
1223 return requestingUserId;
1224 }
1225 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1226 Binder.getCallingUid(), requestingUserId, false, true,
1227 "get/set setting for user", null);
1228 }
1229
1230 private static Bundle packageValueForCallResult(Setting setting) {
1231 if (setting == null) {
1232 return NULL_SETTING;
1233 }
1234 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1235 }
1236
1237 private static int getRequestingUserId(Bundle args) {
1238 final int callingUserId = UserHandle.getCallingUserId();
1239 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1240 : callingUserId;
1241 }
1242
1243 private static String getSettingValue(Bundle args) {
1244 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1245 }
1246
1247 private static String getValidTableOrThrow(Uri uri) {
1248 if (uri.getPathSegments().size() > 0) {
1249 String table = uri.getPathSegments().get(0);
1250 if (DatabaseHelper.isValidTable(table)) {
1251 return table;
1252 }
1253 throw new IllegalArgumentException("Bad root path: " + table);
1254 }
1255 throw new IllegalArgumentException("Invalid URI:" + uri);
1256 }
1257
1258 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1259 if (setting == null) {
1260 return new MatrixCursor(projection, 0);
1261 }
1262 MatrixCursor cursor = new MatrixCursor(projection, 1);
1263 appendSettingToCursor(cursor, setting);
1264 return cursor;
1265 }
1266
1267 private static String[] normalizeProjection(String[] projection) {
1268 if (projection == null) {
1269 return ALL_COLUMNS;
1270 }
1271
1272 final int columnCount = projection.length;
1273 for (int i = 0; i < columnCount; i++) {
1274 String column = projection[i];
1275 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1276 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001277 }
1278 }
1279
Svetoslav683914b2015-01-15 14:22:26 -08001280 return projection;
1281 }
1282
1283 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1284 final int columnCount = cursor.getColumnCount();
1285
1286 String[] values = new String[columnCount];
1287
1288 for (int i = 0; i < columnCount; i++) {
1289 String column = cursor.getColumnName(i);
1290
1291 switch (column) {
1292 case Settings.NameValueTable._ID: {
1293 values[i] = setting.getId();
1294 } break;
1295
1296 case Settings.NameValueTable.NAME: {
1297 values[i] = setting.getName();
1298 } break;
1299
1300 case Settings.NameValueTable.VALUE: {
1301 values[i] = setting.getValue();
1302 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001303 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001304 }
1305
Svetoslav683914b2015-01-15 14:22:26 -08001306 cursor.addRow(values);
1307 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001308
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001309 private static boolean isKeyValid(String key) {
1310 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1311 }
1312
Svetoslav683914b2015-01-15 14:22:26 -08001313 private static final class Arguments {
1314 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1315 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1316
1317 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1318 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1319
1320 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1321 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1322
1323 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1324 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1325
1326 public final String table;
1327 public final String name;
1328
1329 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1330 final int segmentSize = uri.getPathSegments().size();
1331 switch (segmentSize) {
1332 case 1: {
1333 if (where != null
1334 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1335 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1336 && whereArgs.length == 1) {
1337 name = whereArgs[0];
1338 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001339 return;
Svetoslav683914b2015-01-15 14:22:26 -08001340 } else if (where != null
1341 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1342 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1343 final int startIndex = Math.max(where.indexOf("'"),
1344 where.indexOf("\"")) + 1;
1345 final int endIndex = Math.max(where.lastIndexOf("'"),
1346 where.lastIndexOf("\""));
1347 name = where.substring(startIndex, endIndex);
1348 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001349 return;
Svetoslav683914b2015-01-15 14:22:26 -08001350 } else if (supportAll && where == null && whereArgs == null) {
1351 name = null;
1352 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001353 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001354 }
Svetoslav683914b2015-01-15 14:22:26 -08001355 } break;
1356
Svetoslav28494652015-02-12 14:11:42 -08001357 case 2: {
1358 if (where == null && whereArgs == null) {
1359 name = uri.getPathSegments().get(1);
1360 table = computeTableForSetting(uri, name);
1361 return;
1362 }
1363 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001364 }
Svetoslav28494652015-02-12 14:11:42 -08001365
1366 EventLogTags.writeUnsupportedSettingsQuery(
1367 uri.toSafeString(), where, Arrays.toString(whereArgs));
1368 String message = String.format( "Supported SQL:\n"
1369 + " uri content://some_table/some_property with null where and where args\n"
1370 + " uri content://some_table with query name=? and single name as arg\n"
1371 + " uri content://some_table with query name=some_name and null args\n"
1372 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1373 Arrays.toString(whereArgs));
1374 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001375 }
1376
Svetoslav28494652015-02-12 14:11:42 -08001377 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001378 String table = getValidTableOrThrow(uri);
1379
1380 if (name != null) {
1381 if (sSystemMovedToSecureSettings.contains(name)) {
1382 table = TABLE_SECURE;
1383 }
1384
1385 if (sSystemMovedToGlobalSettings.contains(name)) {
1386 table = TABLE_GLOBAL;
1387 }
1388
1389 if (sSecureMovedToGlobalSettings.contains(name)) {
1390 table = TABLE_GLOBAL;
1391 }
1392
1393 if (sGlobalMovedToSecureSettings.contains(name)) {
1394 table = TABLE_SECURE;
1395 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001396 }
Svetoslav683914b2015-01-15 14:22:26 -08001397
1398 return table;
1399 }
1400 }
1401
1402 final class SettingsRegistry {
1403 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1404
1405 private static final int SETTINGS_TYPE_GLOBAL = 0;
1406 private static final int SETTINGS_TYPE_SYSTEM = 1;
1407 private static final int SETTINGS_TYPE_SECURE = 2;
1408
1409 private static final int SETTINGS_TYPE_MASK = 0xF0000000;
1410 private static final int SETTINGS_TYPE_SHIFT = 28;
1411
1412 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1413 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1414 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1415
1416 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1417
1418 private final BackupManager mBackupManager;
1419
Svetoslav7e0683b2015-08-03 16:02:52 -07001420 private final Handler mHandler;
1421
Svetoslav683914b2015-01-15 14:22:26 -08001422 public SettingsRegistry() {
1423 mBackupManager = new BackupManager(getContext());
Svetoslav7e0683b2015-08-03 16:02:52 -07001424 mHandler = new MyHandler(getContext().getMainLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001425 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001426 }
1427
Svetoslav683914b2015-01-15 14:22:26 -08001428 public List<String> getSettingsNamesLocked(int type, int userId) {
1429 final int key = makeKey(type, userId);
1430 SettingsState settingsState = peekSettingsStateLocked(key);
1431 return settingsState.getSettingNamesLocked();
1432 }
1433
1434 public SettingsState getSettingsLocked(int type, int userId) {
1435 final int key = makeKey(type, userId);
1436 return peekSettingsStateLocked(key);
1437 }
1438
1439 public void ensureSettingsForUserLocked(int userId) {
1440 // Migrate the setting for this user if needed.
1441 migrateLegacySettingsForUserIfNeededLocked(userId);
1442
1443 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001444 if (userId == UserHandle.USER_SYSTEM) {
1445 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001446 ensureSettingsStateLocked(globalKey);
1447 }
1448
1449 // Ensure secure settings loaded.
1450 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1451 ensureSettingsStateLocked(secureKey);
1452
1453 // Make sure the secure settings have an Android id set.
1454 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1455 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1456
1457 // Ensure system settings loaded.
1458 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1459 ensureSettingsStateLocked(systemKey);
1460
1461 // Upgrade the settings to the latest version.
1462 UpgradeController upgrader = new UpgradeController(userId);
1463 upgrader.upgradeIfNeededLocked();
1464 }
1465
1466 private void ensureSettingsStateLocked(int key) {
1467 if (mSettingsStates.get(key) == null) {
1468 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1469 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1470 maxBytesPerPackage);
1471 mSettingsStates.put(key, settingsState);
1472 }
1473 }
1474
1475 public void removeUserStateLocked(int userId, boolean permanently) {
1476 // We always keep the global settings in memory.
1477
1478 // Nuke system settings.
1479 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1480 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1481 if (systemSettingsState != null) {
1482 if (permanently) {
1483 mSettingsStates.remove(systemKey);
1484 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001485 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001486 systemSettingsState.destroyLocked(new Runnable() {
1487 @Override
1488 public void run() {
1489 mSettingsStates.remove(systemKey);
1490 }
1491 });
1492 }
1493 }
1494
1495 // Nuke secure settings.
1496 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1497 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1498 if (secureSettingsState != null) {
1499 if (permanently) {
1500 mSettingsStates.remove(secureKey);
1501 secureSettingsState.destroyLocked(null);
1502 } else {
1503 secureSettingsState.destroyLocked(new Runnable() {
1504 @Override
1505 public void run() {
1506 mSettingsStates.remove(secureKey);
1507 }
1508 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001509 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001510 }
1511 }
1512
Svetoslav683914b2015-01-15 14:22:26 -08001513 public boolean insertSettingLocked(int type, int userId, String name, String value,
1514 String packageName) {
1515 final int key = makeKey(type, userId);
1516
1517 SettingsState settingsState = peekSettingsStateLocked(key);
1518 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1519
1520 if (success) {
1521 notifyForSettingsChange(key, name);
1522 }
1523 return success;
1524 }
1525
1526 public boolean deleteSettingLocked(int type, int userId, String name) {
1527 final int key = makeKey(type, userId);
1528
1529 SettingsState settingsState = peekSettingsStateLocked(key);
1530 final boolean success = settingsState.deleteSettingLocked(name);
1531
1532 if (success) {
1533 notifyForSettingsChange(key, name);
1534 }
1535 return success;
1536 }
1537
1538 public Setting getSettingLocked(int type, int userId, String name) {
1539 final int key = makeKey(type, userId);
1540
1541 SettingsState settingsState = peekSettingsStateLocked(key);
1542 return settingsState.getSettingLocked(name);
1543 }
1544
1545 public boolean updateSettingLocked(int type, int userId, String name, String value,
1546 String packageName) {
1547 final int key = makeKey(type, userId);
1548
1549 SettingsState settingsState = peekSettingsStateLocked(key);
1550 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1551
1552 if (success) {
1553 notifyForSettingsChange(key, name);
1554 }
1555
1556 return success;
1557 }
1558
1559 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001560 // Global and secure settings are signature protected. Apps signed
1561 // by the platform certificate are generally not uninstalled and
1562 // the main exception is tests. We trust components signed
1563 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001564
1565 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1566 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001567 if (systemSettings != null) {
1568 systemSettings.onPackageRemovedLocked(packageName);
1569 }
Svetoslav683914b2015-01-15 14:22:26 -08001570 }
1571
1572 private SettingsState peekSettingsStateLocked(int key) {
1573 SettingsState settingsState = mSettingsStates.get(key);
1574 if (settingsState != null) {
1575 return settingsState;
1576 }
1577
1578 ensureSettingsForUserLocked(getUserIdFromKey(key));
1579 return mSettingsStates.get(key);
1580 }
1581
1582 private void migrateAllLegacySettingsIfNeeded() {
1583 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001584 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001585 File globalFile = getSettingsFile(key);
1586 if (globalFile.exists()) {
1587 return;
1588 }
1589
1590 final long identity = Binder.clearCallingIdentity();
1591 try {
1592 List<UserInfo> users = mUserManager.getUsers(true);
1593
1594 final int userCount = users.size();
1595 for (int i = 0; i < userCount; i++) {
1596 final int userId = users.get(i).id;
1597
1598 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1599 SQLiteDatabase database = dbHelper.getWritableDatabase();
1600 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1601
1602 // Upgrade to the latest version.
1603 UpgradeController upgrader = new UpgradeController(userId);
1604 upgrader.upgradeIfNeededLocked();
1605
1606 // Drop from memory if not a running user.
1607 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1608 removeUserStateLocked(userId, false);
1609 }
1610 }
1611 } finally {
1612 Binder.restoreCallingIdentity(identity);
1613 }
1614 }
1615 }
1616
1617 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1618 // Every user has secure settings and if no file we need to migrate.
1619 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1620 File secureFile = getSettingsFile(secureKey);
1621 if (secureFile.exists()) {
1622 return;
1623 }
1624
1625 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1626 SQLiteDatabase database = dbHelper.getWritableDatabase();
1627
1628 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1629 }
1630
1631 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1632 SQLiteDatabase database, int userId) {
1633 // Move over the global settings if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001634 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001635 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1636 ensureSettingsStateLocked(globalKey);
1637 SettingsState globalSettings = mSettingsStates.get(globalKey);
1638 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1639 globalSettings.persistSyncLocked();
1640 }
1641
1642 // Move over the secure settings.
1643 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1644 ensureSettingsStateLocked(secureKey);
1645 SettingsState secureSettings = mSettingsStates.get(secureKey);
1646 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1647 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1648 secureSettings.persistSyncLocked();
1649
1650 // Move over the system settings.
1651 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1652 ensureSettingsStateLocked(systemKey);
1653 SettingsState systemSettings = mSettingsStates.get(systemKey);
1654 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1655 systemSettings.persistSyncLocked();
1656
1657 // Drop the database as now all is moved and persisted.
1658 if (DROP_DATABASE_ON_MIGRATION) {
1659 dbHelper.dropDatabase();
1660 } else {
1661 dbHelper.backupDatabase();
1662 }
1663 }
1664
1665 private void migrateLegacySettingsLocked(SettingsState settingsState,
1666 SQLiteDatabase database, String table) {
1667 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1668 queryBuilder.setTables(table);
1669
1670 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1671 null, null, null, null, null);
1672
1673 if (cursor == null) {
1674 return;
1675 }
1676
1677 try {
1678 if (!cursor.moveToFirst()) {
1679 return;
1680 }
1681
1682 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1683 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1684
1685 settingsState.setVersionLocked(database.getVersion());
1686
1687 while (!cursor.isAfterLast()) {
1688 String name = cursor.getString(nameColumnIdx);
1689 String value = cursor.getString(valueColumnIdx);
1690 settingsState.insertSettingLocked(name, value,
1691 SettingsState.SYSTEM_PACKAGE_NAME);
1692 cursor.moveToNext();
1693 }
1694 } finally {
1695 cursor.close();
1696 }
1697 }
1698
1699 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1700 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1701
1702 if (value != null) {
1703 return;
1704 }
1705
1706 final int userId = getUserIdFromKey(secureSettings.mKey);
1707
1708 final UserInfo user;
1709 final long identity = Binder.clearCallingIdentity();
1710 try {
1711 user = mUserManager.getUserInfo(userId);
1712 } finally {
1713 Binder.restoreCallingIdentity(identity);
1714 }
1715 if (user == null) {
1716 // Can happen due to races when deleting users - treat as benign.
1717 return;
1718 }
1719
1720 String androidId = Long.toHexString(new SecureRandom().nextLong());
1721 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1722 SettingsState.SYSTEM_PACKAGE_NAME);
1723
1724 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1725 + "] for user " + userId);
1726
1727 // Write a drop box entry if it's a restricted profile
1728 if (user.isRestricted()) {
1729 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1730 Context.DROPBOX_SERVICE);
1731 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1732 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1733 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1734 }
1735 }
1736 }
1737
1738 private void notifyForSettingsChange(int key, String name) {
1739 // Update the system property *first*, so if someone is listening for
1740 // a notification and then using the contract class to get their data,
1741 // the system property will be updated and they'll get the new data.
1742
1743 boolean backedUpDataChanged = false;
1744 String property = null;
1745 if (isGlobalSettingsKey(key)) {
1746 property = Settings.Global.SYS_PROP_SETTING_VERSION;
1747 backedUpDataChanged = true;
1748 } else if (isSecureSettingsKey(key)) {
1749 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
1750 backedUpDataChanged = true;
1751 } else if (isSystemSettingsKey(key)) {
1752 property = Settings.System.SYS_PROP_SETTING_VERSION;
1753 backedUpDataChanged = true;
1754 }
1755
1756 if (property != null) {
1757 final long version = SystemProperties.getLong(property, 0) + 1;
1758 SystemProperties.set(property, Long.toString(version));
1759 if (DEBUG) {
1760 Slog.v(LOG_TAG, "System property " + property + "=" + version);
1761 }
1762 }
1763
1764 // Inform the backup manager about a data change
1765 if (backedUpDataChanged) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001766 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Svetoslav683914b2015-01-15 14:22:26 -08001767 }
1768
1769 // Now send the notification through the content framework.
1770
1771 final int userId = getUserIdFromKey(key);
1772 Uri uri = getNotificationUriFor(key, name);
1773
Svetoslav7e0683b2015-08-03 16:02:52 -07001774 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1775 userId, 0, uri).sendToTarget();
1776
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001777 if (isSecureSettingsKey(key)) {
1778 maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
1779 } else if (isSystemSettingsKey(key)) {
1780 maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
1781 }
1782 }
1783
1784 private void maybeNotifyProfiles(int userId, Uri uri, String name,
1785 Set<String> keysCloned) {
1786 if (keysCloned.contains(name)) {
1787 List<UserInfo> profiles = mUserManager.getProfiles(userId);
1788 int size = profiles.size();
1789 for (int i = 0; i < size; i++) {
1790 UserInfo profile = profiles.get(i);
1791 // the notification for userId has already been sent.
1792 if (profile.id != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001793 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1794 profile.id, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001795 }
1796 }
1797 }
Svetoslav683914b2015-01-15 14:22:26 -08001798 }
1799
1800 private int makeKey(int type, int userId) {
1801 return (type << SETTINGS_TYPE_SHIFT) | userId;
1802 }
1803
1804 private int getTypeFromKey(int key) {
1805 return key >> SETTINGS_TYPE_SHIFT;
1806 }
1807
1808 private int getUserIdFromKey(int key) {
1809 return key & ~SETTINGS_TYPE_MASK;
1810 }
1811
1812 private boolean isGlobalSettingsKey(int key) {
1813 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1814 }
1815
1816 private boolean isSystemSettingsKey(int key) {
1817 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1818 }
1819
1820 private boolean isSecureSettingsKey(int key) {
1821 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1822 }
1823
1824 private File getSettingsFile(int key) {
1825 if (isGlobalSettingsKey(key)) {
1826 final int userId = getUserIdFromKey(key);
1827 return new File(Environment.getUserSystemDirectory(userId),
1828 SETTINGS_FILE_GLOBAL);
1829 } else if (isSystemSettingsKey(key)) {
1830 final int userId = getUserIdFromKey(key);
1831 return new File(Environment.getUserSystemDirectory(userId),
1832 SETTINGS_FILE_SYSTEM);
1833 } else if (isSecureSettingsKey(key)) {
1834 final int userId = getUserIdFromKey(key);
1835 return new File(Environment.getUserSystemDirectory(userId),
1836 SETTINGS_FILE_SECURE);
1837 } else {
1838 throw new IllegalArgumentException("Invalid settings key:" + key);
1839 }
1840 }
1841
1842 private Uri getNotificationUriFor(int key, String name) {
1843 if (isGlobalSettingsKey(key)) {
1844 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
1845 : Settings.Global.CONTENT_URI;
1846 } else if (isSecureSettingsKey(key)) {
1847 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
1848 : Settings.Secure.CONTENT_URI;
1849 } else if (isSystemSettingsKey(key)) {
1850 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
1851 : Settings.System.CONTENT_URI;
1852 } else {
1853 throw new IllegalArgumentException("Invalid settings key:" + key);
1854 }
1855 }
1856
1857 private int getMaxBytesPerPackageForType(int type) {
1858 switch (type) {
1859 case SETTINGS_TYPE_GLOBAL:
1860 case SETTINGS_TYPE_SECURE: {
1861 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
1862 }
1863
1864 default: {
1865 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
1866 }
1867 }
1868 }
1869
Svetoslav7e0683b2015-08-03 16:02:52 -07001870 private final class MyHandler extends Handler {
1871 private static final int MSG_NOTIFY_URI_CHANGED = 1;
1872 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
1873
1874 public MyHandler(Looper looper) {
1875 super(looper);
1876 }
1877
1878 @Override
1879 public void handleMessage(Message msg) {
1880 switch (msg.what) {
1881 case MSG_NOTIFY_URI_CHANGED: {
1882 final int userId = msg.arg1;
1883 Uri uri = (Uri) msg.obj;
1884 getContext().getContentResolver().notifyChange(uri, null, true, userId);
1885 if (DEBUG) {
1886 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
1887 }
1888 } break;
1889
1890 case MSG_NOTIFY_DATA_CHANGED: {
1891 mBackupManager.dataChanged();
1892 } break;
1893 }
1894 }
1895 }
1896
Svetoslav683914b2015-01-15 14:22:26 -08001897 private final class UpgradeController {
Bryce Leebd179282015-12-17 19:01:37 -08001898 private static final int SETTINGS_VERSION = 124;
Svetoslav683914b2015-01-15 14:22:26 -08001899
1900 private final int mUserId;
1901
1902 public UpgradeController(int userId) {
1903 mUserId = userId;
1904 }
1905
1906 public void upgradeIfNeededLocked() {
1907 // The version of all settings for a user is the same (all users have secure).
1908 SettingsState secureSettings = getSettingsLocked(
1909 SettingsRegistry.SETTINGS_TYPE_SECURE, mUserId);
1910
1911 // Try an update from the current state.
1912 final int oldVersion = secureSettings.getVersionLocked();
1913 final int newVersion = SETTINGS_VERSION;
1914
Svet Ganovc9755bc2015-03-28 13:21:22 -07001915 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08001916 if (oldVersion == newVersion) {
1917 return;
1918 }
1919
1920 // Try to upgrade.
1921 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
1922
1923 // If upgrade failed start from scratch and upgrade.
1924 if (curVersion != newVersion) {
1925 // Drop state we have for this user.
1926 removeUserStateLocked(mUserId, true);
1927
1928 // Recreate the database.
1929 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
1930 SQLiteDatabase database = dbHelper.getWritableDatabase();
1931 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
1932
1933 // Migrate the settings for this user.
1934 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
1935
1936 // Now upgrade should work fine.
1937 onUpgradeLocked(mUserId, oldVersion, newVersion);
1938 }
1939
1940 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001941 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001942 SettingsState globalSettings = getSettingsLocked(
1943 SettingsRegistry.SETTINGS_TYPE_GLOBAL, mUserId);
1944 globalSettings.setVersionLocked(newVersion);
1945 }
1946
1947 // Set the secure settings version.
1948 secureSettings.setVersionLocked(newVersion);
1949
1950 // Set the system settings version.
1951 SettingsState systemSettings = getSettingsLocked(
1952 SettingsRegistry.SETTINGS_TYPE_SYSTEM, mUserId);
1953 systemSettings.setVersionLocked(newVersion);
1954 }
1955
1956 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001957 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001958 }
1959
1960 private SettingsState getSecureSettingsLocked(int userId) {
1961 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1962 }
1963
1964 private SettingsState getSystemSettingsLocked(int userId) {
1965 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
1966 }
1967
Jeff Brown503cffc2015-03-26 18:08:51 -07001968 /**
1969 * You must perform all necessary mutations to bring the settings
1970 * for this user from the old to the new version. When you add a new
1971 * upgrade step you *must* update SETTINGS_VERSION.
1972 *
1973 * This is an example of moving a setting from secure to global.
1974 *
1975 * // v119: Example settings changes.
1976 * if (currentVersion == 118) {
1977 * if (userId == UserHandle.USER_OWNER) {
1978 * // Remove from the secure settings.
1979 * SettingsState secureSettings = getSecureSettingsLocked(userId);
1980 * String name = "example_setting_to_move";
1981 * String value = secureSettings.getSetting(name);
1982 * secureSettings.deleteSetting(name);
1983 *
1984 * // Add to the global settings.
1985 * SettingsState globalSettings = getGlobalSettingsLocked();
1986 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
1987 * }
1988 *
1989 * // Update the current version.
1990 * currentVersion = 119;
1991 * }
1992 */
Svetoslav683914b2015-01-15 14:22:26 -08001993 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
1994 if (DEBUG) {
1995 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
1996 + oldVersion + " to version: " + newVersion);
1997 }
1998
Jeff Brown503cffc2015-03-26 18:08:51 -07001999 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002000
John Spurlocke11ae112015-05-11 16:09:03 -04002001 // v119: Reset zen + ringer mode.
2002 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002003 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002004 final SettingsState globalSettings = getGlobalSettingsLocked();
2005 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2006 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2007 SettingsState.SYSTEM_PACKAGE_NAME);
2008 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2009 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2010 SettingsState.SYSTEM_PACKAGE_NAME);
2011 }
2012 currentVersion = 119;
2013 }
2014
Jason Monk27bbb2d2015-03-31 16:46:39 -04002015 // v120: Add double tap to wake setting.
2016 if (currentVersion == 119) {
2017 SettingsState secureSettings = getSecureSettingsLocked(userId);
2018 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2019 getContext().getResources().getBoolean(
2020 R.bool.def_double_tap_to_wake) ? "1" : "0",
2021 SettingsState.SYSTEM_PACKAGE_NAME);
2022
2023 currentVersion = 120;
2024 }
2025
Svetoslav7e0683b2015-08-03 16:02:52 -07002026 if (currentVersion == 120) {
2027 // Before 121, we used a different string encoding logic. We just bump the
2028 // version here; SettingsState knows how to handle pre-version 120 files.
2029 currentVersion = 121;
2030 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002031
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002032 if (currentVersion == 121) {
2033 // Version 122: allow OEMs to set a default payment component in resources.
2034 // Note that we only write the default if no default has been set;
2035 // if there is, we just leave the default at whatever it currently is.
2036 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2037 String defaultComponent = (getContext().getResources().getString(
2038 R.string.def_nfc_payment_component));
2039 Setting currentSetting = secureSettings.getSettingLocked(
2040 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2041 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2042 currentSetting == null) {
2043 secureSettings.insertSettingLocked(
2044 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2045 defaultComponent,
2046 SettingsState.SYSTEM_PACKAGE_NAME);
2047 }
2048 currentVersion = 122;
2049 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002050
2051 if (currentVersion == 122) {
2052 // Version 123: Adding a default value for the ability to add a user from
2053 // the lock screen.
2054 if (userId == UserHandle.USER_SYSTEM) {
2055 final SettingsState globalSettings = getGlobalSettingsLocked();
2056 Setting currentSetting = globalSettings.getSettingLocked(
2057 Settings.Global.ADD_USERS_WHEN_LOCKED);
2058 if (currentSetting == null) {
2059 globalSettings.insertSettingLocked(
2060 Settings.Global.ADD_USERS_WHEN_LOCKED,
2061 getContext().getResources().getBoolean(
2062 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2063 SettingsState.SYSTEM_PACKAGE_NAME);
2064 }
2065 }
2066 currentVersion = 123;
2067 }
Bryce Leebd179282015-12-17 19:01:37 -08002068
2069 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002070 final SettingsState globalSettings = getGlobalSettingsLocked();
2071 String defaultDisabledProfiles = (getContext().getResources().getString(
2072 R.string.def_bluetooth_disabled_profiles));
2073 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2074 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002075 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002076 }
2077
Jeff Brown503cffc2015-03-26 18:08:51 -07002078 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002079
Jeff Brown503cffc2015-03-26 18:08:51 -07002080 // Return the current version.
2081 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002082 }
2083 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002084 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002085}