blob: 92a3de7c597713de8d41318469f48633bcf56998 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
Svetoslav683914b2015-01-15 14:22:26 -080019import android.Manifest;
Christopher Tated5fe1472012-09-10 15:48:38 -070020import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070021import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080022import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070023import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080024import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070026import android.content.ContentValues;
27import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.Intent;
29import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080030import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070031import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070034import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040040import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070045import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070047import android.os.Handler;
48import android.os.Looper;
49import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070051import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070052import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070053import android.os.SELinux;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.os.UserHandle;
56import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057import android.provider.Settings;
58import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080059import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070060import android.util.Slog;
61import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040062
Svetoslav683914b2015-01-15 14:22:26 -080063import com.android.internal.annotations.GuardedBy;
64import com.android.internal.content.PackageMonitor;
65import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080066import com.android.providers.settings.SettingsState.Setting;
Ruben Brunk98576cf2016-03-07 18:54:28 -080067import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040068
Svetoslav683914b2015-01-15 14:22:26 -080069import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080070import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080071import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080072import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080073import java.security.SecureRandom;
74import java.util.Arrays;
75import java.util.List;
Svetoslav683914b2015-01-15 14:22:26 -080076import java.util.Set;
77import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070078
Svetoslav683914b2015-01-15 14:22:26 -080079/**
80 * <p>
81 * This class is a content provider that publishes the system settings.
82 * It can be accessed via the content provider APIs or via custom call
83 * commands. The latter is a bit faster and is the preferred way to access
84 * the platform settings.
85 * </p>
86 * <p>
87 * There are three settings types, global (with signature level protection
88 * and shared across users), secure (with signature permission level
89 * protection and per user), and system (with dangerous permission level
90 * protection and per user). Global settings are stored under the device owner.
91 * Each of these settings is represented by a {@link
92 * com.android.providers.settings.SettingsState} object mapped to an integer
93 * key derived from the setting type in the most significant bits and user
94 * id in the least significant bits. Settings are synchronously loaded on
95 * instantiation of a SettingsState and asynchronously persisted on mutation.
96 * Settings are stored in the user specific system directory.
97 * </p>
98 * <p>
99 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
100 * and get a warning. Targeting higher API version prohibits this as the
101 * system settings are not a place for apps to save their state. When a package
102 * is removed the settings it added are deleted. Apps cannot delete system
103 * settings added by the platform. System settings values are validated to
104 * ensure the clients do not put bad values. Global and secure settings are
105 * changed only by trusted parties, therefore no validation is performed. Also
106 * there is a limit on the amount of app specific settings that can be added
107 * to prevent unlimited growth of the system process memory footprint.
108 * </p>
109 */
110@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700111public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800112 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113
Svetoslav683914b2015-01-15 14:22:26 -0800114 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
115
116 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700117
Christopher Tate06efb532012-08-24 15:29:27 -0700118 private static final String TABLE_SYSTEM = "system";
119 private static final String TABLE_SECURE = "secure";
120 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800121
122 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String TABLE_FAVORITES = "favorites";
124 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800125 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
126 private static final String TABLE_BOOKMARKS = "bookmarks";
127 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Svetoslav683914b2015-01-15 14:22:26 -0800129 // The set of removed legacy tables.
130 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700131 static {
Svetoslav683914b2015-01-15 14:22:26 -0800132 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
133 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
134 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
135 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
136 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
137 }
Christopher Tate06efb532012-08-24 15:29:27 -0700138
Svetoslav683914b2015-01-15 14:22:26 -0800139 private static final int MUTATION_OPERATION_INSERT = 1;
140 private static final int MUTATION_OPERATION_DELETE = 2;
141 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400142
Svetoslav683914b2015-01-15 14:22:26 -0800143 private static final String[] ALL_COLUMNS = new String[] {
144 Settings.NameValueTable._ID,
145 Settings.NameValueTable.NAME,
146 Settings.NameValueTable.VALUE
147 };
148
149 private static final Bundle NULL_SETTING = Bundle.forPair(Settings.NameValueTable.VALUE, null);
150
Christopher Tate06efb532012-08-24 15:29:27 -0700151
Svetoslav683914b2015-01-15 14:22:26 -0800152 // Per user secure settings that moved to the for all users global settings.
153 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
154 static {
155 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700156 }
157
Svetoslav683914b2015-01-15 14:22:26 -0800158 // Per user system settings that moved to the for all users global settings.
159 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
160 static {
161 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162 }
163
Svetoslav683914b2015-01-15 14:22:26 -0800164 // Per user system settings that moved to the per user secure settings.
165 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
166 static {
167 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168 }
169
Svetoslav683914b2015-01-15 14:22:26 -0800170 // Per all users global settings that moved to the per user secure settings.
171 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
172 static {
173 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700174 }
175
Svetoslav683914b2015-01-15 14:22:26 -0800176 // Per user secure settings that are cloned for the managed profiles of the user.
177 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
178 static {
179 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700180 }
181
Svetoslav683914b2015-01-15 14:22:26 -0800182 // Per user system settings that are cloned for the managed profiles of the user.
183 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
184 static {
185 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400186 }
187
Svetoslav683914b2015-01-15 14:22:26 -0800188 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700189
Svetoslav683914b2015-01-15 14:22:26 -0800190 @GuardedBy("mLock")
191 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700192
Svetoslav7ec28e82015-05-20 17:01:10 -0700193 // We have to call in the user manager with no lock held,
194 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800195
Svetoslav7ec28e82015-05-20 17:01:10 -0700196 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700197 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700198
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700199 @Override
200 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800201 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700202 mUserManager = UserManager.get(getContext());
203 mPackageManager = AppGlobals.getPackageManager();
Svetoslav683914b2015-01-15 14:22:26 -0800204 mSettingsRegistry = new SettingsRegistry();
205 }
206 registerBroadcastReceivers();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700207 return true;
208 }
209
Svetoslav683914b2015-01-15 14:22:26 -0800210 @Override
211 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700212 final int requestingUserId = getRequestingUserId(args);
213 switch (method) {
214 case Settings.CALL_METHOD_GET_GLOBAL: {
215 Setting setting = getGlobalSetting(name);
216 return packageValueForCallResult(setting);
Svetoslav683914b2015-01-15 14:22:26 -0800217 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700218
219 case Settings.CALL_METHOD_GET_SECURE: {
220 Setting setting = getSecureSetting(name, requestingUserId);
221 return packageValueForCallResult(setting);
222 }
223
224 case Settings.CALL_METHOD_GET_SYSTEM: {
225 Setting setting = getSystemSetting(name, requestingUserId);
226 return packageValueForCallResult(setting);
227 }
228
229 case Settings.CALL_METHOD_PUT_GLOBAL: {
230 String value = getSettingValue(args);
231 insertGlobalSetting(name, value, requestingUserId);
232 break;
233 }
234
235 case Settings.CALL_METHOD_PUT_SECURE: {
236 String value = getSettingValue(args);
237 insertSecureSetting(name, value, requestingUserId);
238 break;
239 }
240
241 case Settings.CALL_METHOD_PUT_SYSTEM: {
242 String value = getSettingValue(args);
243 insertSystemSetting(name, value, requestingUserId);
244 break;
245 }
246
247 default: {
248 Slog.w(LOG_TAG, "call() with invalid method: " + method);
249 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700250 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700251
Christopher Tate06efb532012-08-24 15:29:27 -0700252 return null;
253 }
254
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800255 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800256 public String getType(Uri uri) {
257 Arguments args = new Arguments(uri, null, null, true);
258 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700259 return "vnd.android.cursor.dir/" + args.table;
260 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700261 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262 }
263 }
264
265 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800266 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
267 String order) {
268 if (DEBUG) {
269 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700270 }
271
Svetoslav683914b2015-01-15 14:22:26 -0800272 Arguments args = new Arguments(uri, where, whereArgs, true);
273 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700274
Svetoslav683914b2015-01-15 14:22:26 -0800275 // If a legacy table that is gone, done.
276 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
277 return new MatrixCursor(normalizedProjection, 0);
278 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700279
Svetoslav7ec28e82015-05-20 17:01:10 -0700280 switch (args.table) {
281 case TABLE_GLOBAL: {
282 if (args.name != null) {
283 Setting setting = getGlobalSetting(args.name);
284 return packageSettingForQuery(setting, normalizedProjection);
285 } else {
286 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700287 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700288 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700289
Svetoslav7ec28e82015-05-20 17:01:10 -0700290 case TABLE_SECURE: {
291 final int userId = UserHandle.getCallingUserId();
292 if (args.name != null) {
293 Setting setting = getSecureSetting(args.name, userId);
294 return packageSettingForQuery(setting, normalizedProjection);
295 } else {
296 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800297 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700298 }
Svetoslav683914b2015-01-15 14:22:26 -0800299
Svetoslav7ec28e82015-05-20 17:01:10 -0700300 case TABLE_SYSTEM: {
301 final int userId = UserHandle.getCallingUserId();
302 if (args.name != null) {
303 Setting setting = getSystemSetting(args.name, userId);
304 return packageSettingForQuery(setting, normalizedProjection);
305 } else {
306 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800307 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700308 }
Svetoslav683914b2015-01-15 14:22:26 -0800309
Svetoslav7ec28e82015-05-20 17:01:10 -0700310 default: {
311 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700312 }
313 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700314 }
315
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700316 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800317 public Uri insert(Uri uri, ContentValues values) {
318 if (DEBUG) {
319 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700320 }
321
Svetoslav683914b2015-01-15 14:22:26 -0800322 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700323
Svetoslav683914b2015-01-15 14:22:26 -0800324 // If a legacy table that is gone, done.
325 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 return null;
327 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700328
Svetoslav683914b2015-01-15 14:22:26 -0800329 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700330 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800331 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700332 }
333
Svetoslav683914b2015-01-15 14:22:26 -0800334 String value = values.getAsString(Settings.Secure.VALUE);
335
Svetoslav7ec28e82015-05-20 17:01:10 -0700336 switch (table) {
337 case TABLE_GLOBAL: {
338 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId())) {
339 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700340 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 } break;
342
343 case TABLE_SECURE: {
344 if (insertSecureSetting(name, value, UserHandle.getCallingUserId())) {
345 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
346 }
347 } break;
348
349 case TABLE_SYSTEM: {
350 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
351 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
352 }
353 } break;
354
355 default: {
356 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700357 }
358 }
359
Svetoslav683914b2015-01-15 14:22:26 -0800360 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700361 }
362
363 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800364 public int bulkInsert(Uri uri, ContentValues[] allValues) {
365 if (DEBUG) {
366 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368
Svetoslav683914b2015-01-15 14:22:26 -0800369 int insertionCount = 0;
370 final int valuesCount = allValues.length;
371 for (int i = 0; i < valuesCount; i++) {
372 ContentValues values = allValues[i];
373 if (insert(uri, values) != null) {
374 insertionCount++;
375 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700376 }
Svetoslav683914b2015-01-15 14:22:26 -0800377
378 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379 }
380
381 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800382 public int delete(Uri uri, String where, String[] whereArgs) {
383 if (DEBUG) {
384 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700386
Svetoslav683914b2015-01-15 14:22:26 -0800387 Arguments args = new Arguments(uri, where, whereArgs, false);
388
389 // If a legacy table that is gone, done.
390 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
391 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700392 }
Svetoslav683914b2015-01-15 14:22:26 -0800393
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700394 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800395 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700396 }
Svetoslav683914b2015-01-15 14:22:26 -0800397
Svetoslav7ec28e82015-05-20 17:01:10 -0700398 switch (args.table) {
399 case TABLE_GLOBAL: {
400 final int userId = UserHandle.getCallingUserId();
401 return deleteGlobalSetting(args.name, userId) ? 1 : 0;
402 }
Svetoslav683914b2015-01-15 14:22:26 -0800403
Svetoslav7ec28e82015-05-20 17:01:10 -0700404 case TABLE_SECURE: {
405 final int userId = UserHandle.getCallingUserId();
406 return deleteSecureSetting(args.name, userId) ? 1 : 0;
407 }
Svetoslav683914b2015-01-15 14:22:26 -0800408
Svetoslav7ec28e82015-05-20 17:01:10 -0700409 case TABLE_SYSTEM: {
410 final int userId = UserHandle.getCallingUserId();
411 return deleteSystemSetting(args.name, userId) ? 1 : 0;
412 }
413
414 default: {
415 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800416 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700417 }
Svetoslav683914b2015-01-15 14:22:26 -0800418 }
419
420 @Override
421 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
422 if (DEBUG) {
423 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700424 }
Svetoslav683914b2015-01-15 14:22:26 -0800425
426 Arguments args = new Arguments(uri, where, whereArgs, false);
427
428 // If a legacy table that is gone, done.
429 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
430 return 0;
431 }
432
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700433 String name = values.getAsString(Settings.Secure.NAME);
434 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800435 return 0;
436 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700437 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800438
Svetoslav7ec28e82015-05-20 17:01:10 -0700439 switch (args.table) {
440 case TABLE_GLOBAL: {
441 final int userId = UserHandle.getCallingUserId();
442 return updateGlobalSetting(args.name, value, userId) ? 1 : 0;
443 }
Svetoslav683914b2015-01-15 14:22:26 -0800444
Svetoslav7ec28e82015-05-20 17:01:10 -0700445 case TABLE_SECURE: {
446 final int userId = UserHandle.getCallingUserId();
447 return updateSecureSetting(args.name, value, userId) ? 1 : 0;
448 }
Svetoslav683914b2015-01-15 14:22:26 -0800449
Svetoslav7ec28e82015-05-20 17:01:10 -0700450 case TABLE_SYSTEM: {
451 final int userId = UserHandle.getCallingUserId();
452 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
453 }
Svetoslav683914b2015-01-15 14:22:26 -0800454
Svetoslav7ec28e82015-05-20 17:01:10 -0700455 default: {
456 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800457 }
458 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700459 }
460
461 @Override
462 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey413573a2016-02-22 17:52:45 -0700463 final String cacheName;
464 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
465 cacheName = Settings.System.RINGTONE_CACHE;
466 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
467 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
468 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
469 cacheName = Settings.System.ALARM_ALERT_CACHE;
470 } else {
471 throw new FileNotFoundException("Direct file access no longer supported; "
472 + "ringtone playback is available through android.media.Ringtone");
473 }
474
475 final File cacheFile = new File(
476 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
477 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
478 }
479
480 private File getRingtoneCacheDir(int userId) {
481 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
482 cacheDir.mkdir();
483 SELinux.restorecon(cacheDir);
484 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700485 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800486
Svetoslavb505ccc2015-02-17 12:41:04 -0800487 @Override
488 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
489 synchronized (mLock) {
490 final long identity = Binder.clearCallingIdentity();
491 try {
492 List<UserInfo> users = mUserManager.getUsers(true);
493 final int userCount = users.size();
494 for (int i = 0; i < userCount; i++) {
495 UserInfo user = users.get(i);
496 dumpForUser(user.id, pw);
497 }
498 } finally {
499 Binder.restoreCallingIdentity(identity);
500 }
501 }
502 }
503
504 private void dumpForUser(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700505 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800506 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700507 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800508 dumpSettings(globalCursor, pw);
509 pw.println();
510 }
511
512 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700513 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800514 dumpSettings(secureCursor, pw);
515 pw.println();
516
517 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700518 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800519 dumpSettings(systemCursor, pw);
520 pw.println();
521 }
522
523 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700524 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800525 return;
526 }
527
528 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
529 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
530 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
531
532 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700533 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
534 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
535 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800536 pw.println();
537 } while (cursor.moveToNext());
538 }
539
Svetoslav7e0683b2015-08-03 16:02:52 -0700540 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700541 if (s != null) {
542 return s;
543 }
544 return "{null}";
545 }
546
Svetoslav683914b2015-01-15 14:22:26 -0800547 private void registerBroadcastReceivers() {
548 IntentFilter userFilter = new IntentFilter();
549 userFilter.addAction(Intent.ACTION_USER_REMOVED);
550 userFilter.addAction(Intent.ACTION_USER_STOPPED);
551
552 getContext().registerReceiver(new BroadcastReceiver() {
553 @Override
554 public void onReceive(Context context, Intent intent) {
555 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700556 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800557
558 switch (intent.getAction()) {
559 case Intent.ACTION_USER_REMOVED: {
560 mSettingsRegistry.removeUserStateLocked(userId, true);
561 } break;
562
563 case Intent.ACTION_USER_STOPPED: {
564 mSettingsRegistry.removeUserStateLocked(userId, false);
565 } break;
566 }
567 }
568 }, userFilter);
569
570 PackageMonitor monitor = new PackageMonitor() {
571 @Override
572 public void onPackageRemoved(String packageName, int uid) {
573 synchronized (mLock) {
574 mSettingsRegistry.onPackageRemovedLocked(packageName,
575 UserHandle.getUserId(uid));
576 }
577 }
578 };
579
580 // package changes
581 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
582 UserHandle.ALL, true);
583 }
584
Svetoslav7ec28e82015-05-20 17:01:10 -0700585 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800586 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700587 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800588 }
589
Svetoslav7ec28e82015-05-20 17:01:10 -0700590 synchronized (mLock) {
591 // Get the settings.
592 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Xiaohui Chen43765b72015-08-31 10:57:33 -0700593 SettingsRegistry.SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800594
Svetoslav7ec28e82015-05-20 17:01:10 -0700595 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800596
Svetoslav7ec28e82015-05-20 17:01:10 -0700597 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800598
Svetoslav7ec28e82015-05-20 17:01:10 -0700599 String[] normalizedProjection = normalizeProjection(projection);
600 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800601
Svetoslav7ec28e82015-05-20 17:01:10 -0700602 // Anyone can get the global settings, so no security checks.
603 for (int i = 0; i < nameCount; i++) {
604 String name = names.get(i);
605 Setting setting = settingsState.getSettingLocked(name);
606 appendSettingToCursor(result, setting);
607 }
608
609 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800610 }
Svetoslav683914b2015-01-15 14:22:26 -0800611 }
612
Svetoslav7ec28e82015-05-20 17:01:10 -0700613 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800614 if (DEBUG) {
615 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
616 }
617
618 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700619 synchronized (mLock) {
620 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700621 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800622 }
Svetoslav683914b2015-01-15 14:22:26 -0800623 }
624
Svetoslav7ec28e82015-05-20 17:01:10 -0700625 private boolean updateGlobalSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800626 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700627 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800628 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700629 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800630 }
631
Svetoslav7ec28e82015-05-20 17:01:10 -0700632 private boolean insertGlobalSetting(String name, String value, int requestingUserId) {
633 if (DEBUG) {
634 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
635 }
636 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
637 }
638
639 private boolean deleteGlobalSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800640 if (DEBUG) {
641 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
642 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700643 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800644 }
645
Svetoslav7ec28e82015-05-20 17:01:10 -0700646 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800647 int operation) {
648 // Make sure the caller can change the settings - treated as secure.
649 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
650
Svetoslav683914b2015-01-15 14:22:26 -0800651 // Resolve the userId on whose behalf the call is made.
652 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
653
Makoto Onuki28da2e32015-11-20 11:30:44 -0800654 // If this is a setting that is currently restricted for this user, do not allow
655 // unrestricting changes.
656 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800657 return false;
658 }
659
660 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700661 synchronized (mLock) {
662 switch (operation) {
663 case MUTATION_OPERATION_INSERT: {
664 return mSettingsRegistry
665 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700666 UserHandle.USER_SYSTEM, name, value, getCallingPackage());
Svetoslav7ec28e82015-05-20 17:01:10 -0700667 }
Svetoslav683914b2015-01-15 14:22:26 -0800668
Svetoslav7ec28e82015-05-20 17:01:10 -0700669 case MUTATION_OPERATION_DELETE: {
670 return mSettingsRegistry.deleteSettingLocked(
671 SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700672 UserHandle.USER_SYSTEM, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700673 }
Svetoslav683914b2015-01-15 14:22:26 -0800674
Svetoslav7ec28e82015-05-20 17:01:10 -0700675 case MUTATION_OPERATION_UPDATE: {
676 return mSettingsRegistry
677 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700678 UserHandle.USER_SYSTEM, name, value, getCallingPackage());
Svetoslav7ec28e82015-05-20 17:01:10 -0700679 }
Svetoslav683914b2015-01-15 14:22:26 -0800680 }
681 }
682
683 return false;
684 }
685
Svetoslav7ec28e82015-05-20 17:01:10 -0700686 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800687 if (DEBUG) {
688 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
689 }
690
691 // Resolve the userId on whose behalf the call is made.
692 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
693
Svetoslav7ec28e82015-05-20 17:01:10 -0700694 synchronized (mLock) {
695 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
696 SettingsRegistry.SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800697
Svetoslav7ec28e82015-05-20 17:01:10 -0700698 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800699
Svetoslav7ec28e82015-05-20 17:01:10 -0700700 String[] normalizedProjection = normalizeProjection(projection);
701 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800702
Svetoslav7ec28e82015-05-20 17:01:10 -0700703 for (int i = 0; i < nameCount; i++) {
704 String name = names.get(i);
705 // Determine the owning user as some profile settings are cloned from the parent.
706 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
707 name);
Svetoslav683914b2015-01-15 14:22:26 -0800708
Svetoslav7ec28e82015-05-20 17:01:10 -0700709 // Special case for location (sigh).
710 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
711 return null;
712 }
Svetoslav683914b2015-01-15 14:22:26 -0800713
Svetoslav7ec28e82015-05-20 17:01:10 -0700714 Setting setting = mSettingsRegistry.getSettingLocked(
715 SettingsRegistry.SETTINGS_TYPE_SECURE, owningUserId, name);
716 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800717 }
718
Svetoslav7ec28e82015-05-20 17:01:10 -0700719 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800720 }
Svetoslav683914b2015-01-15 14:22:26 -0800721 }
722
Svetoslav7ec28e82015-05-20 17:01:10 -0700723 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800724 if (DEBUG) {
725 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
726 }
727
728 // Resolve the userId on whose behalf the call is made.
729 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
730
731 // Determine the owning user as some profile settings are cloned from the parent.
732 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
733
734 // Special case for location (sigh).
735 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
736 return null;
737 }
738
739 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 synchronized (mLock) {
741 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
742 owningUserId, name);
743 }
Svetoslav683914b2015-01-15 14:22:26 -0800744 }
745
Svetoslav7ec28e82015-05-20 17:01:10 -0700746 private boolean insertSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800747 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700748 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800749 + requestingUserId + ")");
750 }
751
Svetoslav7ec28e82015-05-20 17:01:10 -0700752 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800753 }
754
Svetoslav7ec28e82015-05-20 17:01:10 -0700755 private boolean deleteSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800756 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700757 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800758 }
759
Svetoslav7ec28e82015-05-20 17:01:10 -0700760 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800761 }
762
Svetoslav7ec28e82015-05-20 17:01:10 -0700763 private boolean updateSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800764 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700765 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800766 + requestingUserId + ")");
767 }
768
Svetoslav7ec28e82015-05-20 17:01:10 -0700769 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800770 }
771
Svetoslav7ec28e82015-05-20 17:01:10 -0700772 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800773 int operation) {
774 // Make sure the caller can change the settings.
775 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
776
Svetoslav683914b2015-01-15 14:22:26 -0800777 // Resolve the userId on whose behalf the call is made.
778 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
779
Makoto Onuki28da2e32015-11-20 11:30:44 -0800780 // If this is a setting that is currently restricted for this user, do not allow
781 // unrestricting changes.
782 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800783 return false;
784 }
785
786 // Determine the owning user as some profile settings are cloned from the parent.
787 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
788
789 // Only the owning user can change the setting.
790 if (owningUserId != callingUserId) {
791 return false;
792 }
793
794 // Special cases for location providers (sigh).
795 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslavb596a2c2015-02-17 21:37:09 -0800796 return updateLocationProvidersAllowedLocked(value, owningUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800797 }
798
799 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700800 synchronized (mLock) {
801 switch (operation) {
802 case MUTATION_OPERATION_INSERT: {
803 return mSettingsRegistry
804 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
805 owningUserId, name, value, getCallingPackage());
806 }
Svetoslav683914b2015-01-15 14:22:26 -0800807
Svetoslav7ec28e82015-05-20 17:01:10 -0700808 case MUTATION_OPERATION_DELETE: {
809 return mSettingsRegistry.deleteSettingLocked(
810 SettingsRegistry.SETTINGS_TYPE_SECURE,
811 owningUserId, name);
812 }
Svetoslav683914b2015-01-15 14:22:26 -0800813
Svetoslav7ec28e82015-05-20 17:01:10 -0700814 case MUTATION_OPERATION_UPDATE: {
815 return mSettingsRegistry
816 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
817 owningUserId, name, value, getCallingPackage());
818 }
Svetoslav683914b2015-01-15 14:22:26 -0800819 }
820 }
821
822 return false;
823 }
824
Svetoslav7ec28e82015-05-20 17:01:10 -0700825 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800826 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700827 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800828 }
829
830 // Resolve the userId on whose behalf the call is made.
831 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
832
Svetoslav7ec28e82015-05-20 17:01:10 -0700833 synchronized (mLock) {
834 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
835 SettingsRegistry.SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800836
Svetoslav7ec28e82015-05-20 17:01:10 -0700837 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800838
Svetoslav7ec28e82015-05-20 17:01:10 -0700839 String[] normalizedProjection = normalizeProjection(projection);
840 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800841
Svetoslav7ec28e82015-05-20 17:01:10 -0700842 for (int i = 0; i < nameCount; i++) {
843 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800844
Svetoslav7ec28e82015-05-20 17:01:10 -0700845 // Determine the owning user as some profile settings are cloned from the parent.
846 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
847 name);
Svetoslav683914b2015-01-15 14:22:26 -0800848
Svetoslav7ec28e82015-05-20 17:01:10 -0700849 Setting setting = mSettingsRegistry.getSettingLocked(
850 SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name);
851 appendSettingToCursor(result, setting);
852 }
853
854 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800855 }
Svetoslav683914b2015-01-15 14:22:26 -0800856 }
857
Svetoslav7ec28e82015-05-20 17:01:10 -0700858 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800859 if (DEBUG) {
860 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
861 }
862
863 // Resolve the userId on whose behalf the call is made.
864 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
865
866 // Determine the owning user as some profile settings are cloned from the parent.
867 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
868
869 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700870 synchronized (mLock) {
871 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
872 owningUserId, name);
873 }
Svetoslav683914b2015-01-15 14:22:26 -0800874 }
875
Svetoslav7ec28e82015-05-20 17:01:10 -0700876 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800877 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700878 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800879 + requestingUserId + ")");
880 }
881
Svetoslav7ec28e82015-05-20 17:01:10 -0700882 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800883 }
884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800886 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800888 }
889
Svetoslav7ec28e82015-05-20 17:01:10 -0700890 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800891 }
892
Svetoslav7ec28e82015-05-20 17:01:10 -0700893 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800894 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700895 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800896 + requestingUserId + ")");
897 }
898
Svetoslav7ec28e82015-05-20 17:01:10 -0700899 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800900 }
901
Svetoslav7ec28e82015-05-20 17:01:10 -0700902 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800903 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +0100904 if (!hasWriteSecureSettingsPermission()) {
905 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
906 // operation is allowed for the calling package through appops.
907 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
908 Binder.getCallingUid(), getCallingPackage(), true)) {
909 return false;
910 }
Svetoslav683914b2015-01-15 14:22:26 -0800911 }
912
Svetoslav683914b2015-01-15 14:22:26 -0800913 // Resolve the userId on whose behalf the call is made.
914 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
915
Svetoslavd8d25e02015-11-20 13:09:26 -0800916 // Enforce what the calling package can mutate the system settings.
917 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
918
Svetoslav683914b2015-01-15 14:22:26 -0800919 // Determine the owning user as some profile settings are cloned from the parent.
920 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
921
922 // Only the owning user id can change the setting.
923 if (owningUserId != callingUserId) {
924 return false;
925 }
926
Jeff Sharkey413573a2016-02-22 17:52:45 -0700927 // Invalidate any relevant cache files
928 String cacheName = null;
929 if (Settings.System.RINGTONE.equals(name)) {
930 cacheName = Settings.System.RINGTONE_CACHE;
931 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
932 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
933 } else if (Settings.System.ALARM_ALERT.equals(name)) {
934 cacheName = Settings.System.ALARM_ALERT_CACHE;
935 }
936 if (cacheName != null) {
937 final File cacheFile = new File(
938 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
939 cacheFile.delete();
940 }
941
Svetoslav683914b2015-01-15 14:22:26 -0800942 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 synchronized (mLock) {
944 switch (operation) {
945 case MUTATION_OPERATION_INSERT: {
946 validateSystemSettingValue(name, value);
947 return mSettingsRegistry
948 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
949 owningUserId, name, value, getCallingPackage());
950 }
951
952 case MUTATION_OPERATION_DELETE: {
953 return mSettingsRegistry.deleteSettingLocked(
954 SettingsRegistry.SETTINGS_TYPE_SYSTEM,
955 owningUserId, name);
956 }
957
958 case MUTATION_OPERATION_UPDATE: {
959 validateSystemSettingValue(name, value);
960 return mSettingsRegistry
961 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
962 owningUserId, name, value, getCallingPackage());
963 }
Svetoslav683914b2015-01-15 14:22:26 -0800964 }
965
Svetoslav7ec28e82015-05-20 17:01:10 -0700966 return false;
Svetoslav683914b2015-01-15 14:22:26 -0800967 }
Svetoslav683914b2015-01-15 14:22:26 -0800968 }
969
Billy Lau6ad2d662015-07-18 00:26:58 +0100970 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -0700971 // Write secure settings is a more protected permission. If caller has it we are good.
972 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
973 == PackageManager.PERMISSION_GRANTED) {
974 return true;
975 }
976
Svetoslavf41334b2015-06-23 12:06:03 -0700977 return false;
978 }
979
Svetoslav683914b2015-01-15 14:22:26 -0800980 private void validateSystemSettingValue(String name, String value) {
981 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
982 if (validator != null && !validator.validate(value)) {
983 throw new IllegalArgumentException("Invalid value: " + value
984 + " for setting: " + name);
985 }
986 }
987
988 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
989 int owningUserId) {
990 // Optimization - location providers are restricted only for managed profiles.
991 if (callingUserId == owningUserId) {
992 return false;
993 }
994 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
995 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
996 new UserHandle(callingUserId))) {
997 return true;
998 }
999 return false;
1000 }
1001
Makoto Onuki28da2e32015-11-20 11:30:44 -08001002 /**
1003 * Checks whether changing a setting to a value is prohibited by the corresponding user
1004 * restriction.
1005 *
1006 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestrictionLR},
1007 * which should be in sync with this method.
1008 *
1009 * @return true if the change is prohibited, false if the change is allowed.
1010 */
1011 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
1012 String value) {
1013 String restriction;
1014 switch (setting) {
1015 case Settings.Secure.LOCATION_MODE:
1016 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1017 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1018 // here normally, but we still protect it here from a direct provider write.
1019 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1020 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1021 break;
1022
1023 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1024 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1025 // a provider, which should be allowed even if the user restriction is set.
1026 if (value != null && value.startsWith("-")) return false;
1027 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1028 break;
1029
1030 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1031 if ("0".equals(value)) return false;
1032 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1033 break;
1034
1035 case Settings.Global.ADB_ENABLED:
1036 if ("0".equals(value)) return false;
1037 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1038 break;
1039
1040 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1041 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1042 if ("1".equals(value)) return false;
1043 restriction = UserManager.ENSURE_VERIFY_APPS;
1044 break;
1045
1046 case Settings.Global.PREFERRED_NETWORK_MODE:
1047 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1048 break;
1049
1050 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001051 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001052 if ("0".equals(value)) return false;
1053 restriction = UserManager.DISALLOW_DATA_ROAMING;
1054 break;
1055 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001056 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001057 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001058
1059 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001060 }
1061
1062 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1063 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1064 }
1065
1066 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1067 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1068 }
1069
1070 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1071 final int parentId = getGroupParentLocked(userId);
1072 if (parentId != userId && keys.contains(name)) {
1073 return parentId;
1074 }
1075 return userId;
1076 }
1077
Svetoslavf41334b2015-06-23 12:06:03 -07001078 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001079 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001080 // System/root/shell can mutate whatever secure settings they want.
1081 final int callingUid = Binder.getCallingUid();
1082 if (callingUid == android.os.Process.SYSTEM_UID
1083 || callingUid == Process.SHELL_UID
1084 || callingUid == Process.ROOT_UID) {
1085 return;
1086 }
1087
1088 switch (operation) {
1089 case MUTATION_OPERATION_INSERT:
1090 // Insert updates.
1091 case MUTATION_OPERATION_UPDATE: {
1092 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1093 return;
1094 }
1095
1096 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001097 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001098
1099 // Privileged apps can do whatever they want.
1100 if ((packageInfo.applicationInfo.privateFlags
1101 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1102 return;
1103 }
1104
1105 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1106 packageInfo.applicationInfo.targetSdkVersion, name);
1107 } break;
1108
1109 case MUTATION_OPERATION_DELETE: {
1110 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1111 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1112 throw new IllegalArgumentException("You cannot delete system defined"
1113 + " secure settings.");
1114 }
1115
1116 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001117 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001118
1119 // Privileged apps can do whatever they want.
1120 if ((packageInfo.applicationInfo.privateFlags &
1121 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1122 return;
1123 }
1124
1125 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1126 packageInfo.applicationInfo.targetSdkVersion, name);
1127 } break;
1128 }
1129 }
1130
Xiaohui Chen43765b72015-08-31 10:57:33 -07001131 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001132 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001133 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1134 getCallingPackage(), 0, userId);
1135 if (packageInfo != null) {
1136 return packageInfo;
1137 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001138 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001139 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001140 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001141 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001142 }
1143
1144 private int getGroupParentLocked(int userId) {
1145 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001146 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001147 return userId;
1148 }
1149 // We are in the same process with the user manager and the returned
1150 // user info is a cached instance, so just look up instead of cache.
1151 final long identity = Binder.clearCallingIdentity();
1152 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001153 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001154 UserInfo userInfo = mUserManager.getProfileParent(userId);
1155 return (userInfo != null) ? userInfo.id : userId;
1156 } finally {
1157 Binder.restoreCallingIdentity(identity);
1158 }
1159 }
1160
Svetoslav683914b2015-01-15 14:22:26 -08001161 private void enforceWritePermission(String permission) {
1162 if (getContext().checkCallingOrSelfPermission(permission)
1163 != PackageManager.PERMISSION_GRANTED) {
1164 throw new SecurityException("Permission denial: writing to settings requires:"
1165 + permission);
1166 }
1167 }
1168
1169 /*
1170 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1171 * This setting contains a list of the currently enabled location providers.
1172 * But helper functions in android.providers.Settings can enable or disable
1173 * a single provider by using a "+" or "-" prefix before the provider name.
1174 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001175 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1176 * is set, the said method will only allow values with the "-" prefix.
1177 *
Svetoslav683914b2015-01-15 14:22:26 -08001178 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001179 */
Svetoslavb596a2c2015-02-17 21:37:09 -08001180 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001181 if (TextUtils.isEmpty(value)) {
1182 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001183 }
1184
Svetoslav683914b2015-01-15 14:22:26 -08001185 final char prefix = value.charAt(0);
1186 if (prefix != '+' && prefix != '-') {
1187 return false;
1188 }
1189
1190 // skip prefix
1191 value = value.substring(1);
1192
Svetoslav7ec28e82015-05-20 17:01:10 -07001193 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001194 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1195
1196 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1197
1198 int index = oldProviders.indexOf(value);
1199 int end = index + value.length();
1200
1201 // check for commas to avoid matching on partial string
1202 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1203 index = -1;
1204 }
1205
1206 // check for commas to avoid matching on partial string
1207 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1208 index = -1;
1209 }
1210
1211 String newProviders;
1212
1213 if (prefix == '+' && index < 0) {
1214 // append the provider to the list if not present
1215 if (oldProviders.length() == 0) {
1216 newProviders = value;
1217 } else {
1218 newProviders = oldProviders + ',' + value;
1219 }
1220 } else if (prefix == '-' && index >= 0) {
1221 // remove the provider from the list if present
1222 // remove leading or trailing comma
1223 if (index > 0) {
1224 index--;
1225 } else if (end < oldProviders.length()) {
1226 end++;
1227 }
1228
1229 newProviders = oldProviders.substring(0, index);
1230 if (end < oldProviders.length()) {
1231 newProviders += oldProviders.substring(end);
1232 }
1233 } else {
1234 // nothing changed, so no need to update the database
1235 return false;
1236 }
1237
Svetoslavb596a2c2015-02-17 21:37:09 -08001238 return mSettingsRegistry.insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
1239 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1240 getCallingPackage());
Svetoslav683914b2015-01-15 14:22:26 -08001241 }
1242
Svetoslav683914b2015-01-15 14:22:26 -08001243 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1244 int targetSdkVersion, String name) {
1245 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1246 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1247 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1248 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1249 + " This will soon become an error.");
1250 } else {
1251 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1252 + " This will soon become an error.");
1253 }
1254 } else {
1255 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1256 throw new IllegalArgumentException("You cannot change private secure settings.");
1257 } else {
1258 throw new IllegalArgumentException("You cannot keep your settings in"
1259 + " the secure settings.");
1260 }
1261 }
1262 }
1263
1264 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1265 if (requestingUserId == UserHandle.getCallingUserId()) {
1266 return requestingUserId;
1267 }
1268 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1269 Binder.getCallingUid(), requestingUserId, false, true,
1270 "get/set setting for user", null);
1271 }
1272
1273 private static Bundle packageValueForCallResult(Setting setting) {
1274 if (setting == null) {
1275 return NULL_SETTING;
1276 }
1277 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1278 }
1279
1280 private static int getRequestingUserId(Bundle args) {
1281 final int callingUserId = UserHandle.getCallingUserId();
1282 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1283 : callingUserId;
1284 }
1285
1286 private static String getSettingValue(Bundle args) {
1287 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1288 }
1289
1290 private static String getValidTableOrThrow(Uri uri) {
1291 if (uri.getPathSegments().size() > 0) {
1292 String table = uri.getPathSegments().get(0);
1293 if (DatabaseHelper.isValidTable(table)) {
1294 return table;
1295 }
1296 throw new IllegalArgumentException("Bad root path: " + table);
1297 }
1298 throw new IllegalArgumentException("Invalid URI:" + uri);
1299 }
1300
1301 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1302 if (setting == null) {
1303 return new MatrixCursor(projection, 0);
1304 }
1305 MatrixCursor cursor = new MatrixCursor(projection, 1);
1306 appendSettingToCursor(cursor, setting);
1307 return cursor;
1308 }
1309
1310 private static String[] normalizeProjection(String[] projection) {
1311 if (projection == null) {
1312 return ALL_COLUMNS;
1313 }
1314
1315 final int columnCount = projection.length;
1316 for (int i = 0; i < columnCount; i++) {
1317 String column = projection[i];
1318 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1319 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001320 }
1321 }
1322
Svetoslav683914b2015-01-15 14:22:26 -08001323 return projection;
1324 }
1325
1326 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1327 final int columnCount = cursor.getColumnCount();
1328
1329 String[] values = new String[columnCount];
1330
1331 for (int i = 0; i < columnCount; i++) {
1332 String column = cursor.getColumnName(i);
1333
1334 switch (column) {
1335 case Settings.NameValueTable._ID: {
1336 values[i] = setting.getId();
1337 } break;
1338
1339 case Settings.NameValueTable.NAME: {
1340 values[i] = setting.getName();
1341 } break;
1342
1343 case Settings.NameValueTable.VALUE: {
1344 values[i] = setting.getValue();
1345 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001346 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001347 }
1348
Svetoslav683914b2015-01-15 14:22:26 -08001349 cursor.addRow(values);
1350 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001351
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001352 private static boolean isKeyValid(String key) {
1353 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1354 }
1355
Svetoslav683914b2015-01-15 14:22:26 -08001356 private static final class Arguments {
1357 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1358 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1359
1360 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1361 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1362
1363 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1364 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1365
1366 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1367 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1368
1369 public final String table;
1370 public final String name;
1371
1372 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1373 final int segmentSize = uri.getPathSegments().size();
1374 switch (segmentSize) {
1375 case 1: {
1376 if (where != null
1377 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1378 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1379 && whereArgs.length == 1) {
1380 name = whereArgs[0];
1381 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001382 return;
Svetoslav683914b2015-01-15 14:22:26 -08001383 } else if (where != null
1384 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1385 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1386 final int startIndex = Math.max(where.indexOf("'"),
1387 where.indexOf("\"")) + 1;
1388 final int endIndex = Math.max(where.lastIndexOf("'"),
1389 where.lastIndexOf("\""));
1390 name = where.substring(startIndex, endIndex);
1391 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001392 return;
Svetoslav683914b2015-01-15 14:22:26 -08001393 } else if (supportAll && where == null && whereArgs == null) {
1394 name = null;
1395 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001396 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001397 }
Svetoslav683914b2015-01-15 14:22:26 -08001398 } break;
1399
Svetoslav28494652015-02-12 14:11:42 -08001400 case 2: {
1401 if (where == null && whereArgs == null) {
1402 name = uri.getPathSegments().get(1);
1403 table = computeTableForSetting(uri, name);
1404 return;
1405 }
1406 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001407 }
Svetoslav28494652015-02-12 14:11:42 -08001408
1409 EventLogTags.writeUnsupportedSettingsQuery(
1410 uri.toSafeString(), where, Arrays.toString(whereArgs));
1411 String message = String.format( "Supported SQL:\n"
1412 + " uri content://some_table/some_property with null where and where args\n"
1413 + " uri content://some_table with query name=? and single name as arg\n"
1414 + " uri content://some_table with query name=some_name and null args\n"
1415 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1416 Arrays.toString(whereArgs));
1417 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001418 }
1419
Svetoslav28494652015-02-12 14:11:42 -08001420 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001421 String table = getValidTableOrThrow(uri);
1422
1423 if (name != null) {
1424 if (sSystemMovedToSecureSettings.contains(name)) {
1425 table = TABLE_SECURE;
1426 }
1427
1428 if (sSystemMovedToGlobalSettings.contains(name)) {
1429 table = TABLE_GLOBAL;
1430 }
1431
1432 if (sSecureMovedToGlobalSettings.contains(name)) {
1433 table = TABLE_GLOBAL;
1434 }
1435
1436 if (sGlobalMovedToSecureSettings.contains(name)) {
1437 table = TABLE_SECURE;
1438 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001439 }
Svetoslav683914b2015-01-15 14:22:26 -08001440
1441 return table;
1442 }
1443 }
1444
1445 final class SettingsRegistry {
1446 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1447
1448 private static final int SETTINGS_TYPE_GLOBAL = 0;
1449 private static final int SETTINGS_TYPE_SYSTEM = 1;
1450 private static final int SETTINGS_TYPE_SECURE = 2;
1451
1452 private static final int SETTINGS_TYPE_MASK = 0xF0000000;
1453 private static final int SETTINGS_TYPE_SHIFT = 28;
1454
1455 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1456 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1457 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1458
1459 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1460
1461 private final BackupManager mBackupManager;
1462
Svetoslav7e0683b2015-08-03 16:02:52 -07001463 private final Handler mHandler;
1464
Svetoslav683914b2015-01-15 14:22:26 -08001465 public SettingsRegistry() {
1466 mBackupManager = new BackupManager(getContext());
Svetoslav7e0683b2015-08-03 16:02:52 -07001467 mHandler = new MyHandler(getContext().getMainLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001468 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001469 }
1470
Svetoslav683914b2015-01-15 14:22:26 -08001471 public List<String> getSettingsNamesLocked(int type, int userId) {
1472 final int key = makeKey(type, userId);
1473 SettingsState settingsState = peekSettingsStateLocked(key);
1474 return settingsState.getSettingNamesLocked();
1475 }
1476
1477 public SettingsState getSettingsLocked(int type, int userId) {
1478 final int key = makeKey(type, userId);
1479 return peekSettingsStateLocked(key);
1480 }
1481
1482 public void ensureSettingsForUserLocked(int userId) {
1483 // Migrate the setting for this user if needed.
1484 migrateLegacySettingsForUserIfNeededLocked(userId);
1485
1486 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001487 if (userId == UserHandle.USER_SYSTEM) {
1488 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001489 ensureSettingsStateLocked(globalKey);
1490 }
1491
1492 // Ensure secure settings loaded.
1493 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1494 ensureSettingsStateLocked(secureKey);
1495
1496 // Make sure the secure settings have an Android id set.
1497 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1498 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1499
1500 // Ensure system settings loaded.
1501 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1502 ensureSettingsStateLocked(systemKey);
1503
1504 // Upgrade the settings to the latest version.
1505 UpgradeController upgrader = new UpgradeController(userId);
1506 upgrader.upgradeIfNeededLocked();
1507 }
1508
1509 private void ensureSettingsStateLocked(int key) {
1510 if (mSettingsStates.get(key) == null) {
1511 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1512 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1513 maxBytesPerPackage);
1514 mSettingsStates.put(key, settingsState);
1515 }
1516 }
1517
1518 public void removeUserStateLocked(int userId, boolean permanently) {
1519 // We always keep the global settings in memory.
1520
1521 // Nuke system settings.
1522 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1523 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1524 if (systemSettingsState != null) {
1525 if (permanently) {
1526 mSettingsStates.remove(systemKey);
1527 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001528 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001529 systemSettingsState.destroyLocked(new Runnable() {
1530 @Override
1531 public void run() {
1532 mSettingsStates.remove(systemKey);
1533 }
1534 });
1535 }
1536 }
1537
1538 // Nuke secure settings.
1539 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1540 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1541 if (secureSettingsState != null) {
1542 if (permanently) {
1543 mSettingsStates.remove(secureKey);
1544 secureSettingsState.destroyLocked(null);
1545 } else {
1546 secureSettingsState.destroyLocked(new Runnable() {
1547 @Override
1548 public void run() {
1549 mSettingsStates.remove(secureKey);
1550 }
1551 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001552 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001553 }
1554 }
1555
Svetoslav683914b2015-01-15 14:22:26 -08001556 public boolean insertSettingLocked(int type, int userId, String name, String value,
1557 String packageName) {
1558 final int key = makeKey(type, userId);
1559
1560 SettingsState settingsState = peekSettingsStateLocked(key);
1561 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1562
1563 if (success) {
1564 notifyForSettingsChange(key, name);
1565 }
1566 return success;
1567 }
1568
1569 public boolean deleteSettingLocked(int type, int userId, String name) {
1570 final int key = makeKey(type, userId);
1571
1572 SettingsState settingsState = peekSettingsStateLocked(key);
1573 final boolean success = settingsState.deleteSettingLocked(name);
1574
1575 if (success) {
1576 notifyForSettingsChange(key, name);
1577 }
1578 return success;
1579 }
1580
1581 public Setting getSettingLocked(int type, int userId, String name) {
1582 final int key = makeKey(type, userId);
1583
1584 SettingsState settingsState = peekSettingsStateLocked(key);
1585 return settingsState.getSettingLocked(name);
1586 }
1587
1588 public boolean updateSettingLocked(int type, int userId, String name, String value,
1589 String packageName) {
1590 final int key = makeKey(type, userId);
1591
1592 SettingsState settingsState = peekSettingsStateLocked(key);
1593 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1594
1595 if (success) {
1596 notifyForSettingsChange(key, name);
1597 }
1598
1599 return success;
1600 }
1601
1602 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001603 // Global and secure settings are signature protected. Apps signed
1604 // by the platform certificate are generally not uninstalled and
1605 // the main exception is tests. We trust components signed
1606 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001607
1608 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1609 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001610 if (systemSettings != null) {
1611 systemSettings.onPackageRemovedLocked(packageName);
1612 }
Svetoslav683914b2015-01-15 14:22:26 -08001613 }
1614
1615 private SettingsState peekSettingsStateLocked(int key) {
1616 SettingsState settingsState = mSettingsStates.get(key);
1617 if (settingsState != null) {
1618 return settingsState;
1619 }
1620
1621 ensureSettingsForUserLocked(getUserIdFromKey(key));
1622 return mSettingsStates.get(key);
1623 }
1624
1625 private void migrateAllLegacySettingsIfNeeded() {
1626 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001627 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001628 File globalFile = getSettingsFile(key);
1629 if (globalFile.exists()) {
1630 return;
1631 }
1632
1633 final long identity = Binder.clearCallingIdentity();
1634 try {
1635 List<UserInfo> users = mUserManager.getUsers(true);
1636
1637 final int userCount = users.size();
1638 for (int i = 0; i < userCount; i++) {
1639 final int userId = users.get(i).id;
1640
1641 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1642 SQLiteDatabase database = dbHelper.getWritableDatabase();
1643 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1644
1645 // Upgrade to the latest version.
1646 UpgradeController upgrader = new UpgradeController(userId);
1647 upgrader.upgradeIfNeededLocked();
1648
1649 // Drop from memory if not a running user.
1650 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1651 removeUserStateLocked(userId, false);
1652 }
1653 }
1654 } finally {
1655 Binder.restoreCallingIdentity(identity);
1656 }
1657 }
1658 }
1659
1660 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1661 // Every user has secure settings and if no file we need to migrate.
1662 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1663 File secureFile = getSettingsFile(secureKey);
1664 if (secureFile.exists()) {
1665 return;
1666 }
1667
1668 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1669 SQLiteDatabase database = dbHelper.getWritableDatabase();
1670
1671 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1672 }
1673
1674 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1675 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001676 // Move over the system settings.
1677 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1678 ensureSettingsStateLocked(systemKey);
1679 SettingsState systemSettings = mSettingsStates.get(systemKey);
1680 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1681 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001682
1683 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001684 // Do this after System settings, since this is the first thing we check when deciding
1685 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001686 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1687 ensureSettingsStateLocked(secureKey);
1688 SettingsState secureSettings = mSettingsStates.get(secureKey);
1689 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1690 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1691 secureSettings.persistSyncLocked();
1692
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001693 // Move over the global settings if owner.
1694 // Do this last, since this is the first thing we check when deciding
1695 // to skip over migration from db to xml for owner user.
1696 if (userId == UserHandle.USER_SYSTEM) {
1697 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1698 ensureSettingsStateLocked(globalKey);
1699 SettingsState globalSettings = mSettingsStates.get(globalKey);
1700 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1701 globalSettings.persistSyncLocked();
1702 }
Svetoslav683914b2015-01-15 14:22:26 -08001703
1704 // Drop the database as now all is moved and persisted.
1705 if (DROP_DATABASE_ON_MIGRATION) {
1706 dbHelper.dropDatabase();
1707 } else {
1708 dbHelper.backupDatabase();
1709 }
1710 }
1711
1712 private void migrateLegacySettingsLocked(SettingsState settingsState,
1713 SQLiteDatabase database, String table) {
1714 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1715 queryBuilder.setTables(table);
1716
1717 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1718 null, null, null, null, null);
1719
1720 if (cursor == null) {
1721 return;
1722 }
1723
1724 try {
1725 if (!cursor.moveToFirst()) {
1726 return;
1727 }
1728
1729 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1730 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1731
1732 settingsState.setVersionLocked(database.getVersion());
1733
1734 while (!cursor.isAfterLast()) {
1735 String name = cursor.getString(nameColumnIdx);
1736 String value = cursor.getString(valueColumnIdx);
1737 settingsState.insertSettingLocked(name, value,
1738 SettingsState.SYSTEM_PACKAGE_NAME);
1739 cursor.moveToNext();
1740 }
1741 } finally {
1742 cursor.close();
1743 }
1744 }
1745
1746 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1747 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1748
1749 if (value != null) {
1750 return;
1751 }
1752
1753 final int userId = getUserIdFromKey(secureSettings.mKey);
1754
1755 final UserInfo user;
1756 final long identity = Binder.clearCallingIdentity();
1757 try {
1758 user = mUserManager.getUserInfo(userId);
1759 } finally {
1760 Binder.restoreCallingIdentity(identity);
1761 }
1762 if (user == null) {
1763 // Can happen due to races when deleting users - treat as benign.
1764 return;
1765 }
1766
1767 String androidId = Long.toHexString(new SecureRandom().nextLong());
1768 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1769 SettingsState.SYSTEM_PACKAGE_NAME);
1770
1771 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1772 + "] for user " + userId);
1773
1774 // Write a drop box entry if it's a restricted profile
1775 if (user.isRestricted()) {
1776 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1777 Context.DROPBOX_SERVICE);
1778 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1779 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1780 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1781 }
1782 }
1783 }
1784
1785 private void notifyForSettingsChange(int key, String name) {
1786 // Update the system property *first*, so if someone is listening for
1787 // a notification and then using the contract class to get their data,
1788 // the system property will be updated and they'll get the new data.
1789
1790 boolean backedUpDataChanged = false;
1791 String property = null;
1792 if (isGlobalSettingsKey(key)) {
1793 property = Settings.Global.SYS_PROP_SETTING_VERSION;
1794 backedUpDataChanged = true;
1795 } else if (isSecureSettingsKey(key)) {
1796 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
1797 backedUpDataChanged = true;
1798 } else if (isSystemSettingsKey(key)) {
1799 property = Settings.System.SYS_PROP_SETTING_VERSION;
1800 backedUpDataChanged = true;
1801 }
1802
1803 if (property != null) {
1804 final long version = SystemProperties.getLong(property, 0) + 1;
1805 SystemProperties.set(property, Long.toString(version));
1806 if (DEBUG) {
1807 Slog.v(LOG_TAG, "System property " + property + "=" + version);
1808 }
1809 }
1810
1811 // Inform the backup manager about a data change
1812 if (backedUpDataChanged) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001813 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Svetoslav683914b2015-01-15 14:22:26 -08001814 }
1815
1816 // Now send the notification through the content framework.
1817
1818 final int userId = getUserIdFromKey(key);
1819 Uri uri = getNotificationUriFor(key, name);
1820
Svetoslav7e0683b2015-08-03 16:02:52 -07001821 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1822 userId, 0, uri).sendToTarget();
1823
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001824 if (isSecureSettingsKey(key)) {
1825 maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
1826 } else if (isSystemSettingsKey(key)) {
1827 maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
1828 }
1829 }
1830
1831 private void maybeNotifyProfiles(int userId, Uri uri, String name,
1832 Set<String> keysCloned) {
1833 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001834 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001835 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001836 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001837 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001838 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001839 }
1840 }
1841 }
Svetoslav683914b2015-01-15 14:22:26 -08001842 }
1843
1844 private int makeKey(int type, int userId) {
1845 return (type << SETTINGS_TYPE_SHIFT) | userId;
1846 }
1847
1848 private int getTypeFromKey(int key) {
1849 return key >> SETTINGS_TYPE_SHIFT;
1850 }
1851
1852 private int getUserIdFromKey(int key) {
1853 return key & ~SETTINGS_TYPE_MASK;
1854 }
1855
1856 private boolean isGlobalSettingsKey(int key) {
1857 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1858 }
1859
1860 private boolean isSystemSettingsKey(int key) {
1861 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1862 }
1863
1864 private boolean isSecureSettingsKey(int key) {
1865 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1866 }
1867
1868 private File getSettingsFile(int key) {
1869 if (isGlobalSettingsKey(key)) {
1870 final int userId = getUserIdFromKey(key);
1871 return new File(Environment.getUserSystemDirectory(userId),
1872 SETTINGS_FILE_GLOBAL);
1873 } else if (isSystemSettingsKey(key)) {
1874 final int userId = getUserIdFromKey(key);
1875 return new File(Environment.getUserSystemDirectory(userId),
1876 SETTINGS_FILE_SYSTEM);
1877 } else if (isSecureSettingsKey(key)) {
1878 final int userId = getUserIdFromKey(key);
1879 return new File(Environment.getUserSystemDirectory(userId),
1880 SETTINGS_FILE_SECURE);
1881 } else {
1882 throw new IllegalArgumentException("Invalid settings key:" + key);
1883 }
1884 }
1885
1886 private Uri getNotificationUriFor(int key, String name) {
1887 if (isGlobalSettingsKey(key)) {
1888 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
1889 : Settings.Global.CONTENT_URI;
1890 } else if (isSecureSettingsKey(key)) {
1891 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
1892 : Settings.Secure.CONTENT_URI;
1893 } else if (isSystemSettingsKey(key)) {
1894 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
1895 : Settings.System.CONTENT_URI;
1896 } else {
1897 throw new IllegalArgumentException("Invalid settings key:" + key);
1898 }
1899 }
1900
1901 private int getMaxBytesPerPackageForType(int type) {
1902 switch (type) {
1903 case SETTINGS_TYPE_GLOBAL:
1904 case SETTINGS_TYPE_SECURE: {
1905 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
1906 }
1907
1908 default: {
1909 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
1910 }
1911 }
1912 }
1913
Svetoslav7e0683b2015-08-03 16:02:52 -07001914 private final class MyHandler extends Handler {
1915 private static final int MSG_NOTIFY_URI_CHANGED = 1;
1916 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
1917
1918 public MyHandler(Looper looper) {
1919 super(looper);
1920 }
1921
1922 @Override
1923 public void handleMessage(Message msg) {
1924 switch (msg.what) {
1925 case MSG_NOTIFY_URI_CHANGED: {
1926 final int userId = msg.arg1;
1927 Uri uri = (Uri) msg.obj;
1928 getContext().getContentResolver().notifyChange(uri, null, true, userId);
1929 if (DEBUG) {
1930 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
1931 }
1932 } break;
1933
1934 case MSG_NOTIFY_DATA_CHANGED: {
1935 mBackupManager.dataChanged();
1936 } break;
1937 }
1938 }
1939 }
1940
Svetoslav683914b2015-01-15 14:22:26 -08001941 private final class UpgradeController {
Ruben Brunk98576cf2016-03-07 18:54:28 -08001942 private static final int SETTINGS_VERSION = 126;
Svetoslav683914b2015-01-15 14:22:26 -08001943
1944 private final int mUserId;
1945
1946 public UpgradeController(int userId) {
1947 mUserId = userId;
1948 }
1949
1950 public void upgradeIfNeededLocked() {
1951 // The version of all settings for a user is the same (all users have secure).
1952 SettingsState secureSettings = getSettingsLocked(
1953 SettingsRegistry.SETTINGS_TYPE_SECURE, mUserId);
1954
1955 // Try an update from the current state.
1956 final int oldVersion = secureSettings.getVersionLocked();
1957 final int newVersion = SETTINGS_VERSION;
1958
Svet Ganovc9755bc2015-03-28 13:21:22 -07001959 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08001960 if (oldVersion == newVersion) {
1961 return;
1962 }
1963
1964 // Try to upgrade.
1965 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
1966
1967 // If upgrade failed start from scratch and upgrade.
1968 if (curVersion != newVersion) {
1969 // Drop state we have for this user.
1970 removeUserStateLocked(mUserId, true);
1971
1972 // Recreate the database.
1973 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
1974 SQLiteDatabase database = dbHelper.getWritableDatabase();
1975 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
1976
1977 // Migrate the settings for this user.
1978 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
1979
1980 // Now upgrade should work fine.
1981 onUpgradeLocked(mUserId, oldVersion, newVersion);
1982 }
1983
1984 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001985 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001986 SettingsState globalSettings = getSettingsLocked(
1987 SettingsRegistry.SETTINGS_TYPE_GLOBAL, mUserId);
1988 globalSettings.setVersionLocked(newVersion);
1989 }
1990
1991 // Set the secure settings version.
1992 secureSettings.setVersionLocked(newVersion);
1993
1994 // Set the system settings version.
1995 SettingsState systemSettings = getSettingsLocked(
1996 SettingsRegistry.SETTINGS_TYPE_SYSTEM, mUserId);
1997 systemSettings.setVersionLocked(newVersion);
1998 }
1999
2000 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002001 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002002 }
2003
2004 private SettingsState getSecureSettingsLocked(int userId) {
2005 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2006 }
2007
2008 private SettingsState getSystemSettingsLocked(int userId) {
2009 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2010 }
2011
Jeff Brown503cffc2015-03-26 18:08:51 -07002012 /**
2013 * You must perform all necessary mutations to bring the settings
2014 * for this user from the old to the new version. When you add a new
2015 * upgrade step you *must* update SETTINGS_VERSION.
2016 *
2017 * This is an example of moving a setting from secure to global.
2018 *
2019 * // v119: Example settings changes.
2020 * if (currentVersion == 118) {
2021 * if (userId == UserHandle.USER_OWNER) {
2022 * // Remove from the secure settings.
2023 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2024 * String name = "example_setting_to_move";
2025 * String value = secureSettings.getSetting(name);
2026 * secureSettings.deleteSetting(name);
2027 *
2028 * // Add to the global settings.
2029 * SettingsState globalSettings = getGlobalSettingsLocked();
2030 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2031 * }
2032 *
2033 * // Update the current version.
2034 * currentVersion = 119;
2035 * }
2036 */
Svetoslav683914b2015-01-15 14:22:26 -08002037 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2038 if (DEBUG) {
2039 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2040 + oldVersion + " to version: " + newVersion);
2041 }
2042
Jeff Brown503cffc2015-03-26 18:08:51 -07002043 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002044
John Spurlocke11ae112015-05-11 16:09:03 -04002045 // v119: Reset zen + ringer mode.
2046 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002047 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002048 final SettingsState globalSettings = getGlobalSettingsLocked();
2049 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2050 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2051 SettingsState.SYSTEM_PACKAGE_NAME);
2052 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2053 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2054 SettingsState.SYSTEM_PACKAGE_NAME);
2055 }
2056 currentVersion = 119;
2057 }
2058
Jason Monk27bbb2d2015-03-31 16:46:39 -04002059 // v120: Add double tap to wake setting.
2060 if (currentVersion == 119) {
2061 SettingsState secureSettings = getSecureSettingsLocked(userId);
2062 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2063 getContext().getResources().getBoolean(
2064 R.bool.def_double_tap_to_wake) ? "1" : "0",
2065 SettingsState.SYSTEM_PACKAGE_NAME);
2066
2067 currentVersion = 120;
2068 }
2069
Svetoslav7e0683b2015-08-03 16:02:52 -07002070 if (currentVersion == 120) {
2071 // Before 121, we used a different string encoding logic. We just bump the
2072 // version here; SettingsState knows how to handle pre-version 120 files.
2073 currentVersion = 121;
2074 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002075
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002076 if (currentVersion == 121) {
2077 // Version 122: allow OEMs to set a default payment component in resources.
2078 // Note that we only write the default if no default has been set;
2079 // if there is, we just leave the default at whatever it currently is.
2080 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2081 String defaultComponent = (getContext().getResources().getString(
2082 R.string.def_nfc_payment_component));
2083 Setting currentSetting = secureSettings.getSettingLocked(
2084 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2085 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2086 currentSetting == null) {
2087 secureSettings.insertSettingLocked(
2088 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2089 defaultComponent,
2090 SettingsState.SYSTEM_PACKAGE_NAME);
2091 }
2092 currentVersion = 122;
2093 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002094
2095 if (currentVersion == 122) {
2096 // Version 123: Adding a default value for the ability to add a user from
2097 // the lock screen.
2098 if (userId == UserHandle.USER_SYSTEM) {
2099 final SettingsState globalSettings = getGlobalSettingsLocked();
2100 Setting currentSetting = globalSettings.getSettingLocked(
2101 Settings.Global.ADD_USERS_WHEN_LOCKED);
2102 if (currentSetting == null) {
2103 globalSettings.insertSettingLocked(
2104 Settings.Global.ADD_USERS_WHEN_LOCKED,
2105 getContext().getResources().getBoolean(
2106 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2107 SettingsState.SYSTEM_PACKAGE_NAME);
2108 }
2109 }
2110 currentVersion = 123;
2111 }
Bryce Leebd179282015-12-17 19:01:37 -08002112
2113 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002114 final SettingsState globalSettings = getGlobalSettingsLocked();
2115 String defaultDisabledProfiles = (getContext().getResources().getString(
2116 R.string.def_bluetooth_disabled_profiles));
2117 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2118 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002119 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002120 }
2121
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002122 if (currentVersion == 124) {
2123 // Version 124: allow OEMs to set a default value for whether IME should be
2124 // shown when a physical keyboard is connected.
2125 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2126 Setting currentSetting = secureSettings.getSettingLocked(
2127 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
2128 if (currentSetting == null) {
2129 secureSettings.insertSettingLocked(
2130 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2131 getContext().getResources().getBoolean(
2132 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2133 SettingsState.SYSTEM_PACKAGE_NAME);
2134 }
2135 currentVersion = 125;
2136 }
2137
Ruben Brunk98576cf2016-03-07 18:54:28 -08002138 if (currentVersion == 125) {
2139 // Version 125: Allow OEMs to set the default VR service.
2140 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2141
2142 Setting currentSetting = secureSettings.getSettingLocked(
2143 Settings.Secure.ENABLED_VR_LISTENERS);
2144 if (currentSetting == null) {
2145 ArraySet<ComponentName> l =
2146 SystemConfig.getInstance().getDefaultVrComponents();
2147
2148 if (l != null && !l.isEmpty()) {
2149 StringBuilder b = new StringBuilder();
2150 boolean start = true;
2151 for (ComponentName c : l) {
2152 if (!start) {
2153 b.append(':');
2154 }
2155 b.append(c.flattenToString());
2156 start = false;
2157 }
2158 secureSettings.insertSettingLocked(
2159 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2160 SettingsState.SYSTEM_PACKAGE_NAME);
2161 }
2162
2163 }
2164 currentVersion = 126;
2165 }
2166
Jeff Brown503cffc2015-03-26 18:08:51 -07002167 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002168
Jeff Brown503cffc2015-03-26 18:08:51 -07002169 // Return the current version.
2170 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002171 }
2172 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002173 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002174}