blob: 22cda0a600906f3338e9a139bb672a02a55f8e5f [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;
Svetoslav683914b2015-01-15 14:22:26 -080061import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070062import android.util.Slog;
63import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040064
Svetoslav683914b2015-01-15 14:22:26 -080065import com.android.internal.annotations.GuardedBy;
66import com.android.internal.content.PackageMonitor;
67import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080068import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070069import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080070import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040071
Svetoslav683914b2015-01-15 14:22:26 -080072import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080073import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080074import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080075import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080076import java.security.SecureRandom;
77import java.util.Arrays;
78import java.util.List;
Svetoslav683914b2015-01-15 14:22:26 -080079import java.util.Set;
80import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070081
Svetoslav683914b2015-01-15 14:22:26 -080082/**
83 * <p>
84 * This class is a content provider that publishes the system settings.
85 * It can be accessed via the content provider APIs or via custom call
86 * commands. The latter is a bit faster and is the preferred way to access
87 * the platform settings.
88 * </p>
89 * <p>
90 * There are three settings types, global (with signature level protection
91 * and shared across users), secure (with signature permission level
92 * protection and per user), and system (with dangerous permission level
93 * protection and per user). Global settings are stored under the device owner.
94 * Each of these settings is represented by a {@link
95 * com.android.providers.settings.SettingsState} object mapped to an integer
96 * key derived from the setting type in the most significant bits and user
97 * id in the least significant bits. Settings are synchronously loaded on
98 * instantiation of a SettingsState and asynchronously persisted on mutation.
99 * Settings are stored in the user specific system directory.
100 * </p>
101 * <p>
102 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
103 * and get a warning. Targeting higher API version prohibits this as the
104 * system settings are not a place for apps to save their state. When a package
105 * is removed the settings it added are deleted. Apps cannot delete system
106 * settings added by the platform. System settings values are validated to
107 * ensure the clients do not put bad values. Global and secure settings are
108 * changed only by trusted parties, therefore no validation is performed. Also
109 * there is a limit on the amount of app specific settings that can be added
110 * to prevent unlimited growth of the system process memory footprint.
111 * </p>
112 */
113@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800115 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116
Svetoslav683914b2015-01-15 14:22:26 -0800117 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
118
119 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700120
Christopher Tate06efb532012-08-24 15:29:27 -0700121 private static final String TABLE_SYSTEM = "system";
122 private static final String TABLE_SECURE = "secure";
123 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800124
125 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final String TABLE_FAVORITES = "favorites";
127 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800128 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
129 private static final String TABLE_BOOKMARKS = "bookmarks";
130 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Svetoslav683914b2015-01-15 14:22:26 -0800132 // The set of removed legacy tables.
133 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700134 static {
Svetoslav683914b2015-01-15 14:22:26 -0800135 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
136 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
137 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
138 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
139 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
140 }
Christopher Tate06efb532012-08-24 15:29:27 -0700141
Svetoslav683914b2015-01-15 14:22:26 -0800142 private static final int MUTATION_OPERATION_INSERT = 1;
143 private static final int MUTATION_OPERATION_DELETE = 2;
144 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400145
Svetoslav683914b2015-01-15 14:22:26 -0800146 private static final String[] ALL_COLUMNS = new String[] {
147 Settings.NameValueTable._ID,
148 Settings.NameValueTable.NAME,
149 Settings.NameValueTable.VALUE
150 };
151
Svet Ganov53a441c2016-04-19 19:38:00 -0700152 public static final int SETTINGS_TYPE_GLOBAL = 0;
153 public static final int SETTINGS_TYPE_SYSTEM = 1;
154 public static final int SETTINGS_TYPE_SECURE = 2;
Svetoslav683914b2015-01-15 14:22:26 -0800155
Svet Ganov53a441c2016-04-19 19:38:00 -0700156 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
157 public static final int SETTINGS_TYPE_SHIFT = 28;
158
159 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
160 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700161
Svetoslav683914b2015-01-15 14:22:26 -0800162 // Per user secure settings that moved to the for all users global settings.
163 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
164 static {
165 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700166 }
167
Svetoslav683914b2015-01-15 14:22:26 -0800168 // Per user system settings that moved to the for all users global settings.
169 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
170 static {
171 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172 }
173
Svetoslav683914b2015-01-15 14:22:26 -0800174 // Per user system settings that moved to the per user secure settings.
175 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
176 static {
177 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 }
179
Svetoslav683914b2015-01-15 14:22:26 -0800180 // Per all users global settings that moved to the per user secure settings.
181 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
182 static {
183 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700184 }
185
Svetoslav683914b2015-01-15 14:22:26 -0800186 // Per user secure settings that are cloned for the managed profiles of the user.
187 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
188 static {
189 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700190 }
191
Svetoslav683914b2015-01-15 14:22:26 -0800192 // Per user system settings that are cloned for the managed profiles of the user.
193 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
194 static {
195 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400196 }
197
Svetoslav683914b2015-01-15 14:22:26 -0800198 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700199
Svetoslav683914b2015-01-15 14:22:26 -0800200 @GuardedBy("mLock")
201 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700202
Svet Ganova8f90262016-05-10 08:44:48 -0700203 @GuardedBy("mLock")
204 private HandlerThread mHandlerThread;
205
Svetoslav7ec28e82015-05-20 17:01:10 -0700206 // We have to call in the user manager with no lock held,
207 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800208
Svetoslav7ec28e82015-05-20 17:01:10 -0700209 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700210 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700211
Svet Ganov53a441c2016-04-19 19:38:00 -0700212 public static int makeKey(int type, int userId) {
213 return (type << SETTINGS_TYPE_SHIFT) | userId;
214 }
215
216 public static int getTypeFromKey(int key) {
217 return key >>> SETTINGS_TYPE_SHIFT;
218 }
219
220 public static int getUserIdFromKey(int key) {
221 return key & ~SETTINGS_TYPE_MASK;
222 }
223
224 public static String settingTypeToString(int type) {
225 switch (type) {
226 case SETTINGS_TYPE_GLOBAL: {
227 return "SETTINGS_GLOBAL";
228 }
229 case SETTINGS_TYPE_SECURE: {
230 return "SETTINGS_SECURE";
231 }
232 case SETTINGS_TYPE_SYSTEM: {
233 return "SETTINGS_SYSTEM";
234 }
235 default: {
236 return "UNKNOWN";
237 }
238 }
239 }
240
241 public static String keyToString(int key) {
242 return "Key[user=" + getUserIdFromKey(key) + ";type="
243 + settingTypeToString(getTypeFromKey(key)) + "]";
244 }
245
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 @Override
247 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800248 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700249 mUserManager = UserManager.get(getContext());
250 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700251 mHandlerThread = new HandlerThread(LOG_TAG,
252 Process.THREAD_PRIORITY_BACKGROUND);
253 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800254 mSettingsRegistry = new SettingsRegistry();
255 }
256 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700257 startWatchingUserRestrictionChanges();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 return true;
259 }
260
Svetoslav683914b2015-01-15 14:22:26 -0800261 @Override
262 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700263 final int requestingUserId = getRequestingUserId(args);
264 switch (method) {
265 case Settings.CALL_METHOD_GET_GLOBAL: {
266 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700267 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800268 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700269
270 case Settings.CALL_METHOD_GET_SECURE: {
271 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700272 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700273 }
274
275 case Settings.CALL_METHOD_GET_SYSTEM: {
276 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700277 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700278 }
279
280 case Settings.CALL_METHOD_PUT_GLOBAL: {
281 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700282 insertGlobalSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700283 break;
284 }
285
286 case Settings.CALL_METHOD_PUT_SECURE: {
287 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700288 insertSecureSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700289 break;
290 }
291
292 case Settings.CALL_METHOD_PUT_SYSTEM: {
293 String value = getSettingValue(args);
294 insertSystemSetting(name, value, requestingUserId);
295 break;
296 }
297
298 default: {
299 Slog.w(LOG_TAG, "call() with invalid method: " + method);
300 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700301 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700302
Christopher Tate06efb532012-08-24 15:29:27 -0700303 return null;
304 }
305
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800306 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800307 public String getType(Uri uri) {
308 Arguments args = new Arguments(uri, null, null, true);
309 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 return "vnd.android.cursor.dir/" + args.table;
311 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700312 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700313 }
314 }
315
316 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800317 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
318 String order) {
319 if (DEBUG) {
320 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 }
322
Svetoslav683914b2015-01-15 14:22:26 -0800323 Arguments args = new Arguments(uri, where, whereArgs, true);
324 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325
Svetoslav683914b2015-01-15 14:22:26 -0800326 // If a legacy table that is gone, done.
327 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
328 return new MatrixCursor(normalizedProjection, 0);
329 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700330
Svetoslav7ec28e82015-05-20 17:01:10 -0700331 switch (args.table) {
332 case TABLE_GLOBAL: {
333 if (args.name != null) {
334 Setting setting = getGlobalSetting(args.name);
335 return packageSettingForQuery(setting, normalizedProjection);
336 } else {
337 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700338 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700339 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700340
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 case TABLE_SECURE: {
342 final int userId = UserHandle.getCallingUserId();
343 if (args.name != null) {
344 Setting setting = getSecureSetting(args.name, userId);
345 return packageSettingForQuery(setting, normalizedProjection);
346 } else {
347 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800348 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700349 }
Svetoslav683914b2015-01-15 14:22:26 -0800350
Svetoslav7ec28e82015-05-20 17:01:10 -0700351 case TABLE_SYSTEM: {
352 final int userId = UserHandle.getCallingUserId();
353 if (args.name != null) {
354 Setting setting = getSystemSetting(args.name, userId);
355 return packageSettingForQuery(setting, normalizedProjection);
356 } else {
357 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800358 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700359 }
Svetoslav683914b2015-01-15 14:22:26 -0800360
Svetoslav7ec28e82015-05-20 17:01:10 -0700361 default: {
362 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700363 }
364 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700365 }
366
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800368 public Uri insert(Uri uri, ContentValues values) {
369 if (DEBUG) {
370 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700371 }
372
Svetoslav683914b2015-01-15 14:22:26 -0800373 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700374
Svetoslav683914b2015-01-15 14:22:26 -0800375 // If a legacy table that is gone, done.
376 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 return null;
378 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379
Svetoslav683914b2015-01-15 14:22:26 -0800380 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700381 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800382 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700383 }
384
Svetoslav683914b2015-01-15 14:22:26 -0800385 String value = values.getAsString(Settings.Secure.VALUE);
386
Svetoslav7ec28e82015-05-20 17:01:10 -0700387 switch (table) {
388 case TABLE_GLOBAL: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700389 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700390 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700391 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700392 } break;
393
394 case TABLE_SECURE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700395 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
397 }
398 } break;
399
400 case TABLE_SYSTEM: {
401 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
402 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
403 }
404 } break;
405
406 default: {
407 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700408 }
409 }
410
Svetoslav683914b2015-01-15 14:22:26 -0800411 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700412 }
413
414 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800415 public int bulkInsert(Uri uri, ContentValues[] allValues) {
416 if (DEBUG) {
417 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700419
Svetoslav683914b2015-01-15 14:22:26 -0800420 int insertionCount = 0;
421 final int valuesCount = allValues.length;
422 for (int i = 0; i < valuesCount; i++) {
423 ContentValues values = allValues[i];
424 if (insert(uri, values) != null) {
425 insertionCount++;
426 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700427 }
Svetoslav683914b2015-01-15 14:22:26 -0800428
429 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430 }
431
432 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800433 public int delete(Uri uri, String where, String[] whereArgs) {
434 if (DEBUG) {
435 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700437
Svetoslav683914b2015-01-15 14:22:26 -0800438 Arguments args = new Arguments(uri, where, whereArgs, false);
439
440 // If a legacy table that is gone, done.
441 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
442 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700443 }
Svetoslav683914b2015-01-15 14:22:26 -0800444
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700445 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800446 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700447 }
Svetoslav683914b2015-01-15 14:22:26 -0800448
Svetoslav7ec28e82015-05-20 17:01:10 -0700449 switch (args.table) {
450 case TABLE_GLOBAL: {
451 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700452 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 }
Svetoslav683914b2015-01-15 14:22:26 -0800454
Svetoslav7ec28e82015-05-20 17:01:10 -0700455 case TABLE_SECURE: {
456 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700457 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700458 }
Svetoslav683914b2015-01-15 14:22:26 -0800459
Svetoslav7ec28e82015-05-20 17:01:10 -0700460 case TABLE_SYSTEM: {
461 final int userId = UserHandle.getCallingUserId();
462 return deleteSystemSetting(args.name, userId) ? 1 : 0;
463 }
464
465 default: {
466 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800467 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700468 }
Svetoslav683914b2015-01-15 14:22:26 -0800469 }
470
471 @Override
472 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
473 if (DEBUG) {
474 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700475 }
Svetoslav683914b2015-01-15 14:22:26 -0800476
477 Arguments args = new Arguments(uri, where, whereArgs, false);
478
479 // If a legacy table that is gone, done.
480 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
481 return 0;
482 }
483
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700484 String name = values.getAsString(Settings.Secure.NAME);
485 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800486 return 0;
487 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700488 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800489
Svetoslav7ec28e82015-05-20 17:01:10 -0700490 switch (args.table) {
491 case TABLE_GLOBAL: {
492 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700493 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700494 }
Svetoslav683914b2015-01-15 14:22:26 -0800495
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 case TABLE_SECURE: {
497 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700498 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700499 }
Svetoslav683914b2015-01-15 14:22:26 -0800500
Svetoslav7ec28e82015-05-20 17:01:10 -0700501 case TABLE_SYSTEM: {
502 final int userId = UserHandle.getCallingUserId();
503 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
504 }
Svetoslav683914b2015-01-15 14:22:26 -0800505
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 default: {
507 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800508 }
509 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700510 }
511
512 @Override
513 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100514 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
515 if (userId != UserHandle.getCallingUserId()) {
516 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
517 "Access files from the settings of another user");
518 }
519 uri = ContentProvider.getUriWithoutUserId(uri);
520
Jeff Sharkey413573a2016-02-22 17:52:45 -0700521 final String cacheName;
522 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
523 cacheName = Settings.System.RINGTONE_CACHE;
524 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
525 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
526 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
527 cacheName = Settings.System.ALARM_ALERT_CACHE;
528 } else {
529 throw new FileNotFoundException("Direct file access no longer supported; "
530 + "ringtone playback is available through android.media.Ringtone");
531 }
532
Robin Lee2ab02e22016-07-28 18:41:23 +0100533 final File cacheFile = new File(getRingtoneCacheDir(userId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700534 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
535 }
536
537 private File getRingtoneCacheDir(int userId) {
538 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
539 cacheDir.mkdir();
540 SELinux.restorecon(cacheDir);
541 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700542 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800543
Svetoslavb505ccc2015-02-17 12:41:04 -0800544 @Override
545 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
546 synchronized (mLock) {
547 final long identity = Binder.clearCallingIdentity();
548 try {
549 List<UserInfo> users = mUserManager.getUsers(true);
550 final int userCount = users.size();
551 for (int i = 0; i < userCount; i++) {
552 UserInfo user = users.get(i);
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700553 dumpForUserLocked(user.id, pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800554 }
555 } finally {
556 Binder.restoreCallingIdentity(identity);
557 }
558 }
559 }
560
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700561 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700562 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800563 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700564 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800565 dumpSettings(globalCursor, pw);
566 pw.println();
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700567
568 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
569 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
570 globalSettings.dumpHistoricalOperations(pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800571 }
572
573 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700574 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800575 dumpSettings(secureCursor, pw);
576 pw.println();
577
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700578 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
579 SETTINGS_TYPE_SECURE, userId);
580 secureSettings.dumpHistoricalOperations(pw);
581
Svetoslavb505ccc2015-02-17 12:41:04 -0800582 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700583 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800584 dumpSettings(systemCursor, pw);
585 pw.println();
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700586
587 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
588 SETTINGS_TYPE_SYSTEM, userId);
589 systemSettings.dumpHistoricalOperations(pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800590 }
591
592 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700593 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800594 return;
595 }
596
597 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
598 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
599 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
600
601 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700602 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
603 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
604 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800605 pw.println();
606 } while (cursor.moveToNext());
607 }
608
Svetoslav7e0683b2015-08-03 16:02:52 -0700609 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700610 if (s != null) {
611 return s;
612 }
613 return "{null}";
614 }
615
Svetoslav683914b2015-01-15 14:22:26 -0800616 private void registerBroadcastReceivers() {
617 IntentFilter userFilter = new IntentFilter();
618 userFilter.addAction(Intent.ACTION_USER_REMOVED);
619 userFilter.addAction(Intent.ACTION_USER_STOPPED);
620
621 getContext().registerReceiver(new BroadcastReceiver() {
622 @Override
623 public void onReceive(Context context, Intent intent) {
624 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700625 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800626
627 switch (intent.getAction()) {
628 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700629 synchronized (mLock) {
630 mSettingsRegistry.removeUserStateLocked(userId, true);
631 }
Svetoslav683914b2015-01-15 14:22:26 -0800632 } break;
633
634 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700635 synchronized (mLock) {
636 mSettingsRegistry.removeUserStateLocked(userId, false);
637 }
Svetoslav683914b2015-01-15 14:22:26 -0800638 } break;
639 }
640 }
641 }, userFilter);
642
643 PackageMonitor monitor = new PackageMonitor() {
644 @Override
645 public void onPackageRemoved(String packageName, int uid) {
646 synchronized (mLock) {
647 mSettingsRegistry.onPackageRemovedLocked(packageName,
648 UserHandle.getUserId(uid));
649 }
650 }
651 };
652
653 // package changes
654 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
655 UserHandle.ALL, true);
656 }
657
Svet Ganov53a441c2016-04-19 19:38:00 -0700658 private void startWatchingUserRestrictionChanges() {
659 // TODO: The current design of settings looking different based on user restrictions
660 // should be reworked to keep them separate and system code should check the setting
661 // first followed by checking the user restriction before performing an operation.
662 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
663 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
664 Bundle prevRestrictions) -> {
665 // We are changing the settings affected by restrictions to their current
666 // value with a forced update to ensure that all cross profile dependencies
667 // are taken into account. Also make sure the settings update to.. the same
668 // value passes the security checks, so clear binder calling id.
669 if (newRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)
670 != prevRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)) {
671 final long identity = Binder.clearCallingIdentity();
672 try {
673 synchronized (mLock) {
674 Setting setting = getSecureSetting(
675 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
676 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
677 setting != null ? setting.getValue() : null, userId, true);
678 }
679 } finally {
680 Binder.restoreCallingIdentity(identity);
681 }
682 }
683 if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
684 != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
685 final long identity = Binder.clearCallingIdentity();
686 try {
687 synchronized (mLock) {
688 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
689 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
690 setting != null ? setting.getValue() : null, userId, true);
691 }
692 } finally {
693 Binder.restoreCallingIdentity(identity);
694 }
695 }
696 if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
697 != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
698 final long identity = Binder.clearCallingIdentity();
699 try {
700 synchronized (mLock) {
701 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
702 updateGlobalSetting(Settings.Global.ADB_ENABLED,
703 setting != null ? setting.getValue() : null, userId, true);
704 }
705 } finally {
706 Binder.restoreCallingIdentity(identity);
707 }
708 }
709 if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
710 != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
711 final long identity = Binder.clearCallingIdentity();
712 try {
713 synchronized (mLock) {
714 Setting enable = getGlobalSetting(
715 Settings.Global.PACKAGE_VERIFIER_ENABLE);
716 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
717 enable != null ? enable.getValue() : null, userId, true);
718 Setting include = getGlobalSetting(
719 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
720 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
721 include != null ? include.getValue() : null, userId, true);
722 }
723 } finally {
724 Binder.restoreCallingIdentity(identity);
725 }
726 }
727 if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
728 != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
729 final long identity = Binder.clearCallingIdentity();
730 try {
731 synchronized (mLock) {
732 Setting setting = getGlobalSetting(
733 Settings.Global.PREFERRED_NETWORK_MODE);
734 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
735 setting != null ? setting.getValue() : null, userId, true);
736 }
737 } finally {
738 Binder.restoreCallingIdentity(identity);
739 }
740 }
741 });
742 }
743
Svetoslav7ec28e82015-05-20 17:01:10 -0700744 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800745 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700746 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800747 }
748
Svetoslav7ec28e82015-05-20 17:01:10 -0700749 synchronized (mLock) {
750 // Get the settings.
751 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700752 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800753
Svetoslav7ec28e82015-05-20 17:01:10 -0700754 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800755
Svetoslav7ec28e82015-05-20 17:01:10 -0700756 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800757
Svetoslav7ec28e82015-05-20 17:01:10 -0700758 String[] normalizedProjection = normalizeProjection(projection);
759 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800760
Svetoslav7ec28e82015-05-20 17:01:10 -0700761 // Anyone can get the global settings, so no security checks.
762 for (int i = 0; i < nameCount; i++) {
763 String name = names.get(i);
764 Setting setting = settingsState.getSettingLocked(name);
765 appendSettingToCursor(result, setting);
766 }
767
768 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800769 }
Svetoslav683914b2015-01-15 14:22:26 -0800770 }
771
Svetoslav7ec28e82015-05-20 17:01:10 -0700772 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800773 if (DEBUG) {
774 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
775 }
776
777 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700778 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700779 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700780 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800781 }
Svetoslav683914b2015-01-15 14:22:26 -0800782 }
783
Svet Ganov53a441c2016-04-19 19:38:00 -0700784 private boolean updateGlobalSetting(String name, String value, int requestingUserId,
785 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800786 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700787 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800788 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700789 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
790 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800791 }
792
Svet Ganov53a441c2016-04-19 19:38:00 -0700793 private boolean insertGlobalSetting(String name, String value, int requestingUserId,
794 boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700795 if (DEBUG) {
796 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
797 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700798 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
799 forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700800 }
801
Svet Ganov53a441c2016-04-19 19:38:00 -0700802 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800803 if (DEBUG) {
804 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
805 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700806 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
807 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800808 }
809
Svetoslav7ec28e82015-05-20 17:01:10 -0700810 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700811 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800812 // Make sure the caller can change the settings - treated as secure.
813 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
814
Svetoslav683914b2015-01-15 14:22:26 -0800815 // Resolve the userId on whose behalf the call is made.
816 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
817
Makoto Onuki28da2e32015-11-20 11:30:44 -0800818 // If this is a setting that is currently restricted for this user, do not allow
819 // unrestricting changes.
Victor Chang9c7b7062016-07-12 23:47:29 +0100820 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
821 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800822 return false;
823 }
824
825 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700826 synchronized (mLock) {
827 switch (operation) {
828 case MUTATION_OPERATION_INSERT: {
829 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700830 .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
831 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700832 }
Svetoslav683914b2015-01-15 14:22:26 -0800833
Svetoslav7ec28e82015-05-20 17:01:10 -0700834 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700835 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
836 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700837 }
Svetoslav683914b2015-01-15 14:22:26 -0800838
Svetoslav7ec28e82015-05-20 17:01:10 -0700839 case MUTATION_OPERATION_UPDATE: {
840 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700841 .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
842 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700843 }
Svetoslav683914b2015-01-15 14:22:26 -0800844 }
845 }
846
847 return false;
848 }
849
Svetoslav7ec28e82015-05-20 17:01:10 -0700850 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800851 if (DEBUG) {
852 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
853 }
854
855 // Resolve the userId on whose behalf the call is made.
856 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
857
Svetoslav7ec28e82015-05-20 17:01:10 -0700858 synchronized (mLock) {
859 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700860 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800861
Svetoslav7ec28e82015-05-20 17:01:10 -0700862 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800863
Svetoslav7ec28e82015-05-20 17:01:10 -0700864 String[] normalizedProjection = normalizeProjection(projection);
865 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800866
Svetoslav7ec28e82015-05-20 17:01:10 -0700867 for (int i = 0; i < nameCount; i++) {
868 String name = names.get(i);
869 // Determine the owning user as some profile settings are cloned from the parent.
870 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
871 name);
Svetoslav683914b2015-01-15 14:22:26 -0800872
Svetoslav7ec28e82015-05-20 17:01:10 -0700873 // Special case for location (sigh).
874 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700875 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700876 }
Svetoslav683914b2015-01-15 14:22:26 -0800877
Svetoslav7ec28e82015-05-20 17:01:10 -0700878 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700879 SETTINGS_TYPE_SECURE, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800881 }
882
Svetoslav7ec28e82015-05-20 17:01:10 -0700883 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800884 }
Svetoslav683914b2015-01-15 14:22:26 -0800885 }
886
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800888 if (DEBUG) {
889 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
890 }
891
892 // Resolve the userId on whose behalf the call is made.
893 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
894
895 // Determine the owning user as some profile settings are cloned from the parent.
896 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
897
898 // Special case for location (sigh).
899 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700900 return mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
901 owningUserId).getNullSetting();
Svetoslav683914b2015-01-15 14:22:26 -0800902 }
903
904 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700905 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700906 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -0700907 owningUserId, name);
908 }
Svetoslav683914b2015-01-15 14:22:26 -0800909 }
910
Svet Ganov53a441c2016-04-19 19:38:00 -0700911 private boolean insertSecureSetting(String name, String value, int requestingUserId,
912 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800913 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700914 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800915 + requestingUserId + ")");
916 }
917
Svet Ganov53a441c2016-04-19 19:38:00 -0700918 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
919 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800920 }
921
Svet Ganov53a441c2016-04-19 19:38:00 -0700922 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800923 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800925 }
926
Svet Ganov53a441c2016-04-19 19:38:00 -0700927 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
928 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800929 }
930
Svet Ganov53a441c2016-04-19 19:38:00 -0700931 private boolean updateSecureSetting(String name, String value, int requestingUserId,
932 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800933 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700934 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800935 + requestingUserId + ")");
936 }
937
Svet Ganov53a441c2016-04-19 19:38:00 -0700938 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
939 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800940 }
941
Svetoslav7ec28e82015-05-20 17:01:10 -0700942 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700943 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800944 // Make sure the caller can change the settings.
945 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
946
Svetoslav683914b2015-01-15 14:22:26 -0800947 // Resolve the userId on whose behalf the call is made.
948 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
949
Makoto Onuki28da2e32015-11-20 11:30:44 -0800950 // If this is a setting that is currently restricted for this user, do not allow
951 // unrestricting changes.
Victor Chang9c7b7062016-07-12 23:47:29 +0100952 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
953 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800954 return false;
955 }
956
957 // Determine the owning user as some profile settings are cloned from the parent.
958 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
959
960 // Only the owning user can change the setting.
961 if (owningUserId != callingUserId) {
962 return false;
963 }
964
965 // Special cases for location providers (sigh).
966 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700967 return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800968 }
969
970 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700971 synchronized (mLock) {
972 switch (operation) {
973 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700974 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
975 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700976 }
Svetoslav683914b2015-01-15 14:22:26 -0800977
Svetoslav7ec28e82015-05-20 17:01:10 -0700978 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700979 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
980 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700981 }
Svetoslav683914b2015-01-15 14:22:26 -0800982
Svetoslav7ec28e82015-05-20 17:01:10 -0700983 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700984 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
985 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700986 }
Svetoslav683914b2015-01-15 14:22:26 -0800987 }
988 }
989
990 return false;
991 }
992
Svetoslav7ec28e82015-05-20 17:01:10 -0700993 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800994 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700995 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800996 }
997
998 // Resolve the userId on whose behalf the call is made.
999 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1000
Svetoslav7ec28e82015-05-20 17:01:10 -07001001 synchronized (mLock) {
1002 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001003 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001004
Svetoslav7ec28e82015-05-20 17:01:10 -07001005 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001006
Svetoslav7ec28e82015-05-20 17:01:10 -07001007 String[] normalizedProjection = normalizeProjection(projection);
1008 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001009
Svetoslav7ec28e82015-05-20 17:01:10 -07001010 for (int i = 0; i < nameCount; i++) {
1011 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001012
Svetoslav7ec28e82015-05-20 17:01:10 -07001013 // Determine the owning user as some profile settings are cloned from the parent.
1014 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1015 name);
Svetoslav683914b2015-01-15 14:22:26 -08001016
Svetoslav7ec28e82015-05-20 17:01:10 -07001017 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001018 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001019 appendSettingToCursor(result, setting);
1020 }
1021
1022 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001023 }
Svetoslav683914b2015-01-15 14:22:26 -08001024 }
1025
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001027 if (DEBUG) {
1028 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1029 }
1030
1031 // Resolve the userId on whose behalf the call is made.
1032 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1033
1034 // Determine the owning user as some profile settings are cloned from the parent.
1035 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1036
1037 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001039 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001040 }
Svetoslav683914b2015-01-15 14:22:26 -08001041 }
1042
Svetoslav7ec28e82015-05-20 17:01:10 -07001043 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001044 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001045 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001046 + requestingUserId + ")");
1047 }
1048
Svetoslav7ec28e82015-05-20 17:01:10 -07001049 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001050 }
1051
Svetoslav7ec28e82015-05-20 17:01:10 -07001052 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001053 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001054 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001055 }
1056
Svetoslav7ec28e82015-05-20 17:01:10 -07001057 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001058 }
1059
Svetoslav7ec28e82015-05-20 17:01:10 -07001060 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001061 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001062 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001063 + requestingUserId + ")");
1064 }
1065
Svetoslav7ec28e82015-05-20 17:01:10 -07001066 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001067 }
1068
Svetoslav7ec28e82015-05-20 17:01:10 -07001069 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001070 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001071 if (!hasWriteSecureSettingsPermission()) {
1072 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1073 // operation is allowed for the calling package through appops.
1074 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1075 Binder.getCallingUid(), getCallingPackage(), true)) {
1076 return false;
1077 }
Svetoslav683914b2015-01-15 14:22:26 -08001078 }
1079
Svetoslav683914b2015-01-15 14:22:26 -08001080 // Resolve the userId on whose behalf the call is made.
1081 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1082
Svetoslavd8d25e02015-11-20 13:09:26 -08001083 // Enforce what the calling package can mutate the system settings.
1084 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1085
Svetoslav683914b2015-01-15 14:22:26 -08001086 // Determine the owning user as some profile settings are cloned from the parent.
1087 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1088
1089 // Only the owning user id can change the setting.
1090 if (owningUserId != callingUserId) {
1091 return false;
1092 }
1093
Jeff Sharkey413573a2016-02-22 17:52:45 -07001094 // Invalidate any relevant cache files
1095 String cacheName = null;
1096 if (Settings.System.RINGTONE.equals(name)) {
1097 cacheName = Settings.System.RINGTONE_CACHE;
1098 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1099 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1100 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1101 cacheName = Settings.System.ALARM_ALERT_CACHE;
1102 }
1103 if (cacheName != null) {
1104 final File cacheFile = new File(
1105 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
1106 cacheFile.delete();
1107 }
1108
Svetoslav683914b2015-01-15 14:22:26 -08001109 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001110 synchronized (mLock) {
1111 switch (operation) {
1112 case MUTATION_OPERATION_INSERT: {
1113 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001114 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
1115 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001116 }
1117
1118 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001119 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1120 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001121 }
1122
1123 case MUTATION_OPERATION_UPDATE: {
1124 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001125 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1126 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001127 }
Svetoslav683914b2015-01-15 14:22:26 -08001128 }
1129
Svetoslav7ec28e82015-05-20 17:01:10 -07001130 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001131 }
Svetoslav683914b2015-01-15 14:22:26 -08001132 }
1133
Billy Lau6ad2d662015-07-18 00:26:58 +01001134 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001135 // Write secure settings is a more protected permission. If caller has it we are good.
1136 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1137 == PackageManager.PERMISSION_GRANTED) {
1138 return true;
1139 }
1140
Svetoslavf41334b2015-06-23 12:06:03 -07001141 return false;
1142 }
1143
Svetoslav683914b2015-01-15 14:22:26 -08001144 private void validateSystemSettingValue(String name, String value) {
1145 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1146 if (validator != null && !validator.validate(value)) {
1147 throw new IllegalArgumentException("Invalid value: " + value
1148 + " for setting: " + name);
1149 }
1150 }
1151
1152 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1153 int owningUserId) {
1154 // Optimization - location providers are restricted only for managed profiles.
1155 if (callingUserId == owningUserId) {
1156 return false;
1157 }
1158 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1159 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1160 new UserHandle(callingUserId))) {
1161 return true;
1162 }
1163 return false;
1164 }
1165
Makoto Onuki28da2e32015-11-20 11:30:44 -08001166 /**
1167 * Checks whether changing a setting to a value is prohibited by the corresponding user
1168 * restriction.
1169 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001170 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1171 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001172 *
1173 * @return true if the change is prohibited, false if the change is allowed.
1174 */
1175 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001176 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001177 String restriction;
1178 switch (setting) {
1179 case Settings.Secure.LOCATION_MODE:
1180 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1181 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1182 // here normally, but we still protect it here from a direct provider write.
1183 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1184 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1185 break;
1186
1187 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1188 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1189 // a provider, which should be allowed even if the user restriction is set.
1190 if (value != null && value.startsWith("-")) return false;
1191 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1192 break;
1193
1194 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1195 if ("0".equals(value)) return false;
1196 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1197 break;
1198
1199 case Settings.Global.ADB_ENABLED:
1200 if ("0".equals(value)) return false;
1201 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1202 break;
1203
1204 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1205 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1206 if ("1".equals(value)) return false;
1207 restriction = UserManager.ENSURE_VERIFY_APPS;
1208 break;
1209
1210 case Settings.Global.PREFERRED_NETWORK_MODE:
1211 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1212 break;
1213
Victor Chang9c7b7062016-07-12 23:47:29 +01001214 case Settings.Secure.ALWAYS_ON_VPN_APP:
1215 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1216 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
1217 if (callingUid == Process.SYSTEM_UID || callingUid == Process.ROOT_UID) {
1218 return false;
1219 }
1220 restriction = UserManager.DISALLOW_CONFIG_VPN;
1221 break;
1222
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001223 case Settings.Global.SAFE_BOOT_DISALLOWED:
1224 if ("1".equals(value)) return false;
1225 restriction = UserManager.DISALLOW_SAFE_BOOT;
1226 break;
1227
Makoto Onuki28da2e32015-11-20 11:30:44 -08001228 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001229 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001230 if ("0".equals(value)) return false;
1231 restriction = UserManager.DISALLOW_DATA_ROAMING;
1232 break;
1233 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001234 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001235 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001236
1237 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001238 }
1239
1240 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1241 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1242 }
1243
1244 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1245 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1246 }
1247
1248 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1249 final int parentId = getGroupParentLocked(userId);
1250 if (parentId != userId && keys.contains(name)) {
1251 return parentId;
1252 }
1253 return userId;
1254 }
1255
Svetoslavf41334b2015-06-23 12:06:03 -07001256 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001257 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001258 // System/root/shell can mutate whatever secure settings they want.
1259 final int callingUid = Binder.getCallingUid();
1260 if (callingUid == android.os.Process.SYSTEM_UID
1261 || callingUid == Process.SHELL_UID
1262 || callingUid == Process.ROOT_UID) {
1263 return;
1264 }
1265
1266 switch (operation) {
1267 case MUTATION_OPERATION_INSERT:
1268 // Insert updates.
1269 case MUTATION_OPERATION_UPDATE: {
1270 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1271 return;
1272 }
1273
1274 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001275 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001276
1277 // Privileged apps can do whatever they want.
1278 if ((packageInfo.applicationInfo.privateFlags
1279 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1280 return;
1281 }
1282
1283 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1284 packageInfo.applicationInfo.targetSdkVersion, name);
1285 } break;
1286
1287 case MUTATION_OPERATION_DELETE: {
1288 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1289 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1290 throw new IllegalArgumentException("You cannot delete system defined"
1291 + " secure settings.");
1292 }
1293
1294 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001295 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001296
1297 // Privileged apps can do whatever they want.
1298 if ((packageInfo.applicationInfo.privateFlags &
1299 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1300 return;
1301 }
1302
1303 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1304 packageInfo.applicationInfo.targetSdkVersion, name);
1305 } break;
1306 }
1307 }
1308
Xiaohui Chen43765b72015-08-31 10:57:33 -07001309 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001310 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001311 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1312 getCallingPackage(), 0, userId);
1313 if (packageInfo != null) {
1314 return packageInfo;
1315 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001316 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001317 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001318 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001319 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001320 }
1321
1322 private int getGroupParentLocked(int userId) {
1323 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001324 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001325 return userId;
1326 }
1327 // We are in the same process with the user manager and the returned
1328 // user info is a cached instance, so just look up instead of cache.
1329 final long identity = Binder.clearCallingIdentity();
1330 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001331 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001332 UserInfo userInfo = mUserManager.getProfileParent(userId);
1333 return (userInfo != null) ? userInfo.id : userId;
1334 } finally {
1335 Binder.restoreCallingIdentity(identity);
1336 }
1337 }
1338
Svetoslav683914b2015-01-15 14:22:26 -08001339 private void enforceWritePermission(String permission) {
1340 if (getContext().checkCallingOrSelfPermission(permission)
1341 != PackageManager.PERMISSION_GRANTED) {
1342 throw new SecurityException("Permission denial: writing to settings requires:"
1343 + permission);
1344 }
1345 }
1346
1347 /*
1348 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1349 * This setting contains a list of the currently enabled location providers.
1350 * But helper functions in android.providers.Settings can enable or disable
1351 * a single provider by using a "+" or "-" prefix before the provider name.
1352 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001353 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1354 * is set, the said method will only allow values with the "-" prefix.
1355 *
Svetoslav683914b2015-01-15 14:22:26 -08001356 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001357 */
Svet Ganov53a441c2016-04-19 19:38:00 -07001358 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1359 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001360 if (TextUtils.isEmpty(value)) {
1361 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001362 }
1363
Svetoslav683914b2015-01-15 14:22:26 -08001364 final char prefix = value.charAt(0);
1365 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001366 if (forceNotify) {
1367 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1368 mSettingsRegistry.notifyForSettingsChange(key,
1369 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1370 }
Svetoslav683914b2015-01-15 14:22:26 -08001371 return false;
1372 }
1373
1374 // skip prefix
1375 value = value.substring(1);
1376
Svetoslav7ec28e82015-05-20 17:01:10 -07001377 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001378 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1379
1380 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1381
1382 int index = oldProviders.indexOf(value);
1383 int end = index + value.length();
1384
1385 // check for commas to avoid matching on partial string
1386 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1387 index = -1;
1388 }
1389
1390 // check for commas to avoid matching on partial string
1391 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1392 index = -1;
1393 }
1394
1395 String newProviders;
1396
1397 if (prefix == '+' && index < 0) {
1398 // append the provider to the list if not present
1399 if (oldProviders.length() == 0) {
1400 newProviders = value;
1401 } else {
1402 newProviders = oldProviders + ',' + value;
1403 }
1404 } else if (prefix == '-' && index >= 0) {
1405 // remove the provider from the list if present
1406 // remove leading or trailing comma
1407 if (index > 0) {
1408 index--;
1409 } else if (end < oldProviders.length()) {
1410 end++;
1411 }
1412
1413 newProviders = oldProviders.substring(0, index);
1414 if (end < oldProviders.length()) {
1415 newProviders += oldProviders.substring(end);
1416 }
1417 } else {
1418 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001419 if (forceNotify) {
1420 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1421 mSettingsRegistry.notifyForSettingsChange(key,
1422 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1423 }
Svetoslav683914b2015-01-15 14:22:26 -08001424 return false;
1425 }
1426
Svet Ganov53a441c2016-04-19 19:38:00 -07001427 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001428 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svet Ganov53a441c2016-04-19 19:38:00 -07001429 getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001430 }
1431
Svetoslav683914b2015-01-15 14:22:26 -08001432 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1433 int targetSdkVersion, String name) {
1434 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1435 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1436 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1437 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1438 + " This will soon become an error.");
1439 } else {
1440 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1441 + " This will soon become an error.");
1442 }
1443 } else {
1444 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1445 throw new IllegalArgumentException("You cannot change private secure settings.");
1446 } else {
1447 throw new IllegalArgumentException("You cannot keep your settings in"
1448 + " the secure settings.");
1449 }
1450 }
1451 }
1452
1453 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1454 if (requestingUserId == UserHandle.getCallingUserId()) {
1455 return requestingUserId;
1456 }
1457 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1458 Binder.getCallingUid(), requestingUserId, false, true,
1459 "get/set setting for user", null);
1460 }
1461
Svet Ganov53a441c2016-04-19 19:38:00 -07001462 private Bundle packageValueForCallResult(Setting setting,
1463 boolean trackingGeneration) {
1464 if (!trackingGeneration) {
1465 if (setting.isNull()) {
1466 return NULL_SETTING_BUNDLE;
1467 }
1468 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001469 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001470 Bundle result = new Bundle();
1471 result.putString(Settings.NameValueTable.VALUE,
1472 !setting.isNull() ? setting.getValue() : null);
1473 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1474 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001475 }
1476
1477 private static int getRequestingUserId(Bundle args) {
1478 final int callingUserId = UserHandle.getCallingUserId();
1479 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1480 : callingUserId;
1481 }
1482
Svet Ganov53a441c2016-04-19 19:38:00 -07001483 private boolean isTrackingGeneration(Bundle args) {
1484 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1485 }
1486
Svetoslav683914b2015-01-15 14:22:26 -08001487 private static String getSettingValue(Bundle args) {
1488 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1489 }
1490
1491 private static String getValidTableOrThrow(Uri uri) {
1492 if (uri.getPathSegments().size() > 0) {
1493 String table = uri.getPathSegments().get(0);
1494 if (DatabaseHelper.isValidTable(table)) {
1495 return table;
1496 }
1497 throw new IllegalArgumentException("Bad root path: " + table);
1498 }
1499 throw new IllegalArgumentException("Invalid URI:" + uri);
1500 }
1501
1502 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001503 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001504 return new MatrixCursor(projection, 0);
1505 }
1506 MatrixCursor cursor = new MatrixCursor(projection, 1);
1507 appendSettingToCursor(cursor, setting);
1508 return cursor;
1509 }
1510
1511 private static String[] normalizeProjection(String[] projection) {
1512 if (projection == null) {
1513 return ALL_COLUMNS;
1514 }
1515
1516 final int columnCount = projection.length;
1517 for (int i = 0; i < columnCount; i++) {
1518 String column = projection[i];
1519 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1520 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001521 }
1522 }
1523
Svetoslav683914b2015-01-15 14:22:26 -08001524 return projection;
1525 }
1526
1527 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001528 if (setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001529 return;
1530 }
Svetoslav683914b2015-01-15 14:22:26 -08001531 final int columnCount = cursor.getColumnCount();
1532
1533 String[] values = new String[columnCount];
1534
1535 for (int i = 0; i < columnCount; i++) {
1536 String column = cursor.getColumnName(i);
1537
1538 switch (column) {
1539 case Settings.NameValueTable._ID: {
1540 values[i] = setting.getId();
1541 } break;
1542
1543 case Settings.NameValueTable.NAME: {
1544 values[i] = setting.getName();
1545 } break;
1546
1547 case Settings.NameValueTable.VALUE: {
1548 values[i] = setting.getValue();
1549 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001550 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001551 }
1552
Svetoslav683914b2015-01-15 14:22:26 -08001553 cursor.addRow(values);
1554 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001555
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001556 private static boolean isKeyValid(String key) {
1557 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1558 }
1559
Svetoslav683914b2015-01-15 14:22:26 -08001560 private static final class Arguments {
1561 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1562 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1563
1564 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1565 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1566
1567 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1568 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1569
1570 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1571 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1572
1573 public final String table;
1574 public final String name;
1575
1576 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1577 final int segmentSize = uri.getPathSegments().size();
1578 switch (segmentSize) {
1579 case 1: {
1580 if (where != null
1581 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1582 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1583 && whereArgs.length == 1) {
1584 name = whereArgs[0];
1585 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001586 return;
Svetoslav683914b2015-01-15 14:22:26 -08001587 } else if (where != null
1588 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1589 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1590 final int startIndex = Math.max(where.indexOf("'"),
1591 where.indexOf("\"")) + 1;
1592 final int endIndex = Math.max(where.lastIndexOf("'"),
1593 where.lastIndexOf("\""));
1594 name = where.substring(startIndex, endIndex);
1595 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001596 return;
Svetoslav683914b2015-01-15 14:22:26 -08001597 } else if (supportAll && where == null && whereArgs == null) {
1598 name = null;
1599 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001600 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001601 }
Svetoslav683914b2015-01-15 14:22:26 -08001602 } break;
1603
Svetoslav28494652015-02-12 14:11:42 -08001604 case 2: {
1605 if (where == null && whereArgs == null) {
1606 name = uri.getPathSegments().get(1);
1607 table = computeTableForSetting(uri, name);
1608 return;
1609 }
1610 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001611 }
Svetoslav28494652015-02-12 14:11:42 -08001612
1613 EventLogTags.writeUnsupportedSettingsQuery(
1614 uri.toSafeString(), where, Arrays.toString(whereArgs));
1615 String message = String.format( "Supported SQL:\n"
1616 + " uri content://some_table/some_property with null where and where args\n"
1617 + " uri content://some_table with query name=? and single name as arg\n"
1618 + " uri content://some_table with query name=some_name and null args\n"
1619 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1620 Arrays.toString(whereArgs));
1621 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001622 }
1623
Svetoslav28494652015-02-12 14:11:42 -08001624 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001625 String table = getValidTableOrThrow(uri);
1626
1627 if (name != null) {
1628 if (sSystemMovedToSecureSettings.contains(name)) {
1629 table = TABLE_SECURE;
1630 }
1631
1632 if (sSystemMovedToGlobalSettings.contains(name)) {
1633 table = TABLE_GLOBAL;
1634 }
1635
1636 if (sSecureMovedToGlobalSettings.contains(name)) {
1637 table = TABLE_GLOBAL;
1638 }
1639
1640 if (sGlobalMovedToSecureSettings.contains(name)) {
1641 table = TABLE_SECURE;
1642 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001643 }
Svetoslav683914b2015-01-15 14:22:26 -08001644
1645 return table;
1646 }
1647 }
1648
1649 final class SettingsRegistry {
1650 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1651
Svetoslav683914b2015-01-15 14:22:26 -08001652 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1653 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1654 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1655
1656 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1657
Svet Ganov53a441c2016-04-19 19:38:00 -07001658 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001659
Svetoslav7e0683b2015-08-03 16:02:52 -07001660 private final Handler mHandler;
1661
Svet Ganov53a441c2016-04-19 19:38:00 -07001662 private final BackupManager mBackupManager;
1663
Svetoslav683914b2015-01-15 14:22:26 -08001664 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001665 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001666 mGenerationRegistry = new GenerationRegistry(mLock);
1667 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001668 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001669 }
1670
Svetoslav683914b2015-01-15 14:22:26 -08001671 public List<String> getSettingsNamesLocked(int type, int userId) {
1672 final int key = makeKey(type, userId);
1673 SettingsState settingsState = peekSettingsStateLocked(key);
1674 return settingsState.getSettingNamesLocked();
1675 }
1676
1677 public SettingsState getSettingsLocked(int type, int userId) {
1678 final int key = makeKey(type, userId);
1679 return peekSettingsStateLocked(key);
1680 }
1681
1682 public void ensureSettingsForUserLocked(int userId) {
1683 // Migrate the setting for this user if needed.
1684 migrateLegacySettingsForUserIfNeededLocked(userId);
1685
1686 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001687 if (userId == UserHandle.USER_SYSTEM) {
1688 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001689 ensureSettingsStateLocked(globalKey);
1690 }
1691
1692 // Ensure secure settings loaded.
1693 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1694 ensureSettingsStateLocked(secureKey);
1695
1696 // Make sure the secure settings have an Android id set.
1697 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1698 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1699
1700 // Ensure system settings loaded.
1701 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1702 ensureSettingsStateLocked(systemKey);
1703
1704 // Upgrade the settings to the latest version.
1705 UpgradeController upgrader = new UpgradeController(userId);
1706 upgrader.upgradeIfNeededLocked();
1707 }
1708
1709 private void ensureSettingsStateLocked(int key) {
1710 if (mSettingsStates.get(key) == null) {
1711 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1712 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
Svetoslav Ganov92057492016-05-16 12:36:43 -07001713 maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001714 mSettingsStates.put(key, settingsState);
1715 }
1716 }
1717
1718 public void removeUserStateLocked(int userId, boolean permanently) {
1719 // We always keep the global settings in memory.
1720
1721 // Nuke system settings.
1722 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1723 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1724 if (systemSettingsState != null) {
1725 if (permanently) {
1726 mSettingsStates.remove(systemKey);
1727 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001728 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001729 systemSettingsState.destroyLocked(new Runnable() {
1730 @Override
1731 public void run() {
1732 mSettingsStates.remove(systemKey);
1733 }
1734 });
1735 }
1736 }
1737
1738 // Nuke secure settings.
1739 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1740 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1741 if (secureSettingsState != null) {
1742 if (permanently) {
1743 mSettingsStates.remove(secureKey);
1744 secureSettingsState.destroyLocked(null);
1745 } else {
1746 secureSettingsState.destroyLocked(new Runnable() {
1747 @Override
1748 public void run() {
1749 mSettingsStates.remove(secureKey);
1750 }
1751 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001752 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001753 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001754
1755 // Nuke generation tracking data
1756 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001757 }
1758
Svetoslav683914b2015-01-15 14:22:26 -08001759 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001760 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001761 final int key = makeKey(type, userId);
1762
1763 SettingsState settingsState = peekSettingsStateLocked(key);
1764 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1765
Svet Ganov53a441c2016-04-19 19:38:00 -07001766 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001767 notifyForSettingsChange(key, name);
1768 }
1769 return success;
1770 }
1771
Svet Ganov53a441c2016-04-19 19:38:00 -07001772 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001773 final int key = makeKey(type, userId);
1774
1775 SettingsState settingsState = peekSettingsStateLocked(key);
1776 final boolean success = settingsState.deleteSettingLocked(name);
1777
Svet Ganov53a441c2016-04-19 19:38:00 -07001778 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001779 notifyForSettingsChange(key, name);
1780 }
1781 return success;
1782 }
1783
1784 public Setting getSettingLocked(int type, int userId, String name) {
1785 final int key = makeKey(type, userId);
1786
1787 SettingsState settingsState = peekSettingsStateLocked(key);
1788 return settingsState.getSettingLocked(name);
1789 }
1790
1791 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001792 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001793 final int key = makeKey(type, userId);
1794
1795 SettingsState settingsState = peekSettingsStateLocked(key);
1796 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1797
Svet Ganov53a441c2016-04-19 19:38:00 -07001798 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001799 notifyForSettingsChange(key, name);
1800 }
1801
1802 return success;
1803 }
1804
1805 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001806 // Global and secure settings are signature protected. Apps signed
1807 // by the platform certificate are generally not uninstalled and
1808 // the main exception is tests. We trust components signed
1809 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001810
1811 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1812 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001813 if (systemSettings != null) {
1814 systemSettings.onPackageRemovedLocked(packageName);
1815 }
Svetoslav683914b2015-01-15 14:22:26 -08001816 }
1817
1818 private SettingsState peekSettingsStateLocked(int key) {
1819 SettingsState settingsState = mSettingsStates.get(key);
1820 if (settingsState != null) {
1821 return settingsState;
1822 }
1823
1824 ensureSettingsForUserLocked(getUserIdFromKey(key));
1825 return mSettingsStates.get(key);
1826 }
1827
1828 private void migrateAllLegacySettingsIfNeeded() {
1829 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001830 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001831 File globalFile = getSettingsFile(key);
1832 if (globalFile.exists()) {
1833 return;
1834 }
1835
1836 final long identity = Binder.clearCallingIdentity();
1837 try {
1838 List<UserInfo> users = mUserManager.getUsers(true);
1839
1840 final int userCount = users.size();
1841 for (int i = 0; i < userCount; i++) {
1842 final int userId = users.get(i).id;
1843
1844 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1845 SQLiteDatabase database = dbHelper.getWritableDatabase();
1846 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1847
1848 // Upgrade to the latest version.
1849 UpgradeController upgrader = new UpgradeController(userId);
1850 upgrader.upgradeIfNeededLocked();
1851
1852 // Drop from memory if not a running user.
1853 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1854 removeUserStateLocked(userId, false);
1855 }
1856 }
1857 } finally {
1858 Binder.restoreCallingIdentity(identity);
1859 }
1860 }
1861 }
1862
1863 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1864 // Every user has secure settings and if no file we need to migrate.
1865 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1866 File secureFile = getSettingsFile(secureKey);
1867 if (secureFile.exists()) {
1868 return;
1869 }
1870
1871 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1872 SQLiteDatabase database = dbHelper.getWritableDatabase();
1873
1874 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1875 }
1876
1877 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1878 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001879 // Move over the system settings.
1880 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1881 ensureSettingsStateLocked(systemKey);
1882 SettingsState systemSettings = mSettingsStates.get(systemKey);
1883 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1884 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001885
1886 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001887 // Do this after System settings, since this is the first thing we check when deciding
1888 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001889 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1890 ensureSettingsStateLocked(secureKey);
1891 SettingsState secureSettings = mSettingsStates.get(secureKey);
1892 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1893 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1894 secureSettings.persistSyncLocked();
1895
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001896 // Move over the global settings if owner.
1897 // Do this last, since this is the first thing we check when deciding
1898 // to skip over migration from db to xml for owner user.
1899 if (userId == UserHandle.USER_SYSTEM) {
1900 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1901 ensureSettingsStateLocked(globalKey);
1902 SettingsState globalSettings = mSettingsStates.get(globalKey);
1903 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1904 globalSettings.persistSyncLocked();
1905 }
Svetoslav683914b2015-01-15 14:22:26 -08001906
1907 // Drop the database as now all is moved and persisted.
1908 if (DROP_DATABASE_ON_MIGRATION) {
1909 dbHelper.dropDatabase();
1910 } else {
1911 dbHelper.backupDatabase();
1912 }
1913 }
1914
1915 private void migrateLegacySettingsLocked(SettingsState settingsState,
1916 SQLiteDatabase database, String table) {
1917 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1918 queryBuilder.setTables(table);
1919
1920 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1921 null, null, null, null, null);
1922
1923 if (cursor == null) {
1924 return;
1925 }
1926
1927 try {
1928 if (!cursor.moveToFirst()) {
1929 return;
1930 }
1931
1932 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1933 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1934
1935 settingsState.setVersionLocked(database.getVersion());
1936
1937 while (!cursor.isAfterLast()) {
1938 String name = cursor.getString(nameColumnIdx);
1939 String value = cursor.getString(valueColumnIdx);
1940 settingsState.insertSettingLocked(name, value,
1941 SettingsState.SYSTEM_PACKAGE_NAME);
1942 cursor.moveToNext();
1943 }
1944 } finally {
1945 cursor.close();
1946 }
1947 }
1948
1949 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1950 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1951
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09001952 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001953 return;
1954 }
1955
1956 final int userId = getUserIdFromKey(secureSettings.mKey);
1957
1958 final UserInfo user;
1959 final long identity = Binder.clearCallingIdentity();
1960 try {
1961 user = mUserManager.getUserInfo(userId);
1962 } finally {
1963 Binder.restoreCallingIdentity(identity);
1964 }
1965 if (user == null) {
1966 // Can happen due to races when deleting users - treat as benign.
1967 return;
1968 }
1969
1970 String androidId = Long.toHexString(new SecureRandom().nextLong());
1971 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1972 SettingsState.SYSTEM_PACKAGE_NAME);
1973
1974 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1975 + "] for user " + userId);
1976
1977 // Write a drop box entry if it's a restricted profile
1978 if (user.isRestricted()) {
1979 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1980 Context.DROPBOX_SERVICE);
1981 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1982 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1983 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1984 }
1985 }
1986 }
1987
1988 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001989 final int userId = getUserIdFromKey(key);
1990 Uri uri = getNotificationUriFor(key, name);
1991
Phil Weaver83fec002016-05-11 10:55:29 -07001992 mGenerationRegistry.incrementGeneration(key);
1993
Svetoslav7e0683b2015-08-03 16:02:52 -07001994 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1995 userId, 0, uri).sendToTarget();
1996
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001997 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001998 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1999 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002000 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002001 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2002 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002003 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002004
Svet Ganov53a441c2016-04-19 19:38:00 -07002005 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002006 }
2007
Svet Ganov53a441c2016-04-19 19:38:00 -07002008 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002009 Set<String> keysCloned) {
2010 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002011 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002012 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002013 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002014 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002015 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002016 final int key = makeKey(type, profileId);
2017 mGenerationRegistry.incrementGeneration(key);
2018
2019 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002020 }
2021 }
2022 }
Svetoslav683914b2015-01-15 14:22:26 -08002023 }
2024
Svetoslav683914b2015-01-15 14:22:26 -08002025 private boolean isGlobalSettingsKey(int key) {
2026 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2027 }
2028
2029 private boolean isSystemSettingsKey(int key) {
2030 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2031 }
2032
2033 private boolean isSecureSettingsKey(int key) {
2034 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2035 }
2036
2037 private File getSettingsFile(int key) {
2038 if (isGlobalSettingsKey(key)) {
2039 final int userId = getUserIdFromKey(key);
2040 return new File(Environment.getUserSystemDirectory(userId),
2041 SETTINGS_FILE_GLOBAL);
2042 } else if (isSystemSettingsKey(key)) {
2043 final int userId = getUserIdFromKey(key);
2044 return new File(Environment.getUserSystemDirectory(userId),
2045 SETTINGS_FILE_SYSTEM);
2046 } else if (isSecureSettingsKey(key)) {
2047 final int userId = getUserIdFromKey(key);
2048 return new File(Environment.getUserSystemDirectory(userId),
2049 SETTINGS_FILE_SECURE);
2050 } else {
2051 throw new IllegalArgumentException("Invalid settings key:" + key);
2052 }
2053 }
2054
2055 private Uri getNotificationUriFor(int key, String name) {
2056 if (isGlobalSettingsKey(key)) {
2057 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2058 : Settings.Global.CONTENT_URI;
2059 } else if (isSecureSettingsKey(key)) {
2060 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2061 : Settings.Secure.CONTENT_URI;
2062 } else if (isSystemSettingsKey(key)) {
2063 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2064 : Settings.System.CONTENT_URI;
2065 } else {
2066 throw new IllegalArgumentException("Invalid settings key:" + key);
2067 }
2068 }
2069
2070 private int getMaxBytesPerPackageForType(int type) {
2071 switch (type) {
2072 case SETTINGS_TYPE_GLOBAL:
2073 case SETTINGS_TYPE_SECURE: {
2074 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2075 }
2076
2077 default: {
2078 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2079 }
2080 }
2081 }
2082
Svetoslav7e0683b2015-08-03 16:02:52 -07002083 private final class MyHandler extends Handler {
2084 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2085 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2086
2087 public MyHandler(Looper looper) {
2088 super(looper);
2089 }
2090
2091 @Override
2092 public void handleMessage(Message msg) {
2093 switch (msg.what) {
2094 case MSG_NOTIFY_URI_CHANGED: {
2095 final int userId = msg.arg1;
2096 Uri uri = (Uri) msg.obj;
2097 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2098 if (DEBUG) {
2099 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2100 }
2101 } break;
2102
2103 case MSG_NOTIFY_DATA_CHANGED: {
2104 mBackupManager.dataChanged();
2105 } break;
2106 }
2107 }
2108 }
2109
Svetoslav683914b2015-01-15 14:22:26 -08002110 private final class UpgradeController {
Andre Lagoea35e072016-08-04 13:41:13 +01002111 private static final int SETTINGS_VERSION = 132;
Svetoslav683914b2015-01-15 14:22:26 -08002112
2113 private final int mUserId;
2114
2115 public UpgradeController(int userId) {
2116 mUserId = userId;
2117 }
2118
2119 public void upgradeIfNeededLocked() {
2120 // The version of all settings for a user is the same (all users have secure).
2121 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002122 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002123
2124 // Try an update from the current state.
2125 final int oldVersion = secureSettings.getVersionLocked();
2126 final int newVersion = SETTINGS_VERSION;
2127
Svet Ganovc9755bc2015-03-28 13:21:22 -07002128 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002129 if (oldVersion == newVersion) {
2130 return;
2131 }
2132
2133 // Try to upgrade.
2134 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2135
2136 // If upgrade failed start from scratch and upgrade.
2137 if (curVersion != newVersion) {
2138 // Drop state we have for this user.
2139 removeUserStateLocked(mUserId, true);
2140
2141 // Recreate the database.
2142 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2143 SQLiteDatabase database = dbHelper.getWritableDatabase();
2144 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2145
2146 // Migrate the settings for this user.
2147 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2148
2149 // Now upgrade should work fine.
2150 onUpgradeLocked(mUserId, oldVersion, newVersion);
2151 }
2152
2153 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002154 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002155 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002156 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002157 globalSettings.setVersionLocked(newVersion);
2158 }
2159
2160 // Set the secure settings version.
2161 secureSettings.setVersionLocked(newVersion);
2162
2163 // Set the system settings version.
2164 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002165 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002166 systemSettings.setVersionLocked(newVersion);
2167 }
2168
2169 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002170 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002171 }
2172
2173 private SettingsState getSecureSettingsLocked(int userId) {
2174 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2175 }
2176
2177 private SettingsState getSystemSettingsLocked(int userId) {
2178 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2179 }
2180
Jeff Brown503cffc2015-03-26 18:08:51 -07002181 /**
2182 * You must perform all necessary mutations to bring the settings
2183 * for this user from the old to the new version. When you add a new
2184 * upgrade step you *must* update SETTINGS_VERSION.
2185 *
2186 * This is an example of moving a setting from secure to global.
2187 *
2188 * // v119: Example settings changes.
2189 * if (currentVersion == 118) {
2190 * if (userId == UserHandle.USER_OWNER) {
2191 * // Remove from the secure settings.
2192 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2193 * String name = "example_setting_to_move";
2194 * String value = secureSettings.getSetting(name);
2195 * secureSettings.deleteSetting(name);
2196 *
2197 * // Add to the global settings.
2198 * SettingsState globalSettings = getGlobalSettingsLocked();
2199 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2200 * }
2201 *
2202 * // Update the current version.
2203 * currentVersion = 119;
2204 * }
2205 */
Svetoslav683914b2015-01-15 14:22:26 -08002206 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2207 if (DEBUG) {
2208 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2209 + oldVersion + " to version: " + newVersion);
2210 }
2211
Jeff Brown503cffc2015-03-26 18:08:51 -07002212 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002213
John Spurlocke11ae112015-05-11 16:09:03 -04002214 // v119: Reset zen + ringer mode.
2215 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002216 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002217 final SettingsState globalSettings = getGlobalSettingsLocked();
2218 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2219 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2220 SettingsState.SYSTEM_PACKAGE_NAME);
2221 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2222 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2223 SettingsState.SYSTEM_PACKAGE_NAME);
2224 }
2225 currentVersion = 119;
2226 }
2227
Jason Monk27bbb2d2015-03-31 16:46:39 -04002228 // v120: Add double tap to wake setting.
2229 if (currentVersion == 119) {
2230 SettingsState secureSettings = getSecureSettingsLocked(userId);
2231 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2232 getContext().getResources().getBoolean(
2233 R.bool.def_double_tap_to_wake) ? "1" : "0",
2234 SettingsState.SYSTEM_PACKAGE_NAME);
2235
2236 currentVersion = 120;
2237 }
2238
Svetoslav7e0683b2015-08-03 16:02:52 -07002239 if (currentVersion == 120) {
2240 // Before 121, we used a different string encoding logic. We just bump the
2241 // version here; SettingsState knows how to handle pre-version 120 files.
2242 currentVersion = 121;
2243 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002244
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002245 if (currentVersion == 121) {
2246 // Version 122: allow OEMs to set a default payment component in resources.
2247 // Note that we only write the default if no default has been set;
2248 // if there is, we just leave the default at whatever it currently is.
2249 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2250 String defaultComponent = (getContext().getResources().getString(
2251 R.string.def_nfc_payment_component));
2252 Setting currentSetting = secureSettings.getSettingLocked(
2253 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2254 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002255 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002256 secureSettings.insertSettingLocked(
2257 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2258 defaultComponent,
2259 SettingsState.SYSTEM_PACKAGE_NAME);
2260 }
2261 currentVersion = 122;
2262 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002263
2264 if (currentVersion == 122) {
2265 // Version 123: Adding a default value for the ability to add a user from
2266 // the lock screen.
2267 if (userId == UserHandle.USER_SYSTEM) {
2268 final SettingsState globalSettings = getGlobalSettingsLocked();
2269 Setting currentSetting = globalSettings.getSettingLocked(
2270 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002271 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002272 globalSettings.insertSettingLocked(
2273 Settings.Global.ADD_USERS_WHEN_LOCKED,
2274 getContext().getResources().getBoolean(
2275 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2276 SettingsState.SYSTEM_PACKAGE_NAME);
2277 }
2278 }
2279 currentVersion = 123;
2280 }
Bryce Leebd179282015-12-17 19:01:37 -08002281
2282 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002283 final SettingsState globalSettings = getGlobalSettingsLocked();
2284 String defaultDisabledProfiles = (getContext().getResources().getString(
2285 R.string.def_bluetooth_disabled_profiles));
2286 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2287 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002288 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002289 }
2290
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002291 if (currentVersion == 124) {
2292 // Version 124: allow OEMs to set a default value for whether IME should be
2293 // shown when a physical keyboard is connected.
2294 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2295 Setting currentSetting = secureSettings.getSettingLocked(
2296 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002297 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002298 secureSettings.insertSettingLocked(
2299 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2300 getContext().getResources().getBoolean(
2301 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2302 SettingsState.SYSTEM_PACKAGE_NAME);
2303 }
2304 currentVersion = 125;
2305 }
2306
Ruben Brunk98576cf2016-03-07 18:54:28 -08002307 if (currentVersion == 125) {
2308 // Version 125: Allow OEMs to set the default VR service.
2309 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2310
2311 Setting currentSetting = secureSettings.getSettingLocked(
2312 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002313 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002314 ArraySet<ComponentName> l =
2315 SystemConfig.getInstance().getDefaultVrComponents();
2316
2317 if (l != null && !l.isEmpty()) {
2318 StringBuilder b = new StringBuilder();
2319 boolean start = true;
2320 for (ComponentName c : l) {
2321 if (!start) {
2322 b.append(':');
2323 }
2324 b.append(c.flattenToString());
2325 start = false;
2326 }
2327 secureSettings.insertSettingLocked(
2328 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2329 SettingsState.SYSTEM_PACKAGE_NAME);
2330 }
2331
2332 }
2333 currentVersion = 126;
2334 }
2335
Daniel U02ba6122016-04-01 18:41:42 +01002336 if (currentVersion == 126) {
2337 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2338 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2339 if (mUserManager.isManagedProfile(userId)) {
2340 final SettingsState systemSecureSettings =
2341 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2342
2343 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2344 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002345 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002346 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2347 secureSettings.insertSettingLocked(
2348 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2349 showNotifications.getValue(),
2350 SettingsState.SYSTEM_PACKAGE_NAME);
2351 }
2352
2353 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2354 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002355 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002356 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2357 secureSettings.insertSettingLocked(
2358 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2359 allowPrivate.getValue(),
2360 SettingsState.SYSTEM_PACKAGE_NAME);
2361 }
2362 }
2363 currentVersion = 127;
2364 }
2365
Steven Ngdc20ba62016-04-26 18:19:04 +01002366 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002367 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002368 currentVersion = 128;
2369 }
2370
Julia Reynolds1f721e12016-07-11 08:50:58 -04002371 if (currentVersion == 128) {
2372 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2373 // the new apps are appended to the list of already approved apps.
2374 final SettingsState systemSecureSettings =
2375 getSecureSettingsLocked(userId);
2376
2377 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2378 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2379 String defaultPolicyAccess = getContext().getResources().getString(
2380 com.android.internal.R.string.config_defaultDndAccessPackages);
2381 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2382 if (policyAccess.isNull()) {
2383 systemSecureSettings.insertSettingLocked(
2384 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2385 defaultPolicyAccess,
2386 SettingsState.SYSTEM_PACKAGE_NAME);
2387 } else {
2388 StringBuilder currentSetting =
2389 new StringBuilder(policyAccess.getValue());
2390 currentSetting.append(":");
2391 currentSetting.append(defaultPolicyAccess);
2392 systemSecureSettings.updateSettingLocked(
2393 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
2394 currentSetting.toString(),
2395 SettingsState.SYSTEM_PACKAGE_NAME);
2396 }
2397 }
2398
2399 currentVersion = 129;
2400 }
2401
Dan Sandler71f85e92016-07-20 13:46:05 -04002402 if (currentVersion == 129) {
2403 // default longpress timeout changed from 500 to 400. If unchanged from the old
2404 // default, update to the new default.
2405 final SettingsState systemSecureSettings =
2406 getSecureSettingsLocked(userId);
2407 final String oldValue = systemSecureSettings.getSettingLocked(
2408 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2409 if (TextUtils.equals("500", oldValue)) {
2410 systemSecureSettings.insertSettingLocked(
2411 Settings.Secure.LONG_PRESS_TIMEOUT,
2412 String.valueOf(getContext().getResources().getInteger(
2413 R.integer.def_long_press_timeout_millis)),
2414 SettingsState.SYSTEM_PACKAGE_NAME);
2415 }
2416 currentVersion = 130;
2417 }
2418
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002419 if (currentVersion == 130) {
2420 // Initialize new multi-press timeout to default value
2421 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2422 final String oldValue = systemSecureSettings.getSettingLocked(
2423 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2424 if (TextUtils.equals(null, oldValue)) {
2425 systemSecureSettings.insertSettingLocked(
2426 Settings.Secure.MULTI_PRESS_TIMEOUT,
2427 String.valueOf(getContext().getResources().getInteger(
2428 R.integer.def_multi_press_timeout_millis)),
2429 SettingsState.SYSTEM_PACKAGE_NAME);
2430 }
2431
2432 currentVersion = 131;
2433 }
2434
Andre Lagoea35e072016-08-04 13:41:13 +01002435 if (currentVersion == 131) {
2436 // Version 131: Allow managed profile to optionally use the parent's ringtones
2437 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2438 String defaultSyncParentSounds = (getContext().getResources()
2439 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
2440 systemSecureSettings.insertSettingLocked(
2441 Settings.Secure.SYNC_PARENT_SOUNDS,
2442 defaultSyncParentSounds,
2443 SettingsState.SYSTEM_PACKAGE_NAME);
2444 currentVersion = 132;
2445 }
2446
Dan Sandler71f85e92016-07-20 13:46:05 -04002447 if (currentVersion != newVersion) {
2448 Slog.w("SettingsProvider", "warning: upgrading settings database to version "
2449 + newVersion + " left it at "
2450 + currentVersion + " instead; this is probably a bug", new Throwable());
2451 if (DEBUG) {
2452 throw new RuntimeException("db upgrade error");
2453 }
2454 }
2455
Jeff Brown503cffc2015-03-26 18:08:51 -07002456 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002457
Jeff Brown503cffc2015-03-26 18:08:51 -07002458 // Return the current version.
2459 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002460 }
2461 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002462 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002463}