blob: 3084b9bae5a115b35b3ff1790d5e5a708a7ce7c3 [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;
Svet Ganov53a441c2016-04-19 19:38:00 -070045import android.os.Debug;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070046import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080047import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070048import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070049import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Looper;
51import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070053import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070054import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070055import android.os.SELinux;
Christopher Tate06efb532012-08-24 15:29:27 -070056import android.os.UserHandle;
57import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070058import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059import android.provider.Settings;
60import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010061import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080062import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.util.Slog;
64import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040065
Svetoslav683914b2015-01-15 14:22:26 -080066import com.android.internal.annotations.GuardedBy;
67import com.android.internal.content.PackageMonitor;
68import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080069import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070070import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080071import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040072
Svetoslav683914b2015-01-15 14:22:26 -080073import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080074import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080075import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080076import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080077import java.security.SecureRandom;
78import java.util.Arrays;
79import java.util.List;
Andre Lago3fa139c2016-08-04 13:53:44 +010080import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080081import java.util.Set;
82import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070083
Svetoslav683914b2015-01-15 14:22:26 -080084/**
85 * <p>
86 * This class is a content provider that publishes the system settings.
87 * It can be accessed via the content provider APIs or via custom call
88 * commands. The latter is a bit faster and is the preferred way to access
89 * the platform settings.
90 * </p>
91 * <p>
92 * There are three settings types, global (with signature level protection
93 * and shared across users), secure (with signature permission level
94 * protection and per user), and system (with dangerous permission level
95 * protection and per user). Global settings are stored under the device owner.
96 * Each of these settings is represented by a {@link
97 * com.android.providers.settings.SettingsState} object mapped to an integer
98 * key derived from the setting type in the most significant bits and user
99 * id in the least significant bits. Settings are synchronously loaded on
100 * instantiation of a SettingsState and asynchronously persisted on mutation.
101 * Settings are stored in the user specific system directory.
102 * </p>
103 * <p>
104 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
105 * and get a warning. Targeting higher API version prohibits this as the
106 * system settings are not a place for apps to save their state. When a package
107 * is removed the settings it added are deleted. Apps cannot delete system
108 * settings added by the platform. System settings values are validated to
109 * ensure the clients do not put bad values. Global and secure settings are
110 * changed only by trusted parties, therefore no validation is performed. Also
111 * there is a limit on the amount of app specific settings that can be added
112 * to prevent unlimited growth of the system process memory footprint.
113 * </p>
114 */
115@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800117 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700118
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700119 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800120
121 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700122
Christopher Tate06efb532012-08-24 15:29:27 -0700123 private static final String TABLE_SYSTEM = "system";
124 private static final String TABLE_SECURE = "secure";
125 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800126
127 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final String TABLE_FAVORITES = "favorites";
129 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800130 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
131 private static final String TABLE_BOOKMARKS = "bookmarks";
132 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
Svetoslav683914b2015-01-15 14:22:26 -0800134 // The set of removed legacy tables.
135 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700136 static {
Svetoslav683914b2015-01-15 14:22:26 -0800137 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
138 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
139 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
140 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
141 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
142 }
Christopher Tate06efb532012-08-24 15:29:27 -0700143
Svetoslav683914b2015-01-15 14:22:26 -0800144 private static final int MUTATION_OPERATION_INSERT = 1;
145 private static final int MUTATION_OPERATION_DELETE = 2;
146 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400147
Svetoslav683914b2015-01-15 14:22:26 -0800148 private static final String[] ALL_COLUMNS = new String[] {
149 Settings.NameValueTable._ID,
150 Settings.NameValueTable.NAME,
151 Settings.NameValueTable.VALUE
152 };
153
Svet Ganov53a441c2016-04-19 19:38:00 -0700154 public static final int SETTINGS_TYPE_GLOBAL = 0;
155 public static final int SETTINGS_TYPE_SYSTEM = 1;
156 public static final int SETTINGS_TYPE_SECURE = 2;
Svetoslav683914b2015-01-15 14:22:26 -0800157
Svet Ganov53a441c2016-04-19 19:38:00 -0700158 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
159 public static final int SETTINGS_TYPE_SHIFT = 28;
160
161 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
162 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700163
Svetoslav683914b2015-01-15 14:22:26 -0800164 // Per user secure settings that moved to the for all users global settings.
165 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
166 static {
167 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700168 }
169
Svetoslav683914b2015-01-15 14:22:26 -0800170 // Per user system settings that moved to the for all users global settings.
171 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
172 static {
173 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700174 }
175
Svetoslav683914b2015-01-15 14:22:26 -0800176 // Per user system settings that moved to the per user secure settings.
177 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
178 static {
179 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700180 }
181
Svetoslav683914b2015-01-15 14:22:26 -0800182 // Per all users global settings that moved to the per user secure settings.
183 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
184 static {
185 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700186 }
187
Svetoslav683914b2015-01-15 14:22:26 -0800188 // Per user secure settings that are cloned for the managed profiles of the user.
189 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
190 static {
191 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700192 }
193
Svetoslav683914b2015-01-15 14:22:26 -0800194 // Per user system settings that are cloned for the managed profiles of the user.
195 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
196 static {
197 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400198 }
199
Andre Lago3fa139c2016-08-04 13:53:44 +0100200 // Per user system settings that are cloned from the profile's parent when a dependency
201 // in {@link Settings.Secure} is set to "1".
202 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
203 static {
204 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
205 }
206
Svetoslav683914b2015-01-15 14:22:26 -0800207 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700208
Svetoslav683914b2015-01-15 14:22:26 -0800209 @GuardedBy("mLock")
210 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700211
Svet Ganova8f90262016-05-10 08:44:48 -0700212 @GuardedBy("mLock")
213 private HandlerThread mHandlerThread;
214
Svetoslav7ec28e82015-05-20 17:01:10 -0700215 // We have to call in the user manager with no lock held,
216 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800217
Svetoslav7ec28e82015-05-20 17:01:10 -0700218 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700219 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700220
Svet Ganov53a441c2016-04-19 19:38:00 -0700221 public static int makeKey(int type, int userId) {
222 return (type << SETTINGS_TYPE_SHIFT) | userId;
223 }
224
225 public static int getTypeFromKey(int key) {
226 return key >>> SETTINGS_TYPE_SHIFT;
227 }
228
229 public static int getUserIdFromKey(int key) {
230 return key & ~SETTINGS_TYPE_MASK;
231 }
232
233 public static String settingTypeToString(int type) {
234 switch (type) {
235 case SETTINGS_TYPE_GLOBAL: {
236 return "SETTINGS_GLOBAL";
237 }
238 case SETTINGS_TYPE_SECURE: {
239 return "SETTINGS_SECURE";
240 }
241 case SETTINGS_TYPE_SYSTEM: {
242 return "SETTINGS_SYSTEM";
243 }
244 default: {
245 return "UNKNOWN";
246 }
247 }
248 }
249
250 public static String keyToString(int key) {
251 return "Key[user=" + getUserIdFromKey(key) + ";type="
252 + settingTypeToString(getTypeFromKey(key)) + "]";
253 }
254
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255 @Override
256 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800257 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700258 mUserManager = UserManager.get(getContext());
259 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700260 mHandlerThread = new HandlerThread(LOG_TAG,
261 Process.THREAD_PRIORITY_BACKGROUND);
262 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800263 mSettingsRegistry = new SettingsRegistry();
264 }
265 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700266 startWatchingUserRestrictionChanges();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 return true;
268 }
269
Svetoslav683914b2015-01-15 14:22:26 -0800270 @Override
271 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700272 final int requestingUserId = getRequestingUserId(args);
273 switch (method) {
274 case Settings.CALL_METHOD_GET_GLOBAL: {
275 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700276 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800277 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700278
279 case Settings.CALL_METHOD_GET_SECURE: {
280 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700282 }
283
284 case Settings.CALL_METHOD_GET_SYSTEM: {
285 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700286 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700287 }
288
289 case Settings.CALL_METHOD_PUT_GLOBAL: {
290 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 insertGlobalSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700292 break;
293 }
294
295 case Settings.CALL_METHOD_PUT_SECURE: {
296 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700297 insertSecureSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700298 break;
299 }
300
301 case Settings.CALL_METHOD_PUT_SYSTEM: {
302 String value = getSettingValue(args);
303 insertSystemSetting(name, value, requestingUserId);
304 break;
305 }
306
307 default: {
308 Slog.w(LOG_TAG, "call() with invalid method: " + method);
309 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700310 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700311
Christopher Tate06efb532012-08-24 15:29:27 -0700312 return null;
313 }
314
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800315 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800316 public String getType(Uri uri) {
317 Arguments args = new Arguments(uri, null, null, true);
318 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 return "vnd.android.cursor.dir/" + args.table;
320 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700321 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700322 }
323 }
324
325 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800326 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
327 String order) {
328 if (DEBUG) {
329 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330 }
331
Svetoslav683914b2015-01-15 14:22:26 -0800332 Arguments args = new Arguments(uri, where, whereArgs, true);
333 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700334
Svetoslav683914b2015-01-15 14:22:26 -0800335 // If a legacy table that is gone, done.
336 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
337 return new MatrixCursor(normalizedProjection, 0);
338 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700339
Svetoslav7ec28e82015-05-20 17:01:10 -0700340 switch (args.table) {
341 case TABLE_GLOBAL: {
342 if (args.name != null) {
343 Setting setting = getGlobalSetting(args.name);
344 return packageSettingForQuery(setting, normalizedProjection);
345 } else {
346 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700347 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700348 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700349
Svetoslav7ec28e82015-05-20 17:01:10 -0700350 case TABLE_SECURE: {
351 final int userId = UserHandle.getCallingUserId();
352 if (args.name != null) {
353 Setting setting = getSecureSetting(args.name, userId);
354 return packageSettingForQuery(setting, normalizedProjection);
355 } else {
356 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800357 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700358 }
Svetoslav683914b2015-01-15 14:22:26 -0800359
Svetoslav7ec28e82015-05-20 17:01:10 -0700360 case TABLE_SYSTEM: {
361 final int userId = UserHandle.getCallingUserId();
362 if (args.name != null) {
363 Setting setting = getSystemSetting(args.name, userId);
364 return packageSettingForQuery(setting, normalizedProjection);
365 } else {
366 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800367 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700368 }
Svetoslav683914b2015-01-15 14:22:26 -0800369
Svetoslav7ec28e82015-05-20 17:01:10 -0700370 default: {
371 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700372 }
373 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700374 }
375
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800377 public Uri insert(Uri uri, ContentValues values) {
378 if (DEBUG) {
379 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700380 }
381
Svetoslav683914b2015-01-15 14:22:26 -0800382 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700383
Svetoslav683914b2015-01-15 14:22:26 -0800384 // If a legacy table that is gone, done.
385 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 return null;
387 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700388
Svetoslav683914b2015-01-15 14:22:26 -0800389 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700390 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800391 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700392 }
393
Svetoslav683914b2015-01-15 14:22:26 -0800394 String value = values.getAsString(Settings.Secure.VALUE);
395
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 switch (table) {
397 case TABLE_GLOBAL: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700398 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700399 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700400 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700401 } break;
402
403 case TABLE_SECURE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700404 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
406 }
407 } break;
408
409 case TABLE_SYSTEM: {
410 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
411 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
412 }
413 } break;
414
415 default: {
416 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700417 }
418 }
419
Svetoslav683914b2015-01-15 14:22:26 -0800420 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700421 }
422
423 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800424 public int bulkInsert(Uri uri, ContentValues[] allValues) {
425 if (DEBUG) {
426 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700428
Svetoslav683914b2015-01-15 14:22:26 -0800429 int insertionCount = 0;
430 final int valuesCount = allValues.length;
431 for (int i = 0; i < valuesCount; i++) {
432 ContentValues values = allValues[i];
433 if (insert(uri, values) != null) {
434 insertionCount++;
435 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700436 }
Svetoslav683914b2015-01-15 14:22:26 -0800437
438 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700439 }
440
441 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800442 public int delete(Uri uri, String where, String[] whereArgs) {
443 if (DEBUG) {
444 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700446
Svetoslav683914b2015-01-15 14:22:26 -0800447 Arguments args = new Arguments(uri, where, whereArgs, false);
448
449 // If a legacy table that is gone, done.
450 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
451 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700452 }
Svetoslav683914b2015-01-15 14:22:26 -0800453
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700454 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800455 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700456 }
Svetoslav683914b2015-01-15 14:22:26 -0800457
Svetoslav7ec28e82015-05-20 17:01:10 -0700458 switch (args.table) {
459 case TABLE_GLOBAL: {
460 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700461 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700462 }
Svetoslav683914b2015-01-15 14:22:26 -0800463
Svetoslav7ec28e82015-05-20 17:01:10 -0700464 case TABLE_SECURE: {
465 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700466 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700467 }
Svetoslav683914b2015-01-15 14:22:26 -0800468
Svetoslav7ec28e82015-05-20 17:01:10 -0700469 case TABLE_SYSTEM: {
470 final int userId = UserHandle.getCallingUserId();
471 return deleteSystemSetting(args.name, userId) ? 1 : 0;
472 }
473
474 default: {
475 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800476 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700477 }
Svetoslav683914b2015-01-15 14:22:26 -0800478 }
479
480 @Override
481 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
482 if (DEBUG) {
483 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700484 }
Svetoslav683914b2015-01-15 14:22:26 -0800485
486 Arguments args = new Arguments(uri, where, whereArgs, false);
487
488 // If a legacy table that is gone, done.
489 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
490 return 0;
491 }
492
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700493 String name = values.getAsString(Settings.Secure.NAME);
494 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800495 return 0;
496 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700497 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800498
Svetoslav7ec28e82015-05-20 17:01:10 -0700499 switch (args.table) {
500 case TABLE_GLOBAL: {
501 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700502 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700503 }
Svetoslav683914b2015-01-15 14:22:26 -0800504
Svetoslav7ec28e82015-05-20 17:01:10 -0700505 case TABLE_SECURE: {
506 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700507 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700508 }
Svetoslav683914b2015-01-15 14:22:26 -0800509
Svetoslav7ec28e82015-05-20 17:01:10 -0700510 case TABLE_SYSTEM: {
511 final int userId = UserHandle.getCallingUserId();
512 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
513 }
Svetoslav683914b2015-01-15 14:22:26 -0800514
Svetoslav7ec28e82015-05-20 17:01:10 -0700515 default: {
516 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800517 }
518 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700519 }
520
521 @Override
522 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100523 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
524 if (userId != UserHandle.getCallingUserId()) {
525 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
526 "Access files from the settings of another user");
527 }
528 uri = ContentProvider.getUriWithoutUserId(uri);
529
Andre Lago3fa139c2016-08-04 13:53:44 +0100530 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700531 final String cacheName;
532 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100533 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700534 cacheName = Settings.System.RINGTONE_CACHE;
535 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100536 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700537 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
538 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100539 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700540 cacheName = Settings.System.ALARM_ALERT_CACHE;
541 } else {
542 throw new FileNotFoundException("Direct file access no longer supported; "
543 + "ringtone playback is available through android.media.Ringtone");
544 }
545
Andre Lago3fa139c2016-08-04 13:53:44 +0100546 int actualCacheOwner;
547 // Redirect cache to parent if ringtone setting is owned by profile parent
548 synchronized (mLock) {
549 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
550 cacheRingtoneSetting);
551 }
552 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700553 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
554 }
555
556 private File getRingtoneCacheDir(int userId) {
557 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
558 cacheDir.mkdir();
559 SELinux.restorecon(cacheDir);
560 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700561 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800562
Svetoslavb505ccc2015-02-17 12:41:04 -0800563 @Override
564 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
565 synchronized (mLock) {
566 final long identity = Binder.clearCallingIdentity();
567 try {
568 List<UserInfo> users = mUserManager.getUsers(true);
569 final int userCount = users.size();
570 for (int i = 0; i < userCount; i++) {
571 UserInfo user = users.get(i);
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700572 dumpForUserLocked(user.id, pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800573 }
574 } finally {
575 Binder.restoreCallingIdentity(identity);
576 }
577 }
578 }
579
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700580 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700581 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800582 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700583 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800584 dumpSettings(globalCursor, pw);
585 pw.println();
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700586
587 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
588 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
589 globalSettings.dumpHistoricalOperations(pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800590 }
591
592 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700593 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800594 dumpSettings(secureCursor, pw);
595 pw.println();
596
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700597 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
598 SETTINGS_TYPE_SECURE, userId);
599 secureSettings.dumpHistoricalOperations(pw);
600
Svetoslavb505ccc2015-02-17 12:41:04 -0800601 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700602 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800603 dumpSettings(systemCursor, pw);
604 pw.println();
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700605
606 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
607 SETTINGS_TYPE_SYSTEM, userId);
608 systemSettings.dumpHistoricalOperations(pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800609 }
610
611 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700612 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800613 return;
614 }
615
616 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
617 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
618 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
619
620 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700621 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
622 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
623 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800624 pw.println();
625 } while (cursor.moveToNext());
626 }
627
Svetoslav7e0683b2015-08-03 16:02:52 -0700628 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700629 if (s != null) {
630 return s;
631 }
632 return "{null}";
633 }
634
Svetoslav683914b2015-01-15 14:22:26 -0800635 private void registerBroadcastReceivers() {
636 IntentFilter userFilter = new IntentFilter();
637 userFilter.addAction(Intent.ACTION_USER_REMOVED);
638 userFilter.addAction(Intent.ACTION_USER_STOPPED);
639
640 getContext().registerReceiver(new BroadcastReceiver() {
641 @Override
642 public void onReceive(Context context, Intent intent) {
643 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700644 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800645
646 switch (intent.getAction()) {
647 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700648 synchronized (mLock) {
649 mSettingsRegistry.removeUserStateLocked(userId, true);
650 }
Svetoslav683914b2015-01-15 14:22:26 -0800651 } break;
652
653 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700654 synchronized (mLock) {
655 mSettingsRegistry.removeUserStateLocked(userId, false);
656 }
Svetoslav683914b2015-01-15 14:22:26 -0800657 } break;
658 }
659 }
660 }, userFilter);
661
662 PackageMonitor monitor = new PackageMonitor() {
663 @Override
664 public void onPackageRemoved(String packageName, int uid) {
665 synchronized (mLock) {
666 mSettingsRegistry.onPackageRemovedLocked(packageName,
667 UserHandle.getUserId(uid));
668 }
669 }
670 };
671
672 // package changes
673 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
674 UserHandle.ALL, true);
675 }
676
Svet Ganov53a441c2016-04-19 19:38:00 -0700677 private void startWatchingUserRestrictionChanges() {
678 // TODO: The current design of settings looking different based on user restrictions
679 // should be reworked to keep them separate and system code should check the setting
680 // first followed by checking the user restriction before performing an operation.
681 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
682 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
683 Bundle prevRestrictions) -> {
684 // We are changing the settings affected by restrictions to their current
685 // value with a forced update to ensure that all cross profile dependencies
686 // are taken into account. Also make sure the settings update to.. the same
687 // value passes the security checks, so clear binder calling id.
688 if (newRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)
689 != prevRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)) {
690 final long identity = Binder.clearCallingIdentity();
691 try {
692 synchronized (mLock) {
693 Setting setting = getSecureSetting(
694 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
695 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
696 setting != null ? setting.getValue() : null, userId, true);
697 }
698 } finally {
699 Binder.restoreCallingIdentity(identity);
700 }
701 }
702 if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
703 != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
704 final long identity = Binder.clearCallingIdentity();
705 try {
706 synchronized (mLock) {
707 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
708 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
709 setting != null ? setting.getValue() : null, userId, true);
710 }
711 } finally {
712 Binder.restoreCallingIdentity(identity);
713 }
714 }
715 if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
716 != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
717 final long identity = Binder.clearCallingIdentity();
718 try {
719 synchronized (mLock) {
720 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
721 updateGlobalSetting(Settings.Global.ADB_ENABLED,
722 setting != null ? setting.getValue() : null, userId, true);
723 }
724 } finally {
725 Binder.restoreCallingIdentity(identity);
726 }
727 }
728 if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
729 != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
730 final long identity = Binder.clearCallingIdentity();
731 try {
732 synchronized (mLock) {
733 Setting enable = getGlobalSetting(
734 Settings.Global.PACKAGE_VERIFIER_ENABLE);
735 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
736 enable != null ? enable.getValue() : null, userId, true);
737 Setting include = getGlobalSetting(
738 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
739 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
740 include != null ? include.getValue() : null, userId, true);
741 }
742 } finally {
743 Binder.restoreCallingIdentity(identity);
744 }
745 }
746 if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
747 != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
748 final long identity = Binder.clearCallingIdentity();
749 try {
750 synchronized (mLock) {
751 Setting setting = getGlobalSetting(
752 Settings.Global.PREFERRED_NETWORK_MODE);
753 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
754 setting != null ? setting.getValue() : null, userId, true);
755 }
756 } finally {
757 Binder.restoreCallingIdentity(identity);
758 }
759 }
760 });
761 }
762
Svetoslav7ec28e82015-05-20 17:01:10 -0700763 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800764 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700765 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800766 }
767
Svetoslav7ec28e82015-05-20 17:01:10 -0700768 synchronized (mLock) {
769 // Get the settings.
770 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700771 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800772
Svetoslav7ec28e82015-05-20 17:01:10 -0700773 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800774
Svetoslav7ec28e82015-05-20 17:01:10 -0700775 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800776
Svetoslav7ec28e82015-05-20 17:01:10 -0700777 String[] normalizedProjection = normalizeProjection(projection);
778 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800779
Svetoslav7ec28e82015-05-20 17:01:10 -0700780 // Anyone can get the global settings, so no security checks.
781 for (int i = 0; i < nameCount; i++) {
782 String name = names.get(i);
783 Setting setting = settingsState.getSettingLocked(name);
784 appendSettingToCursor(result, setting);
785 }
786
787 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800788 }
Svetoslav683914b2015-01-15 14:22:26 -0800789 }
790
Svetoslav7ec28e82015-05-20 17:01:10 -0700791 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800792 if (DEBUG) {
793 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
794 }
795
796 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700797 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700798 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700799 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800800 }
Svetoslav683914b2015-01-15 14:22:26 -0800801 }
802
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 private boolean updateGlobalSetting(String name, String value, int requestingUserId,
804 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800805 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700806 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800807 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700808 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
809 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800810 }
811
Svet Ganov53a441c2016-04-19 19:38:00 -0700812 private boolean insertGlobalSetting(String name, String value, int requestingUserId,
813 boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700814 if (DEBUG) {
815 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
816 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
818 forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700819 }
820
Svet Ganov53a441c2016-04-19 19:38:00 -0700821 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800822 if (DEBUG) {
823 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
824 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700825 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
826 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800827 }
828
Svetoslav7ec28e82015-05-20 17:01:10 -0700829 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700830 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800831 // Make sure the caller can change the settings - treated as secure.
832 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
833
Svetoslav683914b2015-01-15 14:22:26 -0800834 // Resolve the userId on whose behalf the call is made.
835 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
836
Makoto Onuki28da2e32015-11-20 11:30:44 -0800837 // If this is a setting that is currently restricted for this user, do not allow
838 // unrestricting changes.
Victor Chang9c7b7062016-07-12 23:47:29 +0100839 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
840 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800841 return false;
842 }
843
844 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700845 synchronized (mLock) {
846 switch (operation) {
847 case MUTATION_OPERATION_INSERT: {
848 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700849 .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
850 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700851 }
Svetoslav683914b2015-01-15 14:22:26 -0800852
Svetoslav7ec28e82015-05-20 17:01:10 -0700853 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700854 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
855 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700856 }
Svetoslav683914b2015-01-15 14:22:26 -0800857
Svetoslav7ec28e82015-05-20 17:01:10 -0700858 case MUTATION_OPERATION_UPDATE: {
859 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700860 .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
861 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700862 }
Svetoslav683914b2015-01-15 14:22:26 -0800863 }
864 }
865
866 return false;
867 }
868
Svetoslav7ec28e82015-05-20 17:01:10 -0700869 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800870 if (DEBUG) {
871 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
872 }
873
874 // Resolve the userId on whose behalf the call is made.
875 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
876
Svetoslav7ec28e82015-05-20 17:01:10 -0700877 synchronized (mLock) {
878 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700879 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800880
Svetoslav7ec28e82015-05-20 17:01:10 -0700881 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800882
Svetoslav7ec28e82015-05-20 17:01:10 -0700883 String[] normalizedProjection = normalizeProjection(projection);
884 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800885
Svetoslav7ec28e82015-05-20 17:01:10 -0700886 for (int i = 0; i < nameCount; i++) {
887 String name = names.get(i);
888 // Determine the owning user as some profile settings are cloned from the parent.
889 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
890 name);
Svetoslav683914b2015-01-15 14:22:26 -0800891
Svetoslav7ec28e82015-05-20 17:01:10 -0700892 // Special case for location (sigh).
893 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700894 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700895 }
Svetoslav683914b2015-01-15 14:22:26 -0800896
Svetoslav7ec28e82015-05-20 17:01:10 -0700897 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700898 SETTINGS_TYPE_SECURE, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700899 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800900 }
901
Svetoslav7ec28e82015-05-20 17:01:10 -0700902 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800903 }
Svetoslav683914b2015-01-15 14:22:26 -0800904 }
905
Svetoslav7ec28e82015-05-20 17:01:10 -0700906 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800907 if (DEBUG) {
908 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
909 }
910
911 // Resolve the userId on whose behalf the call is made.
912 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
913
914 // Determine the owning user as some profile settings are cloned from the parent.
915 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
916
917 // Special case for location (sigh).
918 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700919 return mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
920 owningUserId).getNullSetting();
Svetoslav683914b2015-01-15 14:22:26 -0800921 }
922
923 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700925 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -0700926 owningUserId, name);
927 }
Svetoslav683914b2015-01-15 14:22:26 -0800928 }
929
Svet Ganov53a441c2016-04-19 19:38:00 -0700930 private boolean insertSecureSetting(String name, String value, int requestingUserId,
931 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800932 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700933 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800934 + requestingUserId + ")");
935 }
936
Svet Ganov53a441c2016-04-19 19:38:00 -0700937 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
938 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800939 }
940
Svet Ganov53a441c2016-04-19 19:38:00 -0700941 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800942 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800944 }
945
Svet Ganov53a441c2016-04-19 19:38:00 -0700946 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
947 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800948 }
949
Svet Ganov53a441c2016-04-19 19:38:00 -0700950 private boolean updateSecureSetting(String name, String value, int requestingUserId,
951 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800952 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700953 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800954 + requestingUserId + ")");
955 }
956
Svet Ganov53a441c2016-04-19 19:38:00 -0700957 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
958 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800959 }
960
Svetoslav7ec28e82015-05-20 17:01:10 -0700961 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700962 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800963 // Make sure the caller can change the settings.
964 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
965
Svetoslav683914b2015-01-15 14:22:26 -0800966 // Resolve the userId on whose behalf the call is made.
967 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
968
Makoto Onuki28da2e32015-11-20 11:30:44 -0800969 // If this is a setting that is currently restricted for this user, do not allow
970 // unrestricting changes.
Victor Chang9c7b7062016-07-12 23:47:29 +0100971 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
972 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800973 return false;
974 }
975
976 // Determine the owning user as some profile settings are cloned from the parent.
977 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
978
979 // Only the owning user can change the setting.
980 if (owningUserId != callingUserId) {
981 return false;
982 }
983
984 // Special cases for location providers (sigh).
985 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700986 return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800987 }
988
989 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700990 synchronized (mLock) {
991 switch (operation) {
992 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700993 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
994 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700995 }
Svetoslav683914b2015-01-15 14:22:26 -0800996
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700998 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
999 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001000 }
Svetoslav683914b2015-01-15 14:22:26 -08001001
Svetoslav7ec28e82015-05-20 17:01:10 -07001002 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001003 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
1004 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001005 }
Svetoslav683914b2015-01-15 14:22:26 -08001006 }
1007 }
1008
1009 return false;
1010 }
1011
Svetoslav7ec28e82015-05-20 17:01:10 -07001012 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001013 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001014 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001015 }
1016
1017 // Resolve the userId on whose behalf the call is made.
1018 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1019
Svetoslav7ec28e82015-05-20 17:01:10 -07001020 synchronized (mLock) {
1021 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001022 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001023
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001025
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 String[] normalizedProjection = normalizeProjection(projection);
1027 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001028
Svetoslav7ec28e82015-05-20 17:01:10 -07001029 for (int i = 0; i < nameCount; i++) {
1030 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001031
Svetoslav7ec28e82015-05-20 17:01:10 -07001032 // Determine the owning user as some profile settings are cloned from the parent.
1033 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1034 name);
Svetoslav683914b2015-01-15 14:22:26 -08001035
Svetoslav7ec28e82015-05-20 17:01:10 -07001036 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001037 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 appendSettingToCursor(result, setting);
1039 }
1040
1041 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001042 }
Svetoslav683914b2015-01-15 14:22:26 -08001043 }
1044
Svetoslav7ec28e82015-05-20 17:01:10 -07001045 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001046 if (DEBUG) {
1047 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1048 }
1049
1050 // Resolve the userId on whose behalf the call is made.
1051 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1052
1053 // Determine the owning user as some profile settings are cloned from the parent.
1054 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1055
1056 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001057 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001058 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001059 }
Svetoslav683914b2015-01-15 14:22:26 -08001060 }
1061
Svetoslav7ec28e82015-05-20 17:01:10 -07001062 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001063 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001064 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001065 + requestingUserId + ")");
1066 }
1067
Svetoslav7ec28e82015-05-20 17:01:10 -07001068 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001069 }
1070
Svetoslav7ec28e82015-05-20 17:01:10 -07001071 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001072 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001073 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001074 }
1075
Svetoslav7ec28e82015-05-20 17:01:10 -07001076 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001077 }
1078
Svetoslav7ec28e82015-05-20 17:01:10 -07001079 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001080 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001081 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001082 + requestingUserId + ")");
1083 }
1084
Svetoslav7ec28e82015-05-20 17:01:10 -07001085 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001086 }
1087
Svetoslav7ec28e82015-05-20 17:01:10 -07001088 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001089 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001090 if (!hasWriteSecureSettingsPermission()) {
1091 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1092 // operation is allowed for the calling package through appops.
1093 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1094 Binder.getCallingUid(), getCallingPackage(), true)) {
1095 return false;
1096 }
Svetoslav683914b2015-01-15 14:22:26 -08001097 }
1098
Svetoslav683914b2015-01-15 14:22:26 -08001099 // Resolve the userId on whose behalf the call is made.
1100 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1101
Svetoslavd8d25e02015-11-20 13:09:26 -08001102 // Enforce what the calling package can mutate the system settings.
1103 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1104
Svetoslav683914b2015-01-15 14:22:26 -08001105 // Determine the owning user as some profile settings are cloned from the parent.
1106 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1107
1108 // Only the owning user id can change the setting.
1109 if (owningUserId != callingUserId) {
1110 return false;
1111 }
1112
Jeff Sharkey413573a2016-02-22 17:52:45 -07001113 // Invalidate any relevant cache files
1114 String cacheName = null;
1115 if (Settings.System.RINGTONE.equals(name)) {
1116 cacheName = Settings.System.RINGTONE_CACHE;
1117 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1118 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1119 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1120 cacheName = Settings.System.ALARM_ALERT_CACHE;
1121 }
1122 if (cacheName != null) {
1123 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001124 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001125 cacheFile.delete();
1126 }
1127
Svetoslav683914b2015-01-15 14:22:26 -08001128 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001129 synchronized (mLock) {
1130 switch (operation) {
1131 case MUTATION_OPERATION_INSERT: {
1132 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001133 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
1134 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001135 }
1136
1137 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001138 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1139 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001140 }
1141
1142 case MUTATION_OPERATION_UPDATE: {
1143 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001144 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1145 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001146 }
Svetoslav683914b2015-01-15 14:22:26 -08001147 }
1148
Svetoslav7ec28e82015-05-20 17:01:10 -07001149 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001150 }
Svetoslav683914b2015-01-15 14:22:26 -08001151 }
1152
Billy Lau6ad2d662015-07-18 00:26:58 +01001153 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001154 // Write secure settings is a more protected permission. If caller has it we are good.
1155 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1156 == PackageManager.PERMISSION_GRANTED) {
1157 return true;
1158 }
1159
Svetoslavf41334b2015-06-23 12:06:03 -07001160 return false;
1161 }
1162
Svetoslav683914b2015-01-15 14:22:26 -08001163 private void validateSystemSettingValue(String name, String value) {
1164 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1165 if (validator != null && !validator.validate(value)) {
1166 throw new IllegalArgumentException("Invalid value: " + value
1167 + " for setting: " + name);
1168 }
1169 }
1170
1171 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1172 int owningUserId) {
1173 // Optimization - location providers are restricted only for managed profiles.
1174 if (callingUserId == owningUserId) {
1175 return false;
1176 }
1177 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1178 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1179 new UserHandle(callingUserId))) {
1180 return true;
1181 }
1182 return false;
1183 }
1184
Makoto Onuki28da2e32015-11-20 11:30:44 -08001185 /**
1186 * Checks whether changing a setting to a value is prohibited by the corresponding user
1187 * restriction.
1188 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001189 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1190 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001191 *
1192 * @return true if the change is prohibited, false if the change is allowed.
1193 */
1194 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001195 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001196 String restriction;
1197 switch (setting) {
1198 case Settings.Secure.LOCATION_MODE:
1199 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1200 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1201 // here normally, but we still protect it here from a direct provider write.
1202 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1203 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1204 break;
1205
1206 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1207 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1208 // a provider, which should be allowed even if the user restriction is set.
1209 if (value != null && value.startsWith("-")) return false;
1210 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1211 break;
1212
1213 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1214 if ("0".equals(value)) return false;
1215 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1216 break;
1217
1218 case Settings.Global.ADB_ENABLED:
1219 if ("0".equals(value)) return false;
1220 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1221 break;
1222
1223 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1224 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1225 if ("1".equals(value)) return false;
1226 restriction = UserManager.ENSURE_VERIFY_APPS;
1227 break;
1228
1229 case Settings.Global.PREFERRED_NETWORK_MODE:
1230 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1231 break;
1232
Victor Chang9c7b7062016-07-12 23:47:29 +01001233 case Settings.Secure.ALWAYS_ON_VPN_APP:
1234 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1235 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
1236 if (callingUid == Process.SYSTEM_UID || callingUid == Process.ROOT_UID) {
1237 return false;
1238 }
1239 restriction = UserManager.DISALLOW_CONFIG_VPN;
1240 break;
1241
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001242 case Settings.Global.SAFE_BOOT_DISALLOWED:
1243 if ("1".equals(value)) return false;
1244 restriction = UserManager.DISALLOW_SAFE_BOOT;
1245 break;
1246
Makoto Onuki28da2e32015-11-20 11:30:44 -08001247 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001248 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001249 if ("0".equals(value)) return false;
1250 restriction = UserManager.DISALLOW_DATA_ROAMING;
1251 break;
1252 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001253 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001254 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001255
1256 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001257 }
1258
1259 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1260 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1261 }
1262
1263 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001264 final int parentId;
1265 // Resolves dependency if setting has a dependency and the calling user has a parent
1266 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1267 && (parentId = getGroupParentLocked(userId)) != userId) {
1268 // The setting has a dependency and the profile has a parent
1269 String dependency = sSystemCloneFromParentOnDependency.get(setting);
1270 if (getSecureSetting(dependency, userId).getValue().equals("1")) {
1271 return parentId;
1272 }
1273 }
Svetoslav683914b2015-01-15 14:22:26 -08001274 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1275 }
1276
1277 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1278 final int parentId = getGroupParentLocked(userId);
1279 if (parentId != userId && keys.contains(name)) {
1280 return parentId;
1281 }
1282 return userId;
1283 }
1284
Svetoslavf41334b2015-06-23 12:06:03 -07001285 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001286 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001287 // System/root/shell can mutate whatever secure settings they want.
1288 final int callingUid = Binder.getCallingUid();
1289 if (callingUid == android.os.Process.SYSTEM_UID
1290 || callingUid == Process.SHELL_UID
1291 || callingUid == Process.ROOT_UID) {
1292 return;
1293 }
1294
1295 switch (operation) {
1296 case MUTATION_OPERATION_INSERT:
1297 // Insert updates.
1298 case MUTATION_OPERATION_UPDATE: {
1299 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1300 return;
1301 }
1302
1303 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001304 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001305
1306 // Privileged apps can do whatever they want.
1307 if ((packageInfo.applicationInfo.privateFlags
1308 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1309 return;
1310 }
1311
1312 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1313 packageInfo.applicationInfo.targetSdkVersion, name);
1314 } break;
1315
1316 case MUTATION_OPERATION_DELETE: {
1317 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1318 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1319 throw new IllegalArgumentException("You cannot delete system defined"
1320 + " secure settings.");
1321 }
1322
1323 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001324 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001325
1326 // Privileged apps can do whatever they want.
1327 if ((packageInfo.applicationInfo.privateFlags &
1328 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1329 return;
1330 }
1331
1332 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1333 packageInfo.applicationInfo.targetSdkVersion, name);
1334 } break;
1335 }
1336 }
1337
Xiaohui Chen43765b72015-08-31 10:57:33 -07001338 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001339 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001340 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1341 getCallingPackage(), 0, userId);
1342 if (packageInfo != null) {
1343 return packageInfo;
1344 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001345 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001346 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001347 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001348 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001349 }
1350
1351 private int getGroupParentLocked(int userId) {
1352 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001353 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001354 return userId;
1355 }
1356 // We are in the same process with the user manager and the returned
1357 // user info is a cached instance, so just look up instead of cache.
1358 final long identity = Binder.clearCallingIdentity();
1359 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001360 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001361 UserInfo userInfo = mUserManager.getProfileParent(userId);
1362 return (userInfo != null) ? userInfo.id : userId;
1363 } finally {
1364 Binder.restoreCallingIdentity(identity);
1365 }
1366 }
1367
Svetoslav683914b2015-01-15 14:22:26 -08001368 private void enforceWritePermission(String permission) {
1369 if (getContext().checkCallingOrSelfPermission(permission)
1370 != PackageManager.PERMISSION_GRANTED) {
1371 throw new SecurityException("Permission denial: writing to settings requires:"
1372 + permission);
1373 }
1374 }
1375
1376 /*
1377 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1378 * This setting contains a list of the currently enabled location providers.
1379 * But helper functions in android.providers.Settings can enable or disable
1380 * a single provider by using a "+" or "-" prefix before the provider name.
1381 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001382 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1383 * is set, the said method will only allow values with the "-" prefix.
1384 *
Svetoslav683914b2015-01-15 14:22:26 -08001385 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001386 */
Svet Ganov53a441c2016-04-19 19:38:00 -07001387 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1388 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001389 if (TextUtils.isEmpty(value)) {
1390 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001391 }
1392
Svetoslav683914b2015-01-15 14:22:26 -08001393 final char prefix = value.charAt(0);
1394 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001395 if (forceNotify) {
1396 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1397 mSettingsRegistry.notifyForSettingsChange(key,
1398 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1399 }
Svetoslav683914b2015-01-15 14:22:26 -08001400 return false;
1401 }
1402
1403 // skip prefix
1404 value = value.substring(1);
1405
Svetoslav7ec28e82015-05-20 17:01:10 -07001406 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001407 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1408
1409 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1410
1411 int index = oldProviders.indexOf(value);
1412 int end = index + value.length();
1413
1414 // check for commas to avoid matching on partial string
1415 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1416 index = -1;
1417 }
1418
1419 // check for commas to avoid matching on partial string
1420 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1421 index = -1;
1422 }
1423
1424 String newProviders;
1425
1426 if (prefix == '+' && index < 0) {
1427 // append the provider to the list if not present
1428 if (oldProviders.length() == 0) {
1429 newProviders = value;
1430 } else {
1431 newProviders = oldProviders + ',' + value;
1432 }
1433 } else if (prefix == '-' && index >= 0) {
1434 // remove the provider from the list if present
1435 // remove leading or trailing comma
1436 if (index > 0) {
1437 index--;
1438 } else if (end < oldProviders.length()) {
1439 end++;
1440 }
1441
1442 newProviders = oldProviders.substring(0, index);
1443 if (end < oldProviders.length()) {
1444 newProviders += oldProviders.substring(end);
1445 }
1446 } else {
1447 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001448 if (forceNotify) {
1449 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1450 mSettingsRegistry.notifyForSettingsChange(key,
1451 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1452 }
Svetoslav683914b2015-01-15 14:22:26 -08001453 return false;
1454 }
1455
Svet Ganov53a441c2016-04-19 19:38:00 -07001456 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001457 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svet Ganov53a441c2016-04-19 19:38:00 -07001458 getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001459 }
1460
Svetoslav683914b2015-01-15 14:22:26 -08001461 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1462 int targetSdkVersion, String name) {
1463 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1464 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1465 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1466 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1467 + " This will soon become an error.");
1468 } else {
1469 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1470 + " This will soon become an error.");
1471 }
1472 } else {
1473 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1474 throw new IllegalArgumentException("You cannot change private secure settings.");
1475 } else {
1476 throw new IllegalArgumentException("You cannot keep your settings in"
1477 + " the secure settings.");
1478 }
1479 }
1480 }
1481
1482 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1483 if (requestingUserId == UserHandle.getCallingUserId()) {
1484 return requestingUserId;
1485 }
1486 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1487 Binder.getCallingUid(), requestingUserId, false, true,
1488 "get/set setting for user", null);
1489 }
1490
Svet Ganov53a441c2016-04-19 19:38:00 -07001491 private Bundle packageValueForCallResult(Setting setting,
1492 boolean trackingGeneration) {
1493 if (!trackingGeneration) {
1494 if (setting.isNull()) {
1495 return NULL_SETTING_BUNDLE;
1496 }
1497 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001498 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001499 Bundle result = new Bundle();
1500 result.putString(Settings.NameValueTable.VALUE,
1501 !setting.isNull() ? setting.getValue() : null);
1502 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1503 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001504 }
1505
1506 private static int getRequestingUserId(Bundle args) {
1507 final int callingUserId = UserHandle.getCallingUserId();
1508 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1509 : callingUserId;
1510 }
1511
Svet Ganov53a441c2016-04-19 19:38:00 -07001512 private boolean isTrackingGeneration(Bundle args) {
1513 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1514 }
1515
Svetoslav683914b2015-01-15 14:22:26 -08001516 private static String getSettingValue(Bundle args) {
1517 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1518 }
1519
1520 private static String getValidTableOrThrow(Uri uri) {
1521 if (uri.getPathSegments().size() > 0) {
1522 String table = uri.getPathSegments().get(0);
1523 if (DatabaseHelper.isValidTable(table)) {
1524 return table;
1525 }
1526 throw new IllegalArgumentException("Bad root path: " + table);
1527 }
1528 throw new IllegalArgumentException("Invalid URI:" + uri);
1529 }
1530
1531 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001532 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001533 return new MatrixCursor(projection, 0);
1534 }
1535 MatrixCursor cursor = new MatrixCursor(projection, 1);
1536 appendSettingToCursor(cursor, setting);
1537 return cursor;
1538 }
1539
1540 private static String[] normalizeProjection(String[] projection) {
1541 if (projection == null) {
1542 return ALL_COLUMNS;
1543 }
1544
1545 final int columnCount = projection.length;
1546 for (int i = 0; i < columnCount; i++) {
1547 String column = projection[i];
1548 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1549 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001550 }
1551 }
1552
Svetoslav683914b2015-01-15 14:22:26 -08001553 return projection;
1554 }
1555
1556 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001557 if (setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001558 return;
1559 }
Svetoslav683914b2015-01-15 14:22:26 -08001560 final int columnCount = cursor.getColumnCount();
1561
1562 String[] values = new String[columnCount];
1563
1564 for (int i = 0; i < columnCount; i++) {
1565 String column = cursor.getColumnName(i);
1566
1567 switch (column) {
1568 case Settings.NameValueTable._ID: {
1569 values[i] = setting.getId();
1570 } break;
1571
1572 case Settings.NameValueTable.NAME: {
1573 values[i] = setting.getName();
1574 } break;
1575
1576 case Settings.NameValueTable.VALUE: {
1577 values[i] = setting.getValue();
1578 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001579 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001580 }
1581
Svetoslav683914b2015-01-15 14:22:26 -08001582 cursor.addRow(values);
1583 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001584
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001585 private static boolean isKeyValid(String key) {
1586 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1587 }
1588
Svetoslav683914b2015-01-15 14:22:26 -08001589 private static final class Arguments {
1590 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1591 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1592
1593 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1594 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1595
1596 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1597 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1598
1599 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1600 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1601
1602 public final String table;
1603 public final String name;
1604
1605 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1606 final int segmentSize = uri.getPathSegments().size();
1607 switch (segmentSize) {
1608 case 1: {
1609 if (where != null
1610 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1611 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1612 && whereArgs.length == 1) {
1613 name = whereArgs[0];
1614 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001615 return;
Svetoslav683914b2015-01-15 14:22:26 -08001616 } else if (where != null
1617 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1618 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1619 final int startIndex = Math.max(where.indexOf("'"),
1620 where.indexOf("\"")) + 1;
1621 final int endIndex = Math.max(where.lastIndexOf("'"),
1622 where.lastIndexOf("\""));
1623 name = where.substring(startIndex, endIndex);
1624 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001625 return;
Svetoslav683914b2015-01-15 14:22:26 -08001626 } else if (supportAll && where == null && whereArgs == null) {
1627 name = null;
1628 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001629 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001630 }
Svetoslav683914b2015-01-15 14:22:26 -08001631 } break;
1632
Svetoslav28494652015-02-12 14:11:42 -08001633 case 2: {
1634 if (where == null && whereArgs == null) {
1635 name = uri.getPathSegments().get(1);
1636 table = computeTableForSetting(uri, name);
1637 return;
1638 }
1639 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001640 }
Svetoslav28494652015-02-12 14:11:42 -08001641
1642 EventLogTags.writeUnsupportedSettingsQuery(
1643 uri.toSafeString(), where, Arrays.toString(whereArgs));
1644 String message = String.format( "Supported SQL:\n"
1645 + " uri content://some_table/some_property with null where and where args\n"
1646 + " uri content://some_table with query name=? and single name as arg\n"
1647 + " uri content://some_table with query name=some_name and null args\n"
1648 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1649 Arrays.toString(whereArgs));
1650 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001651 }
1652
Svetoslav28494652015-02-12 14:11:42 -08001653 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001654 String table = getValidTableOrThrow(uri);
1655
1656 if (name != null) {
1657 if (sSystemMovedToSecureSettings.contains(name)) {
1658 table = TABLE_SECURE;
1659 }
1660
1661 if (sSystemMovedToGlobalSettings.contains(name)) {
1662 table = TABLE_GLOBAL;
1663 }
1664
1665 if (sSecureMovedToGlobalSettings.contains(name)) {
1666 table = TABLE_GLOBAL;
1667 }
1668
1669 if (sGlobalMovedToSecureSettings.contains(name)) {
1670 table = TABLE_SECURE;
1671 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001672 }
Svetoslav683914b2015-01-15 14:22:26 -08001673
1674 return table;
1675 }
1676 }
1677
1678 final class SettingsRegistry {
1679 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1680
Svetoslav683914b2015-01-15 14:22:26 -08001681 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1682 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1683 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1684
1685 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1686
Svet Ganov53a441c2016-04-19 19:38:00 -07001687 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001688
Svetoslav7e0683b2015-08-03 16:02:52 -07001689 private final Handler mHandler;
1690
Svet Ganov53a441c2016-04-19 19:38:00 -07001691 private final BackupManager mBackupManager;
1692
Svetoslav683914b2015-01-15 14:22:26 -08001693 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001694 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001695 mGenerationRegistry = new GenerationRegistry(mLock);
1696 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001697 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001698 }
1699
Svetoslav683914b2015-01-15 14:22:26 -08001700 public List<String> getSettingsNamesLocked(int type, int userId) {
1701 final int key = makeKey(type, userId);
1702 SettingsState settingsState = peekSettingsStateLocked(key);
1703 return settingsState.getSettingNamesLocked();
1704 }
1705
1706 public SettingsState getSettingsLocked(int type, int userId) {
1707 final int key = makeKey(type, userId);
1708 return peekSettingsStateLocked(key);
1709 }
1710
1711 public void ensureSettingsForUserLocked(int userId) {
1712 // Migrate the setting for this user if needed.
1713 migrateLegacySettingsForUserIfNeededLocked(userId);
1714
1715 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001716 if (userId == UserHandle.USER_SYSTEM) {
1717 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001718 ensureSettingsStateLocked(globalKey);
1719 }
1720
1721 // Ensure secure settings loaded.
1722 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1723 ensureSettingsStateLocked(secureKey);
1724
1725 // Make sure the secure settings have an Android id set.
1726 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1727 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1728
1729 // Ensure system settings loaded.
1730 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1731 ensureSettingsStateLocked(systemKey);
1732
1733 // Upgrade the settings to the latest version.
1734 UpgradeController upgrader = new UpgradeController(userId);
1735 upgrader.upgradeIfNeededLocked();
1736 }
1737
1738 private void ensureSettingsStateLocked(int key) {
1739 if (mSettingsStates.get(key) == null) {
1740 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1741 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
Svetoslav Ganov92057492016-05-16 12:36:43 -07001742 maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001743 mSettingsStates.put(key, settingsState);
1744 }
1745 }
1746
1747 public void removeUserStateLocked(int userId, boolean permanently) {
1748 // We always keep the global settings in memory.
1749
1750 // Nuke system settings.
1751 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1752 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1753 if (systemSettingsState != null) {
1754 if (permanently) {
1755 mSettingsStates.remove(systemKey);
1756 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001757 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001758 systemSettingsState.destroyLocked(new Runnable() {
1759 @Override
1760 public void run() {
1761 mSettingsStates.remove(systemKey);
1762 }
1763 });
1764 }
1765 }
1766
1767 // Nuke secure settings.
1768 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1769 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1770 if (secureSettingsState != null) {
1771 if (permanently) {
1772 mSettingsStates.remove(secureKey);
1773 secureSettingsState.destroyLocked(null);
1774 } else {
1775 secureSettingsState.destroyLocked(new Runnable() {
1776 @Override
1777 public void run() {
1778 mSettingsStates.remove(secureKey);
1779 }
1780 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001781 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001782 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001783
1784 // Nuke generation tracking data
1785 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001786 }
1787
Svetoslav683914b2015-01-15 14:22:26 -08001788 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001789 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001790 final int key = makeKey(type, userId);
1791
1792 SettingsState settingsState = peekSettingsStateLocked(key);
1793 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1794
Svet Ganov53a441c2016-04-19 19:38:00 -07001795 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001796 notifyForSettingsChange(key, name);
1797 }
1798 return success;
1799 }
1800
Svet Ganov53a441c2016-04-19 19:38:00 -07001801 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001802 final int key = makeKey(type, userId);
1803
1804 SettingsState settingsState = peekSettingsStateLocked(key);
1805 final boolean success = settingsState.deleteSettingLocked(name);
1806
Svet Ganov53a441c2016-04-19 19:38:00 -07001807 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001808 notifyForSettingsChange(key, name);
1809 }
1810 return success;
1811 }
1812
1813 public Setting getSettingLocked(int type, int userId, String name) {
1814 final int key = makeKey(type, userId);
1815
1816 SettingsState settingsState = peekSettingsStateLocked(key);
1817 return settingsState.getSettingLocked(name);
1818 }
1819
1820 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001821 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001822 final int key = makeKey(type, userId);
1823
1824 SettingsState settingsState = peekSettingsStateLocked(key);
1825 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1826
Svet Ganov53a441c2016-04-19 19:38:00 -07001827 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001828 notifyForSettingsChange(key, name);
1829 }
1830
1831 return success;
1832 }
1833
1834 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001835 // Global and secure settings are signature protected. Apps signed
1836 // by the platform certificate are generally not uninstalled and
1837 // the main exception is tests. We trust components signed
1838 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001839
1840 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1841 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001842 if (systemSettings != null) {
1843 systemSettings.onPackageRemovedLocked(packageName);
1844 }
Svetoslav683914b2015-01-15 14:22:26 -08001845 }
1846
1847 private SettingsState peekSettingsStateLocked(int key) {
1848 SettingsState settingsState = mSettingsStates.get(key);
1849 if (settingsState != null) {
1850 return settingsState;
1851 }
1852
1853 ensureSettingsForUserLocked(getUserIdFromKey(key));
1854 return mSettingsStates.get(key);
1855 }
1856
1857 private void migrateAllLegacySettingsIfNeeded() {
1858 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001859 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001860 File globalFile = getSettingsFile(key);
1861 if (globalFile.exists()) {
1862 return;
1863 }
1864
1865 final long identity = Binder.clearCallingIdentity();
1866 try {
1867 List<UserInfo> users = mUserManager.getUsers(true);
1868
1869 final int userCount = users.size();
1870 for (int i = 0; i < userCount; i++) {
1871 final int userId = users.get(i).id;
1872
1873 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1874 SQLiteDatabase database = dbHelper.getWritableDatabase();
1875 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1876
1877 // Upgrade to the latest version.
1878 UpgradeController upgrader = new UpgradeController(userId);
1879 upgrader.upgradeIfNeededLocked();
1880
1881 // Drop from memory if not a running user.
1882 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1883 removeUserStateLocked(userId, false);
1884 }
1885 }
1886 } finally {
1887 Binder.restoreCallingIdentity(identity);
1888 }
1889 }
1890 }
1891
1892 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1893 // Every user has secure settings and if no file we need to migrate.
1894 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1895 File secureFile = getSettingsFile(secureKey);
1896 if (secureFile.exists()) {
1897 return;
1898 }
1899
1900 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1901 SQLiteDatabase database = dbHelper.getWritableDatabase();
1902
1903 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1904 }
1905
1906 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1907 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001908 // Move over the system settings.
1909 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1910 ensureSettingsStateLocked(systemKey);
1911 SettingsState systemSettings = mSettingsStates.get(systemKey);
1912 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1913 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001914
1915 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001916 // Do this after System settings, since this is the first thing we check when deciding
1917 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001918 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1919 ensureSettingsStateLocked(secureKey);
1920 SettingsState secureSettings = mSettingsStates.get(secureKey);
1921 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1922 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1923 secureSettings.persistSyncLocked();
1924
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001925 // Move over the global settings if owner.
1926 // Do this last, since this is the first thing we check when deciding
1927 // to skip over migration from db to xml for owner user.
1928 if (userId == UserHandle.USER_SYSTEM) {
1929 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1930 ensureSettingsStateLocked(globalKey);
1931 SettingsState globalSettings = mSettingsStates.get(globalKey);
1932 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1933 globalSettings.persistSyncLocked();
1934 }
Svetoslav683914b2015-01-15 14:22:26 -08001935
1936 // Drop the database as now all is moved and persisted.
1937 if (DROP_DATABASE_ON_MIGRATION) {
1938 dbHelper.dropDatabase();
1939 } else {
1940 dbHelper.backupDatabase();
1941 }
1942 }
1943
1944 private void migrateLegacySettingsLocked(SettingsState settingsState,
1945 SQLiteDatabase database, String table) {
1946 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1947 queryBuilder.setTables(table);
1948
1949 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1950 null, null, null, null, null);
1951
1952 if (cursor == null) {
1953 return;
1954 }
1955
1956 try {
1957 if (!cursor.moveToFirst()) {
1958 return;
1959 }
1960
1961 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1962 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1963
1964 settingsState.setVersionLocked(database.getVersion());
1965
1966 while (!cursor.isAfterLast()) {
1967 String name = cursor.getString(nameColumnIdx);
1968 String value = cursor.getString(valueColumnIdx);
1969 settingsState.insertSettingLocked(name, value,
1970 SettingsState.SYSTEM_PACKAGE_NAME);
1971 cursor.moveToNext();
1972 }
1973 } finally {
1974 cursor.close();
1975 }
1976 }
1977
1978 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1979 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1980
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09001981 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001982 return;
1983 }
1984
1985 final int userId = getUserIdFromKey(secureSettings.mKey);
1986
1987 final UserInfo user;
1988 final long identity = Binder.clearCallingIdentity();
1989 try {
1990 user = mUserManager.getUserInfo(userId);
1991 } finally {
1992 Binder.restoreCallingIdentity(identity);
1993 }
1994 if (user == null) {
1995 // Can happen due to races when deleting users - treat as benign.
1996 return;
1997 }
1998
1999 String androidId = Long.toHexString(new SecureRandom().nextLong());
2000 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
2001 SettingsState.SYSTEM_PACKAGE_NAME);
2002
2003 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2004 + "] for user " + userId);
2005
2006 // Write a drop box entry if it's a restricted profile
2007 if (user.isRestricted()) {
2008 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2009 Context.DROPBOX_SERVICE);
2010 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2011 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2012 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2013 }
2014 }
2015 }
2016
2017 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002018 final int userId = getUserIdFromKey(key);
2019 Uri uri = getNotificationUriFor(key, name);
2020
Phil Weaver83fec002016-05-11 10:55:29 -07002021 mGenerationRegistry.incrementGeneration(key);
2022
Svetoslav7e0683b2015-08-03 16:02:52 -07002023 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2024 userId, 0, uri).sendToTarget();
2025
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002026 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002027 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2028 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002029 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002030 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2031 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002032 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002033
Svet Ganov53a441c2016-04-19 19:38:00 -07002034 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002035 }
2036
Svet Ganov53a441c2016-04-19 19:38:00 -07002037 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002038 Set<String> keysCloned) {
2039 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002040 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002041 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002042 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002043 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002044 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002045 final int key = makeKey(type, profileId);
2046 mGenerationRegistry.incrementGeneration(key);
2047
2048 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002049 }
2050 }
2051 }
Svetoslav683914b2015-01-15 14:22:26 -08002052 }
2053
Svetoslav683914b2015-01-15 14:22:26 -08002054 private boolean isGlobalSettingsKey(int key) {
2055 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2056 }
2057
2058 private boolean isSystemSettingsKey(int key) {
2059 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2060 }
2061
2062 private boolean isSecureSettingsKey(int key) {
2063 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2064 }
2065
2066 private File getSettingsFile(int key) {
2067 if (isGlobalSettingsKey(key)) {
2068 final int userId = getUserIdFromKey(key);
2069 return new File(Environment.getUserSystemDirectory(userId),
2070 SETTINGS_FILE_GLOBAL);
2071 } else if (isSystemSettingsKey(key)) {
2072 final int userId = getUserIdFromKey(key);
2073 return new File(Environment.getUserSystemDirectory(userId),
2074 SETTINGS_FILE_SYSTEM);
2075 } else if (isSecureSettingsKey(key)) {
2076 final int userId = getUserIdFromKey(key);
2077 return new File(Environment.getUserSystemDirectory(userId),
2078 SETTINGS_FILE_SECURE);
2079 } else {
2080 throw new IllegalArgumentException("Invalid settings key:" + key);
2081 }
2082 }
2083
2084 private Uri getNotificationUriFor(int key, String name) {
2085 if (isGlobalSettingsKey(key)) {
2086 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2087 : Settings.Global.CONTENT_URI;
2088 } else if (isSecureSettingsKey(key)) {
2089 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2090 : Settings.Secure.CONTENT_URI;
2091 } else if (isSystemSettingsKey(key)) {
2092 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2093 : Settings.System.CONTENT_URI;
2094 } else {
2095 throw new IllegalArgumentException("Invalid settings key:" + key);
2096 }
2097 }
2098
2099 private int getMaxBytesPerPackageForType(int type) {
2100 switch (type) {
2101 case SETTINGS_TYPE_GLOBAL:
2102 case SETTINGS_TYPE_SECURE: {
2103 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2104 }
2105
2106 default: {
2107 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2108 }
2109 }
2110 }
2111
Svetoslav7e0683b2015-08-03 16:02:52 -07002112 private final class MyHandler extends Handler {
2113 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2114 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2115
2116 public MyHandler(Looper looper) {
2117 super(looper);
2118 }
2119
2120 @Override
2121 public void handleMessage(Message msg) {
2122 switch (msg.what) {
2123 case MSG_NOTIFY_URI_CHANGED: {
2124 final int userId = msg.arg1;
2125 Uri uri = (Uri) msg.obj;
2126 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2127 if (DEBUG) {
2128 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2129 }
2130 } break;
2131
2132 case MSG_NOTIFY_DATA_CHANGED: {
2133 mBackupManager.dataChanged();
2134 } break;
2135 }
2136 }
2137 }
2138
Svetoslav683914b2015-01-15 14:22:26 -08002139 private final class UpgradeController {
Keun-young Parkec7a1182016-10-18 11:52:38 -07002140 private static final int SETTINGS_VERSION = 133;
Svetoslav683914b2015-01-15 14:22:26 -08002141
2142 private final int mUserId;
2143
2144 public UpgradeController(int userId) {
2145 mUserId = userId;
2146 }
2147
2148 public void upgradeIfNeededLocked() {
2149 // The version of all settings for a user is the same (all users have secure).
2150 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002151 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002152
2153 // Try an update from the current state.
2154 final int oldVersion = secureSettings.getVersionLocked();
2155 final int newVersion = SETTINGS_VERSION;
2156
Svet Ganovc9755bc2015-03-28 13:21:22 -07002157 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002158 if (oldVersion == newVersion) {
2159 return;
2160 }
2161
2162 // Try to upgrade.
2163 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2164
2165 // If upgrade failed start from scratch and upgrade.
2166 if (curVersion != newVersion) {
2167 // Drop state we have for this user.
2168 removeUserStateLocked(mUserId, true);
2169
2170 // Recreate the database.
2171 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2172 SQLiteDatabase database = dbHelper.getWritableDatabase();
2173 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2174
2175 // Migrate the settings for this user.
2176 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2177
2178 // Now upgrade should work fine.
2179 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002180
2181 // Make a note what happened, so we don't wonder why data was lost
2182 String reason = "Settings rebuilt! Current version: "
2183 + curVersion + " while expected: " + newVersion;
2184 getGlobalSettingsLocked().insertSettingLocked(
2185 Settings.Global.DATABASE_DOWNGRADE_REASON, reason, "android");
Svetoslav683914b2015-01-15 14:22:26 -08002186 }
2187
2188 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002189 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002190 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002191 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002192 globalSettings.setVersionLocked(newVersion);
2193 }
2194
2195 // Set the secure settings version.
2196 secureSettings.setVersionLocked(newVersion);
2197
2198 // Set the system settings version.
2199 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002200 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002201 systemSettings.setVersionLocked(newVersion);
2202 }
2203
2204 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002205 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002206 }
2207
2208 private SettingsState getSecureSettingsLocked(int userId) {
2209 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2210 }
2211
2212 private SettingsState getSystemSettingsLocked(int userId) {
2213 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2214 }
2215
Jeff Brown503cffc2015-03-26 18:08:51 -07002216 /**
2217 * You must perform all necessary mutations to bring the settings
2218 * for this user from the old to the new version. When you add a new
2219 * upgrade step you *must* update SETTINGS_VERSION.
2220 *
2221 * This is an example of moving a setting from secure to global.
2222 *
2223 * // v119: Example settings changes.
2224 * if (currentVersion == 118) {
2225 * if (userId == UserHandle.USER_OWNER) {
2226 * // Remove from the secure settings.
2227 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2228 * String name = "example_setting_to_move";
2229 * String value = secureSettings.getSetting(name);
2230 * secureSettings.deleteSetting(name);
2231 *
2232 * // Add to the global settings.
2233 * SettingsState globalSettings = getGlobalSettingsLocked();
2234 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2235 * }
2236 *
2237 * // Update the current version.
2238 * currentVersion = 119;
2239 * }
2240 */
Svetoslav683914b2015-01-15 14:22:26 -08002241 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2242 if (DEBUG) {
2243 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2244 + oldVersion + " to version: " + newVersion);
2245 }
2246
Jeff Brown503cffc2015-03-26 18:08:51 -07002247 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002248
John Spurlocke11ae112015-05-11 16:09:03 -04002249 // v119: Reset zen + ringer mode.
2250 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002251 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002252 final SettingsState globalSettings = getGlobalSettingsLocked();
2253 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2254 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2255 SettingsState.SYSTEM_PACKAGE_NAME);
2256 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2257 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2258 SettingsState.SYSTEM_PACKAGE_NAME);
2259 }
2260 currentVersion = 119;
2261 }
2262
Jason Monk27bbb2d2015-03-31 16:46:39 -04002263 // v120: Add double tap to wake setting.
2264 if (currentVersion == 119) {
2265 SettingsState secureSettings = getSecureSettingsLocked(userId);
2266 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2267 getContext().getResources().getBoolean(
2268 R.bool.def_double_tap_to_wake) ? "1" : "0",
2269 SettingsState.SYSTEM_PACKAGE_NAME);
2270
2271 currentVersion = 120;
2272 }
2273
Svetoslav7e0683b2015-08-03 16:02:52 -07002274 if (currentVersion == 120) {
2275 // Before 121, we used a different string encoding logic. We just bump the
2276 // version here; SettingsState knows how to handle pre-version 120 files.
2277 currentVersion = 121;
2278 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002279
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002280 if (currentVersion == 121) {
2281 // Version 122: allow OEMs to set a default payment component in resources.
2282 // Note that we only write the default if no default has been set;
2283 // if there is, we just leave the default at whatever it currently is.
2284 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2285 String defaultComponent = (getContext().getResources().getString(
2286 R.string.def_nfc_payment_component));
2287 Setting currentSetting = secureSettings.getSettingLocked(
2288 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2289 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002290 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002291 secureSettings.insertSettingLocked(
2292 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2293 defaultComponent,
2294 SettingsState.SYSTEM_PACKAGE_NAME);
2295 }
2296 currentVersion = 122;
2297 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002298
2299 if (currentVersion == 122) {
2300 // Version 123: Adding a default value for the ability to add a user from
2301 // the lock screen.
2302 if (userId == UserHandle.USER_SYSTEM) {
2303 final SettingsState globalSettings = getGlobalSettingsLocked();
2304 Setting currentSetting = globalSettings.getSettingLocked(
2305 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002306 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002307 globalSettings.insertSettingLocked(
2308 Settings.Global.ADD_USERS_WHEN_LOCKED,
2309 getContext().getResources().getBoolean(
2310 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2311 SettingsState.SYSTEM_PACKAGE_NAME);
2312 }
2313 }
2314 currentVersion = 123;
2315 }
Bryce Leebd179282015-12-17 19:01:37 -08002316
2317 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002318 final SettingsState globalSettings = getGlobalSettingsLocked();
2319 String defaultDisabledProfiles = (getContext().getResources().getString(
2320 R.string.def_bluetooth_disabled_profiles));
2321 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2322 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002323 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002324 }
2325
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002326 if (currentVersion == 124) {
2327 // Version 124: allow OEMs to set a default value for whether IME should be
2328 // shown when a physical keyboard is connected.
2329 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2330 Setting currentSetting = secureSettings.getSettingLocked(
2331 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002332 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002333 secureSettings.insertSettingLocked(
2334 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2335 getContext().getResources().getBoolean(
2336 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2337 SettingsState.SYSTEM_PACKAGE_NAME);
2338 }
2339 currentVersion = 125;
2340 }
2341
Ruben Brunk98576cf2016-03-07 18:54:28 -08002342 if (currentVersion == 125) {
2343 // Version 125: Allow OEMs to set the default VR service.
2344 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2345
2346 Setting currentSetting = secureSettings.getSettingLocked(
2347 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002348 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002349 ArraySet<ComponentName> l =
2350 SystemConfig.getInstance().getDefaultVrComponents();
2351
2352 if (l != null && !l.isEmpty()) {
2353 StringBuilder b = new StringBuilder();
2354 boolean start = true;
2355 for (ComponentName c : l) {
2356 if (!start) {
2357 b.append(':');
2358 }
2359 b.append(c.flattenToString());
2360 start = false;
2361 }
2362 secureSettings.insertSettingLocked(
2363 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2364 SettingsState.SYSTEM_PACKAGE_NAME);
2365 }
2366
2367 }
2368 currentVersion = 126;
2369 }
2370
Daniel U02ba6122016-04-01 18:41:42 +01002371 if (currentVersion == 126) {
2372 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2373 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2374 if (mUserManager.isManagedProfile(userId)) {
2375 final SettingsState systemSecureSettings =
2376 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2377
2378 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2379 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002380 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002381 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2382 secureSettings.insertSettingLocked(
2383 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2384 showNotifications.getValue(),
2385 SettingsState.SYSTEM_PACKAGE_NAME);
2386 }
2387
2388 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2389 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002390 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002391 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2392 secureSettings.insertSettingLocked(
2393 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2394 allowPrivate.getValue(),
2395 SettingsState.SYSTEM_PACKAGE_NAME);
2396 }
2397 }
2398 currentVersion = 127;
2399 }
2400
Steven Ngdc20ba62016-04-26 18:19:04 +01002401 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002402 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002403 currentVersion = 128;
2404 }
2405
Julia Reynolds1f721e12016-07-11 08:50:58 -04002406 if (currentVersion == 128) {
2407 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2408 // the new apps are appended to the list of already approved apps.
2409 final SettingsState systemSecureSettings =
2410 getSecureSettingsLocked(userId);
2411
2412 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2413 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2414 String defaultPolicyAccess = getContext().getResources().getString(
2415 com.android.internal.R.string.config_defaultDndAccessPackages);
2416 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2417 if (policyAccess.isNull()) {
2418 systemSecureSettings.insertSettingLocked(
2419 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2420 defaultPolicyAccess,
2421 SettingsState.SYSTEM_PACKAGE_NAME);
2422 } else {
2423 StringBuilder currentSetting =
2424 new StringBuilder(policyAccess.getValue());
2425 currentSetting.append(":");
2426 currentSetting.append(defaultPolicyAccess);
2427 systemSecureSettings.updateSettingLocked(
2428 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2429 currentSetting.toString(),
2430 SettingsState.SYSTEM_PACKAGE_NAME);
2431 }
2432 }
2433
2434 currentVersion = 129;
2435 }
2436
Dan Sandler71f85e92016-07-20 13:46:05 -04002437 if (currentVersion == 129) {
2438 // default longpress timeout changed from 500 to 400. If unchanged from the old
2439 // default, update to the new default.
2440 final SettingsState systemSecureSettings =
2441 getSecureSettingsLocked(userId);
2442 final String oldValue = systemSecureSettings.getSettingLocked(
2443 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2444 if (TextUtils.equals("500", oldValue)) {
2445 systemSecureSettings.insertSettingLocked(
2446 Settings.Secure.LONG_PRESS_TIMEOUT,
2447 String.valueOf(getContext().getResources().getInteger(
2448 R.integer.def_long_press_timeout_millis)),
2449 SettingsState.SYSTEM_PACKAGE_NAME);
2450 }
2451 currentVersion = 130;
2452 }
2453
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002454 if (currentVersion == 130) {
2455 // Initialize new multi-press timeout to default value
2456 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2457 final String oldValue = systemSecureSettings.getSettingLocked(
2458 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2459 if (TextUtils.equals(null, oldValue)) {
2460 systemSecureSettings.insertSettingLocked(
2461 Settings.Secure.MULTI_PRESS_TIMEOUT,
2462 String.valueOf(getContext().getResources().getInteger(
2463 R.integer.def_multi_press_timeout_millis)),
2464 SettingsState.SYSTEM_PACKAGE_NAME);
2465 }
2466
2467 currentVersion = 131;
2468 }
2469
Andre Lagoea35e072016-08-04 13:41:13 +01002470 if (currentVersion == 131) {
2471 // Version 131: Allow managed profile to optionally use the parent's ringtones
2472 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2473 String defaultSyncParentSounds = (getContext().getResources()
2474 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
2475 systemSecureSettings.insertSettingLocked(
2476 Settings.Secure.SYNC_PARENT_SOUNDS,
2477 defaultSyncParentSounds,
2478 SettingsState.SYSTEM_PACKAGE_NAME);
2479 currentVersion = 132;
2480 }
2481
Keun-young Parkec7a1182016-10-18 11:52:38 -07002482 if (currentVersion == 132) {
2483 // Version 132: Add default end button behavior
2484 final SettingsState systemSettings = getSystemSettingsLocked(userId);
2485 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
2486 null) {
2487 String defaultEndButtonBehavior = Integer.toString(getContext()
2488 .getResources().getInteger(R.integer.def_end_button_behavior));
2489 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
2490 defaultEndButtonBehavior, SettingsState.SYSTEM_PACKAGE_NAME);
2491 }
2492 currentVersion = 133;
2493 }
2494
Dan Sandler71f85e92016-07-20 13:46:05 -04002495 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002496 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04002497 + newVersion + " left it at "
2498 + currentVersion + " instead; this is probably a bug", new Throwable());
2499 if (DEBUG) {
2500 throw new RuntimeException("db upgrade error");
2501 }
2502 }
2503
Jeff Brown503cffc2015-03-26 18:08:51 -07002504 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002505
Jeff Brown503cffc2015-03-26 18:08:51 -07002506 // Return the current version.
2507 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002508 }
2509 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002510 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002511}