blob: 8dc247a010a2557c300b4da0e746ea6bf98343f7 [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) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001327 if (setting == null) {
1328 return;
1329 }
Svetoslav683914b2015-01-15 14:22:26 -08001330 final int columnCount = cursor.getColumnCount();
1331
1332 String[] values = new String[columnCount];
1333
1334 for (int i = 0; i < columnCount; i++) {
1335 String column = cursor.getColumnName(i);
1336
1337 switch (column) {
1338 case Settings.NameValueTable._ID: {
1339 values[i] = setting.getId();
1340 } break;
1341
1342 case Settings.NameValueTable.NAME: {
1343 values[i] = setting.getName();
1344 } break;
1345
1346 case Settings.NameValueTable.VALUE: {
1347 values[i] = setting.getValue();
1348 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001349 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001350 }
1351
Svetoslav683914b2015-01-15 14:22:26 -08001352 cursor.addRow(values);
1353 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001354
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001355 private static boolean isKeyValid(String key) {
1356 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1357 }
1358
Svetoslav683914b2015-01-15 14:22:26 -08001359 private static final class Arguments {
1360 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1361 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1362
1363 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1364 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1365
1366 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1367 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1368
1369 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1370 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1371
1372 public final String table;
1373 public final String name;
1374
1375 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1376 final int segmentSize = uri.getPathSegments().size();
1377 switch (segmentSize) {
1378 case 1: {
1379 if (where != null
1380 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1381 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1382 && whereArgs.length == 1) {
1383 name = whereArgs[0];
1384 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001385 return;
Svetoslav683914b2015-01-15 14:22:26 -08001386 } else if (where != null
1387 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1388 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1389 final int startIndex = Math.max(where.indexOf("'"),
1390 where.indexOf("\"")) + 1;
1391 final int endIndex = Math.max(where.lastIndexOf("'"),
1392 where.lastIndexOf("\""));
1393 name = where.substring(startIndex, endIndex);
1394 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001395 return;
Svetoslav683914b2015-01-15 14:22:26 -08001396 } else if (supportAll && where == null && whereArgs == null) {
1397 name = null;
1398 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001399 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001400 }
Svetoslav683914b2015-01-15 14:22:26 -08001401 } break;
1402
Svetoslav28494652015-02-12 14:11:42 -08001403 case 2: {
1404 if (where == null && whereArgs == null) {
1405 name = uri.getPathSegments().get(1);
1406 table = computeTableForSetting(uri, name);
1407 return;
1408 }
1409 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001410 }
Svetoslav28494652015-02-12 14:11:42 -08001411
1412 EventLogTags.writeUnsupportedSettingsQuery(
1413 uri.toSafeString(), where, Arrays.toString(whereArgs));
1414 String message = String.format( "Supported SQL:\n"
1415 + " uri content://some_table/some_property with null where and where args\n"
1416 + " uri content://some_table with query name=? and single name as arg\n"
1417 + " uri content://some_table with query name=some_name and null args\n"
1418 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1419 Arrays.toString(whereArgs));
1420 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001421 }
1422
Svetoslav28494652015-02-12 14:11:42 -08001423 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001424 String table = getValidTableOrThrow(uri);
1425
1426 if (name != null) {
1427 if (sSystemMovedToSecureSettings.contains(name)) {
1428 table = TABLE_SECURE;
1429 }
1430
1431 if (sSystemMovedToGlobalSettings.contains(name)) {
1432 table = TABLE_GLOBAL;
1433 }
1434
1435 if (sSecureMovedToGlobalSettings.contains(name)) {
1436 table = TABLE_GLOBAL;
1437 }
1438
1439 if (sGlobalMovedToSecureSettings.contains(name)) {
1440 table = TABLE_SECURE;
1441 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001442 }
Svetoslav683914b2015-01-15 14:22:26 -08001443
1444 return table;
1445 }
1446 }
1447
1448 final class SettingsRegistry {
1449 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1450
1451 private static final int SETTINGS_TYPE_GLOBAL = 0;
1452 private static final int SETTINGS_TYPE_SYSTEM = 1;
1453 private static final int SETTINGS_TYPE_SECURE = 2;
1454
1455 private static final int SETTINGS_TYPE_MASK = 0xF0000000;
1456 private static final int SETTINGS_TYPE_SHIFT = 28;
1457
1458 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1459 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1460 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1461
1462 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1463
1464 private final BackupManager mBackupManager;
1465
Svetoslav7e0683b2015-08-03 16:02:52 -07001466 private final Handler mHandler;
1467
Svetoslav683914b2015-01-15 14:22:26 -08001468 public SettingsRegistry() {
1469 mBackupManager = new BackupManager(getContext());
Svetoslav7e0683b2015-08-03 16:02:52 -07001470 mHandler = new MyHandler(getContext().getMainLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001471 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001472 }
1473
Svetoslav683914b2015-01-15 14:22:26 -08001474 public List<String> getSettingsNamesLocked(int type, int userId) {
1475 final int key = makeKey(type, userId);
1476 SettingsState settingsState = peekSettingsStateLocked(key);
1477 return settingsState.getSettingNamesLocked();
1478 }
1479
1480 public SettingsState getSettingsLocked(int type, int userId) {
1481 final int key = makeKey(type, userId);
1482 return peekSettingsStateLocked(key);
1483 }
1484
1485 public void ensureSettingsForUserLocked(int userId) {
1486 // Migrate the setting for this user if needed.
1487 migrateLegacySettingsForUserIfNeededLocked(userId);
1488
1489 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001490 if (userId == UserHandle.USER_SYSTEM) {
1491 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001492 ensureSettingsStateLocked(globalKey);
1493 }
1494
1495 // Ensure secure settings loaded.
1496 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1497 ensureSettingsStateLocked(secureKey);
1498
1499 // Make sure the secure settings have an Android id set.
1500 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1501 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1502
1503 // Ensure system settings loaded.
1504 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1505 ensureSettingsStateLocked(systemKey);
1506
1507 // Upgrade the settings to the latest version.
1508 UpgradeController upgrader = new UpgradeController(userId);
1509 upgrader.upgradeIfNeededLocked();
1510 }
1511
1512 private void ensureSettingsStateLocked(int key) {
1513 if (mSettingsStates.get(key) == null) {
1514 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1515 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1516 maxBytesPerPackage);
1517 mSettingsStates.put(key, settingsState);
1518 }
1519 }
1520
1521 public void removeUserStateLocked(int userId, boolean permanently) {
1522 // We always keep the global settings in memory.
1523
1524 // Nuke system settings.
1525 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1526 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1527 if (systemSettingsState != null) {
1528 if (permanently) {
1529 mSettingsStates.remove(systemKey);
1530 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001531 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001532 systemSettingsState.destroyLocked(new Runnable() {
1533 @Override
1534 public void run() {
1535 mSettingsStates.remove(systemKey);
1536 }
1537 });
1538 }
1539 }
1540
1541 // Nuke secure settings.
1542 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1543 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1544 if (secureSettingsState != null) {
1545 if (permanently) {
1546 mSettingsStates.remove(secureKey);
1547 secureSettingsState.destroyLocked(null);
1548 } else {
1549 secureSettingsState.destroyLocked(new Runnable() {
1550 @Override
1551 public void run() {
1552 mSettingsStates.remove(secureKey);
1553 }
1554 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001555 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001556 }
1557 }
1558
Svetoslav683914b2015-01-15 14:22:26 -08001559 public boolean insertSettingLocked(int type, int userId, String name, String value,
1560 String packageName) {
1561 final int key = makeKey(type, userId);
1562
1563 SettingsState settingsState = peekSettingsStateLocked(key);
1564 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1565
1566 if (success) {
1567 notifyForSettingsChange(key, name);
1568 }
1569 return success;
1570 }
1571
1572 public boolean deleteSettingLocked(int type, int userId, String name) {
1573 final int key = makeKey(type, userId);
1574
1575 SettingsState settingsState = peekSettingsStateLocked(key);
1576 final boolean success = settingsState.deleteSettingLocked(name);
1577
1578 if (success) {
1579 notifyForSettingsChange(key, name);
1580 }
1581 return success;
1582 }
1583
1584 public Setting getSettingLocked(int type, int userId, String name) {
1585 final int key = makeKey(type, userId);
1586
1587 SettingsState settingsState = peekSettingsStateLocked(key);
1588 return settingsState.getSettingLocked(name);
1589 }
1590
1591 public boolean updateSettingLocked(int type, int userId, String name, String value,
1592 String packageName) {
1593 final int key = makeKey(type, userId);
1594
1595 SettingsState settingsState = peekSettingsStateLocked(key);
1596 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1597
1598 if (success) {
1599 notifyForSettingsChange(key, name);
1600 }
1601
1602 return success;
1603 }
1604
1605 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001606 // Global and secure settings are signature protected. Apps signed
1607 // by the platform certificate are generally not uninstalled and
1608 // the main exception is tests. We trust components signed
1609 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001610
1611 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1612 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001613 if (systemSettings != null) {
1614 systemSettings.onPackageRemovedLocked(packageName);
1615 }
Svetoslav683914b2015-01-15 14:22:26 -08001616 }
1617
1618 private SettingsState peekSettingsStateLocked(int key) {
1619 SettingsState settingsState = mSettingsStates.get(key);
1620 if (settingsState != null) {
1621 return settingsState;
1622 }
1623
1624 ensureSettingsForUserLocked(getUserIdFromKey(key));
1625 return mSettingsStates.get(key);
1626 }
1627
1628 private void migrateAllLegacySettingsIfNeeded() {
1629 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001630 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001631 File globalFile = getSettingsFile(key);
1632 if (globalFile.exists()) {
1633 return;
1634 }
1635
1636 final long identity = Binder.clearCallingIdentity();
1637 try {
1638 List<UserInfo> users = mUserManager.getUsers(true);
1639
1640 final int userCount = users.size();
1641 for (int i = 0; i < userCount; i++) {
1642 final int userId = users.get(i).id;
1643
1644 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1645 SQLiteDatabase database = dbHelper.getWritableDatabase();
1646 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1647
1648 // Upgrade to the latest version.
1649 UpgradeController upgrader = new UpgradeController(userId);
1650 upgrader.upgradeIfNeededLocked();
1651
1652 // Drop from memory if not a running user.
1653 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1654 removeUserStateLocked(userId, false);
1655 }
1656 }
1657 } finally {
1658 Binder.restoreCallingIdentity(identity);
1659 }
1660 }
1661 }
1662
1663 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1664 // Every user has secure settings and if no file we need to migrate.
1665 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1666 File secureFile = getSettingsFile(secureKey);
1667 if (secureFile.exists()) {
1668 return;
1669 }
1670
1671 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1672 SQLiteDatabase database = dbHelper.getWritableDatabase();
1673
1674 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1675 }
1676
1677 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1678 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001679 // Move over the system settings.
1680 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1681 ensureSettingsStateLocked(systemKey);
1682 SettingsState systemSettings = mSettingsStates.get(systemKey);
1683 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1684 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001685
1686 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001687 // Do this after System settings, since this is the first thing we check when deciding
1688 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001689 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1690 ensureSettingsStateLocked(secureKey);
1691 SettingsState secureSettings = mSettingsStates.get(secureKey);
1692 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1693 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1694 secureSettings.persistSyncLocked();
1695
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001696 // Move over the global settings if owner.
1697 // Do this last, since this is the first thing we check when deciding
1698 // to skip over migration from db to xml for owner user.
1699 if (userId == UserHandle.USER_SYSTEM) {
1700 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1701 ensureSettingsStateLocked(globalKey);
1702 SettingsState globalSettings = mSettingsStates.get(globalKey);
1703 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1704 globalSettings.persistSyncLocked();
1705 }
Svetoslav683914b2015-01-15 14:22:26 -08001706
1707 // Drop the database as now all is moved and persisted.
1708 if (DROP_DATABASE_ON_MIGRATION) {
1709 dbHelper.dropDatabase();
1710 } else {
1711 dbHelper.backupDatabase();
1712 }
1713 }
1714
1715 private void migrateLegacySettingsLocked(SettingsState settingsState,
1716 SQLiteDatabase database, String table) {
1717 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1718 queryBuilder.setTables(table);
1719
1720 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1721 null, null, null, null, null);
1722
1723 if (cursor == null) {
1724 return;
1725 }
1726
1727 try {
1728 if (!cursor.moveToFirst()) {
1729 return;
1730 }
1731
1732 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1733 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1734
1735 settingsState.setVersionLocked(database.getVersion());
1736
1737 while (!cursor.isAfterLast()) {
1738 String name = cursor.getString(nameColumnIdx);
1739 String value = cursor.getString(valueColumnIdx);
1740 settingsState.insertSettingLocked(name, value,
1741 SettingsState.SYSTEM_PACKAGE_NAME);
1742 cursor.moveToNext();
1743 }
1744 } finally {
1745 cursor.close();
1746 }
1747 }
1748
1749 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1750 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1751
1752 if (value != null) {
1753 return;
1754 }
1755
1756 final int userId = getUserIdFromKey(secureSettings.mKey);
1757
1758 final UserInfo user;
1759 final long identity = Binder.clearCallingIdentity();
1760 try {
1761 user = mUserManager.getUserInfo(userId);
1762 } finally {
1763 Binder.restoreCallingIdentity(identity);
1764 }
1765 if (user == null) {
1766 // Can happen due to races when deleting users - treat as benign.
1767 return;
1768 }
1769
1770 String androidId = Long.toHexString(new SecureRandom().nextLong());
1771 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1772 SettingsState.SYSTEM_PACKAGE_NAME);
1773
1774 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1775 + "] for user " + userId);
1776
1777 // Write a drop box entry if it's a restricted profile
1778 if (user.isRestricted()) {
1779 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1780 Context.DROPBOX_SERVICE);
1781 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1782 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1783 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1784 }
1785 }
1786 }
1787
1788 private void notifyForSettingsChange(int key, String name) {
1789 // Update the system property *first*, so if someone is listening for
1790 // a notification and then using the contract class to get their data,
1791 // the system property will be updated and they'll get the new data.
1792
1793 boolean backedUpDataChanged = false;
1794 String property = null;
1795 if (isGlobalSettingsKey(key)) {
1796 property = Settings.Global.SYS_PROP_SETTING_VERSION;
1797 backedUpDataChanged = true;
1798 } else if (isSecureSettingsKey(key)) {
1799 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
1800 backedUpDataChanged = true;
1801 } else if (isSystemSettingsKey(key)) {
1802 property = Settings.System.SYS_PROP_SETTING_VERSION;
1803 backedUpDataChanged = true;
1804 }
1805
1806 if (property != null) {
1807 final long version = SystemProperties.getLong(property, 0) + 1;
1808 SystemProperties.set(property, Long.toString(version));
1809 if (DEBUG) {
1810 Slog.v(LOG_TAG, "System property " + property + "=" + version);
1811 }
1812 }
1813
1814 // Inform the backup manager about a data change
1815 if (backedUpDataChanged) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001816 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Svetoslav683914b2015-01-15 14:22:26 -08001817 }
1818
1819 // Now send the notification through the content framework.
1820
1821 final int userId = getUserIdFromKey(key);
1822 Uri uri = getNotificationUriFor(key, name);
1823
Svetoslav7e0683b2015-08-03 16:02:52 -07001824 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1825 userId, 0, uri).sendToTarget();
1826
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001827 if (isSecureSettingsKey(key)) {
1828 maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
1829 } else if (isSystemSettingsKey(key)) {
1830 maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
1831 }
1832 }
1833
1834 private void maybeNotifyProfiles(int userId, Uri uri, String name,
1835 Set<String> keysCloned) {
1836 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001837 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001838 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001839 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001840 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001841 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001842 }
1843 }
1844 }
Svetoslav683914b2015-01-15 14:22:26 -08001845 }
1846
1847 private int makeKey(int type, int userId) {
1848 return (type << SETTINGS_TYPE_SHIFT) | userId;
1849 }
1850
1851 private int getTypeFromKey(int key) {
1852 return key >> SETTINGS_TYPE_SHIFT;
1853 }
1854
1855 private int getUserIdFromKey(int key) {
1856 return key & ~SETTINGS_TYPE_MASK;
1857 }
1858
1859 private boolean isGlobalSettingsKey(int key) {
1860 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1861 }
1862
1863 private boolean isSystemSettingsKey(int key) {
1864 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1865 }
1866
1867 private boolean isSecureSettingsKey(int key) {
1868 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1869 }
1870
1871 private File getSettingsFile(int key) {
1872 if (isGlobalSettingsKey(key)) {
1873 final int userId = getUserIdFromKey(key);
1874 return new File(Environment.getUserSystemDirectory(userId),
1875 SETTINGS_FILE_GLOBAL);
1876 } else if (isSystemSettingsKey(key)) {
1877 final int userId = getUserIdFromKey(key);
1878 return new File(Environment.getUserSystemDirectory(userId),
1879 SETTINGS_FILE_SYSTEM);
1880 } else if (isSecureSettingsKey(key)) {
1881 final int userId = getUserIdFromKey(key);
1882 return new File(Environment.getUserSystemDirectory(userId),
1883 SETTINGS_FILE_SECURE);
1884 } else {
1885 throw new IllegalArgumentException("Invalid settings key:" + key);
1886 }
1887 }
1888
1889 private Uri getNotificationUriFor(int key, String name) {
1890 if (isGlobalSettingsKey(key)) {
1891 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
1892 : Settings.Global.CONTENT_URI;
1893 } else if (isSecureSettingsKey(key)) {
1894 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
1895 : Settings.Secure.CONTENT_URI;
1896 } else if (isSystemSettingsKey(key)) {
1897 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
1898 : Settings.System.CONTENT_URI;
1899 } else {
1900 throw new IllegalArgumentException("Invalid settings key:" + key);
1901 }
1902 }
1903
1904 private int getMaxBytesPerPackageForType(int type) {
1905 switch (type) {
1906 case SETTINGS_TYPE_GLOBAL:
1907 case SETTINGS_TYPE_SECURE: {
1908 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
1909 }
1910
1911 default: {
1912 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
1913 }
1914 }
1915 }
1916
Svetoslav7e0683b2015-08-03 16:02:52 -07001917 private final class MyHandler extends Handler {
1918 private static final int MSG_NOTIFY_URI_CHANGED = 1;
1919 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
1920
1921 public MyHandler(Looper looper) {
1922 super(looper);
1923 }
1924
1925 @Override
1926 public void handleMessage(Message msg) {
1927 switch (msg.what) {
1928 case MSG_NOTIFY_URI_CHANGED: {
1929 final int userId = msg.arg1;
1930 Uri uri = (Uri) msg.obj;
1931 getContext().getContentResolver().notifyChange(uri, null, true, userId);
1932 if (DEBUG) {
1933 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
1934 }
1935 } break;
1936
1937 case MSG_NOTIFY_DATA_CHANGED: {
1938 mBackupManager.dataChanged();
1939 } break;
1940 }
1941 }
1942 }
1943
Svetoslav683914b2015-01-15 14:22:26 -08001944 private final class UpgradeController {
Daniel U02ba6122016-04-01 18:41:42 +01001945 private static final int SETTINGS_VERSION = 127;
Svetoslav683914b2015-01-15 14:22:26 -08001946
1947 private final int mUserId;
1948
1949 public UpgradeController(int userId) {
1950 mUserId = userId;
1951 }
1952
1953 public void upgradeIfNeededLocked() {
1954 // The version of all settings for a user is the same (all users have secure).
1955 SettingsState secureSettings = getSettingsLocked(
1956 SettingsRegistry.SETTINGS_TYPE_SECURE, mUserId);
1957
1958 // Try an update from the current state.
1959 final int oldVersion = secureSettings.getVersionLocked();
1960 final int newVersion = SETTINGS_VERSION;
1961
Svet Ganovc9755bc2015-03-28 13:21:22 -07001962 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08001963 if (oldVersion == newVersion) {
1964 return;
1965 }
1966
1967 // Try to upgrade.
1968 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
1969
1970 // If upgrade failed start from scratch and upgrade.
1971 if (curVersion != newVersion) {
1972 // Drop state we have for this user.
1973 removeUserStateLocked(mUserId, true);
1974
1975 // Recreate the database.
1976 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
1977 SQLiteDatabase database = dbHelper.getWritableDatabase();
1978 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
1979
1980 // Migrate the settings for this user.
1981 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
1982
1983 // Now upgrade should work fine.
1984 onUpgradeLocked(mUserId, oldVersion, newVersion);
1985 }
1986
1987 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001988 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001989 SettingsState globalSettings = getSettingsLocked(
1990 SettingsRegistry.SETTINGS_TYPE_GLOBAL, mUserId);
1991 globalSettings.setVersionLocked(newVersion);
1992 }
1993
1994 // Set the secure settings version.
1995 secureSettings.setVersionLocked(newVersion);
1996
1997 // Set the system settings version.
1998 SettingsState systemSettings = getSettingsLocked(
1999 SettingsRegistry.SETTINGS_TYPE_SYSTEM, mUserId);
2000 systemSettings.setVersionLocked(newVersion);
2001 }
2002
2003 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002004 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002005 }
2006
2007 private SettingsState getSecureSettingsLocked(int userId) {
2008 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2009 }
2010
2011 private SettingsState getSystemSettingsLocked(int userId) {
2012 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2013 }
2014
Jeff Brown503cffc2015-03-26 18:08:51 -07002015 /**
2016 * You must perform all necessary mutations to bring the settings
2017 * for this user from the old to the new version. When you add a new
2018 * upgrade step you *must* update SETTINGS_VERSION.
2019 *
2020 * This is an example of moving a setting from secure to global.
2021 *
2022 * // v119: Example settings changes.
2023 * if (currentVersion == 118) {
2024 * if (userId == UserHandle.USER_OWNER) {
2025 * // Remove from the secure settings.
2026 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2027 * String name = "example_setting_to_move";
2028 * String value = secureSettings.getSetting(name);
2029 * secureSettings.deleteSetting(name);
2030 *
2031 * // Add to the global settings.
2032 * SettingsState globalSettings = getGlobalSettingsLocked();
2033 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2034 * }
2035 *
2036 * // Update the current version.
2037 * currentVersion = 119;
2038 * }
2039 */
Svetoslav683914b2015-01-15 14:22:26 -08002040 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2041 if (DEBUG) {
2042 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2043 + oldVersion + " to version: " + newVersion);
2044 }
2045
Jeff Brown503cffc2015-03-26 18:08:51 -07002046 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002047
John Spurlocke11ae112015-05-11 16:09:03 -04002048 // v119: Reset zen + ringer mode.
2049 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002050 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002051 final SettingsState globalSettings = getGlobalSettingsLocked();
2052 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2053 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2054 SettingsState.SYSTEM_PACKAGE_NAME);
2055 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2056 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2057 SettingsState.SYSTEM_PACKAGE_NAME);
2058 }
2059 currentVersion = 119;
2060 }
2061
Jason Monk27bbb2d2015-03-31 16:46:39 -04002062 // v120: Add double tap to wake setting.
2063 if (currentVersion == 119) {
2064 SettingsState secureSettings = getSecureSettingsLocked(userId);
2065 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2066 getContext().getResources().getBoolean(
2067 R.bool.def_double_tap_to_wake) ? "1" : "0",
2068 SettingsState.SYSTEM_PACKAGE_NAME);
2069
2070 currentVersion = 120;
2071 }
2072
Svetoslav7e0683b2015-08-03 16:02:52 -07002073 if (currentVersion == 120) {
2074 // Before 121, we used a different string encoding logic. We just bump the
2075 // version here; SettingsState knows how to handle pre-version 120 files.
2076 currentVersion = 121;
2077 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002078
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002079 if (currentVersion == 121) {
2080 // Version 122: allow OEMs to set a default payment component in resources.
2081 // Note that we only write the default if no default has been set;
2082 // if there is, we just leave the default at whatever it currently is.
2083 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2084 String defaultComponent = (getContext().getResources().getString(
2085 R.string.def_nfc_payment_component));
2086 Setting currentSetting = secureSettings.getSettingLocked(
2087 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2088 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2089 currentSetting == null) {
2090 secureSettings.insertSettingLocked(
2091 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2092 defaultComponent,
2093 SettingsState.SYSTEM_PACKAGE_NAME);
2094 }
2095 currentVersion = 122;
2096 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002097
2098 if (currentVersion == 122) {
2099 // Version 123: Adding a default value for the ability to add a user from
2100 // the lock screen.
2101 if (userId == UserHandle.USER_SYSTEM) {
2102 final SettingsState globalSettings = getGlobalSettingsLocked();
2103 Setting currentSetting = globalSettings.getSettingLocked(
2104 Settings.Global.ADD_USERS_WHEN_LOCKED);
2105 if (currentSetting == null) {
2106 globalSettings.insertSettingLocked(
2107 Settings.Global.ADD_USERS_WHEN_LOCKED,
2108 getContext().getResources().getBoolean(
2109 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2110 SettingsState.SYSTEM_PACKAGE_NAME);
2111 }
2112 }
2113 currentVersion = 123;
2114 }
Bryce Leebd179282015-12-17 19:01:37 -08002115
2116 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002117 final SettingsState globalSettings = getGlobalSettingsLocked();
2118 String defaultDisabledProfiles = (getContext().getResources().getString(
2119 R.string.def_bluetooth_disabled_profiles));
2120 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2121 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002122 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002123 }
2124
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002125 if (currentVersion == 124) {
2126 // Version 124: allow OEMs to set a default value for whether IME should be
2127 // shown when a physical keyboard is connected.
2128 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2129 Setting currentSetting = secureSettings.getSettingLocked(
2130 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
2131 if (currentSetting == null) {
2132 secureSettings.insertSettingLocked(
2133 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2134 getContext().getResources().getBoolean(
2135 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2136 SettingsState.SYSTEM_PACKAGE_NAME);
2137 }
2138 currentVersion = 125;
2139 }
2140
Ruben Brunk98576cf2016-03-07 18:54:28 -08002141 if (currentVersion == 125) {
2142 // Version 125: Allow OEMs to set the default VR service.
2143 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2144
2145 Setting currentSetting = secureSettings.getSettingLocked(
2146 Settings.Secure.ENABLED_VR_LISTENERS);
2147 if (currentSetting == null) {
2148 ArraySet<ComponentName> l =
2149 SystemConfig.getInstance().getDefaultVrComponents();
2150
2151 if (l != null && !l.isEmpty()) {
2152 StringBuilder b = new StringBuilder();
2153 boolean start = true;
2154 for (ComponentName c : l) {
2155 if (!start) {
2156 b.append(':');
2157 }
2158 b.append(c.flattenToString());
2159 start = false;
2160 }
2161 secureSettings.insertSettingLocked(
2162 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2163 SettingsState.SYSTEM_PACKAGE_NAME);
2164 }
2165
2166 }
2167 currentVersion = 126;
2168 }
2169
Daniel U02ba6122016-04-01 18:41:42 +01002170 if (currentVersion == 126) {
2171 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2172 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2173 if (mUserManager.isManagedProfile(userId)) {
2174 final SettingsState systemSecureSettings =
2175 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2176
2177 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2178 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
2179 if (showNotifications != null) {
2180 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2181 secureSettings.insertSettingLocked(
2182 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2183 showNotifications.getValue(),
2184 SettingsState.SYSTEM_PACKAGE_NAME);
2185 }
2186
2187 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2188 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
2189 if (allowPrivate != null) {
2190 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2191 secureSettings.insertSettingLocked(
2192 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2193 allowPrivate.getValue(),
2194 SettingsState.SYSTEM_PACKAGE_NAME);
2195 }
2196 }
2197 currentVersion = 127;
2198 }
2199
Jeff Brown503cffc2015-03-26 18:08:51 -07002200 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002201
Jeff Brown503cffc2015-03-26 18:08:51 -07002202 // Return the current version.
2203 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002204 }
2205 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002206 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002207}