blob: db720bb52558bfbe64850c69cd141af85183f8b4 [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;
49import android.os.Looper;
50import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070051import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070052import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070053import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070054import android.os.SELinux;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.os.UserHandle;
56import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070057import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.provider.Settings;
59import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080060import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070061import android.util.Slog;
62import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040063
Svetoslav683914b2015-01-15 14:22:26 -080064import com.android.internal.annotations.GuardedBy;
65import com.android.internal.content.PackageMonitor;
66import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080067import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070068import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080069import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040070
Svetoslav683914b2015-01-15 14:22:26 -080071import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080072import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080073import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080074import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080075import java.security.SecureRandom;
76import java.util.Arrays;
77import java.util.List;
Svetoslav683914b2015-01-15 14:22:26 -080078import java.util.Set;
79import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070080
Svetoslav683914b2015-01-15 14:22:26 -080081/**
82 * <p>
83 * This class is a content provider that publishes the system settings.
84 * It can be accessed via the content provider APIs or via custom call
85 * commands. The latter is a bit faster and is the preferred way to access
86 * the platform settings.
87 * </p>
88 * <p>
89 * There are three settings types, global (with signature level protection
90 * and shared across users), secure (with signature permission level
91 * protection and per user), and system (with dangerous permission level
92 * protection and per user). Global settings are stored under the device owner.
93 * Each of these settings is represented by a {@link
94 * com.android.providers.settings.SettingsState} object mapped to an integer
95 * key derived from the setting type in the most significant bits and user
96 * id in the least significant bits. Settings are synchronously loaded on
97 * instantiation of a SettingsState and asynchronously persisted on mutation.
98 * Settings are stored in the user specific system directory.
99 * </p>
100 * <p>
101 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
102 * and get a warning. Targeting higher API version prohibits this as the
103 * system settings are not a place for apps to save their state. When a package
104 * is removed the settings it added are deleted. Apps cannot delete system
105 * settings added by the platform. System settings values are validated to
106 * ensure the clients do not put bad values. Global and secure settings are
107 * changed only by trusted parties, therefore no validation is performed. Also
108 * there is a limit on the amount of app specific settings that can be added
109 * to prevent unlimited growth of the system process memory footprint.
110 * </p>
111 */
112@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800114 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700115
Svetoslav683914b2015-01-15 14:22:26 -0800116 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
117
118 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700119
Christopher Tate06efb532012-08-24 15:29:27 -0700120 private static final String TABLE_SYSTEM = "system";
121 private static final String TABLE_SECURE = "secure";
122 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800123
124 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final String TABLE_FAVORITES = "favorites";
126 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800127 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
128 private static final String TABLE_BOOKMARKS = "bookmarks";
129 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130
Svetoslav683914b2015-01-15 14:22:26 -0800131 // The set of removed legacy tables.
132 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700133 static {
Svetoslav683914b2015-01-15 14:22:26 -0800134 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
135 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
136 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
137 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
138 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
139 }
Christopher Tate06efb532012-08-24 15:29:27 -0700140
Svetoslav683914b2015-01-15 14:22:26 -0800141 private static final int MUTATION_OPERATION_INSERT = 1;
142 private static final int MUTATION_OPERATION_DELETE = 2;
143 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400144
Svetoslav683914b2015-01-15 14:22:26 -0800145 private static final String[] ALL_COLUMNS = new String[] {
146 Settings.NameValueTable._ID,
147 Settings.NameValueTable.NAME,
148 Settings.NameValueTable.VALUE
149 };
150
Svet Ganov53a441c2016-04-19 19:38:00 -0700151 public static final int SETTINGS_TYPE_GLOBAL = 0;
152 public static final int SETTINGS_TYPE_SYSTEM = 1;
153 public static final int SETTINGS_TYPE_SECURE = 2;
Svetoslav683914b2015-01-15 14:22:26 -0800154
Svet Ganov53a441c2016-04-19 19:38:00 -0700155 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
156 public static final int SETTINGS_TYPE_SHIFT = 28;
157
158 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
159 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700160
Svetoslav683914b2015-01-15 14:22:26 -0800161 // Per user secure settings that moved to the for all users global settings.
162 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
163 static {
164 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700165 }
166
Svetoslav683914b2015-01-15 14:22:26 -0800167 // Per user system settings that moved to the for all users global settings.
168 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
169 static {
170 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700171 }
172
Svetoslav683914b2015-01-15 14:22:26 -0800173 // Per user system settings that moved to the per user secure settings.
174 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
175 static {
176 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700177 }
178
Svetoslav683914b2015-01-15 14:22:26 -0800179 // Per all users global settings that moved to the per user secure settings.
180 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
181 static {
182 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700183 }
184
Svetoslav683914b2015-01-15 14:22:26 -0800185 // Per user secure settings that are cloned for the managed profiles of the user.
186 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
187 static {
188 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700189 }
190
Svetoslav683914b2015-01-15 14:22:26 -0800191 // Per user system settings that are cloned for the managed profiles of the user.
192 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
193 static {
194 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400195 }
196
Svetoslav683914b2015-01-15 14:22:26 -0800197 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700198
Svetoslav683914b2015-01-15 14:22:26 -0800199 @GuardedBy("mLock")
200 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700201
Svetoslav7ec28e82015-05-20 17:01:10 -0700202 // We have to call in the user manager with no lock held,
203 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800204
Svetoslav7ec28e82015-05-20 17:01:10 -0700205 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700206 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700207
Svet Ganov53a441c2016-04-19 19:38:00 -0700208 public static int makeKey(int type, int userId) {
209 return (type << SETTINGS_TYPE_SHIFT) | userId;
210 }
211
212 public static int getTypeFromKey(int key) {
213 return key >>> SETTINGS_TYPE_SHIFT;
214 }
215
216 public static int getUserIdFromKey(int key) {
217 return key & ~SETTINGS_TYPE_MASK;
218 }
219
220 public static String settingTypeToString(int type) {
221 switch (type) {
222 case SETTINGS_TYPE_GLOBAL: {
223 return "SETTINGS_GLOBAL";
224 }
225 case SETTINGS_TYPE_SECURE: {
226 return "SETTINGS_SECURE";
227 }
228 case SETTINGS_TYPE_SYSTEM: {
229 return "SETTINGS_SYSTEM";
230 }
231 default: {
232 return "UNKNOWN";
233 }
234 }
235 }
236
237 public static String keyToString(int key) {
238 return "Key[user=" + getUserIdFromKey(key) + ";type="
239 + settingTypeToString(getTypeFromKey(key)) + "]";
240 }
241
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 @Override
243 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800244 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700245 mUserManager = UserManager.get(getContext());
246 mPackageManager = AppGlobals.getPackageManager();
Svetoslav683914b2015-01-15 14:22:26 -0800247 mSettingsRegistry = new SettingsRegistry();
248 }
249 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700250 startWatchingUserRestrictionChanges();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700251 return true;
252 }
253
Svetoslav683914b2015-01-15 14:22:26 -0800254 @Override
255 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700256 final int requestingUserId = getRequestingUserId(args);
257 switch (method) {
258 case Settings.CALL_METHOD_GET_GLOBAL: {
259 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700260 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800261 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700262
263 case Settings.CALL_METHOD_GET_SECURE: {
264 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700265 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700266 }
267
268 case Settings.CALL_METHOD_GET_SYSTEM: {
269 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700270 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700271 }
272
273 case Settings.CALL_METHOD_PUT_GLOBAL: {
274 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700275 insertGlobalSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700276 break;
277 }
278
279 case Settings.CALL_METHOD_PUT_SECURE: {
280 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 insertSecureSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700282 break;
283 }
284
285 case Settings.CALL_METHOD_PUT_SYSTEM: {
286 String value = getSettingValue(args);
287 insertSystemSetting(name, value, requestingUserId);
288 break;
289 }
290
291 default: {
292 Slog.w(LOG_TAG, "call() with invalid method: " + method);
293 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700294 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700295
Christopher Tate06efb532012-08-24 15:29:27 -0700296 return null;
297 }
298
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800299 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800300 public String getType(Uri uri) {
301 Arguments args = new Arguments(uri, null, null, true);
302 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700303 return "vnd.android.cursor.dir/" + args.table;
304 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700305 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700306 }
307 }
308
309 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800310 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
311 String order) {
312 if (DEBUG) {
313 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 }
315
Svetoslav683914b2015-01-15 14:22:26 -0800316 Arguments args = new Arguments(uri, where, whereArgs, true);
317 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700318
Svetoslav683914b2015-01-15 14:22:26 -0800319 // If a legacy table that is gone, done.
320 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
321 return new MatrixCursor(normalizedProjection, 0);
322 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700323
Svetoslav7ec28e82015-05-20 17:01:10 -0700324 switch (args.table) {
325 case TABLE_GLOBAL: {
326 if (args.name != null) {
327 Setting setting = getGlobalSetting(args.name);
328 return packageSettingForQuery(setting, normalizedProjection);
329 } else {
330 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700331 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700332 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700333
Svetoslav7ec28e82015-05-20 17:01:10 -0700334 case TABLE_SECURE: {
335 final int userId = UserHandle.getCallingUserId();
336 if (args.name != null) {
337 Setting setting = getSecureSetting(args.name, userId);
338 return packageSettingForQuery(setting, normalizedProjection);
339 } else {
340 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800341 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700342 }
Svetoslav683914b2015-01-15 14:22:26 -0800343
Svetoslav7ec28e82015-05-20 17:01:10 -0700344 case TABLE_SYSTEM: {
345 final int userId = UserHandle.getCallingUserId();
346 if (args.name != null) {
347 Setting setting = getSystemSetting(args.name, userId);
348 return packageSettingForQuery(setting, normalizedProjection);
349 } else {
350 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800351 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700352 }
Svetoslav683914b2015-01-15 14:22:26 -0800353
Svetoslav7ec28e82015-05-20 17:01:10 -0700354 default: {
355 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700356 }
357 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700358 }
359
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700360 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800361 public Uri insert(Uri uri, ContentValues values) {
362 if (DEBUG) {
363 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700364 }
365
Svetoslav683914b2015-01-15 14:22:26 -0800366 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700367
Svetoslav683914b2015-01-15 14:22:26 -0800368 // If a legacy table that is gone, done.
369 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 return null;
371 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372
Svetoslav683914b2015-01-15 14:22:26 -0800373 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700374 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800375 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700376 }
377
Svetoslav683914b2015-01-15 14:22:26 -0800378 String value = values.getAsString(Settings.Secure.VALUE);
379
Svetoslav7ec28e82015-05-20 17:01:10 -0700380 switch (table) {
381 case TABLE_GLOBAL: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700382 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700383 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700384 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700385 } break;
386
387 case TABLE_SECURE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700388 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700389 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
390 }
391 } break;
392
393 case TABLE_SYSTEM: {
394 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
395 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
396 }
397 } break;
398
399 default: {
400 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700401 }
402 }
403
Svetoslav683914b2015-01-15 14:22:26 -0800404 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700405 }
406
407 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800408 public int bulkInsert(Uri uri, ContentValues[] allValues) {
409 if (DEBUG) {
410 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700412
Svetoslav683914b2015-01-15 14:22:26 -0800413 int insertionCount = 0;
414 final int valuesCount = allValues.length;
415 for (int i = 0; i < valuesCount; i++) {
416 ContentValues values = allValues[i];
417 if (insert(uri, values) != null) {
418 insertionCount++;
419 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700420 }
Svetoslav683914b2015-01-15 14:22:26 -0800421
422 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700423 }
424
425 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800426 public int delete(Uri uri, String where, String[] whereArgs) {
427 if (DEBUG) {
428 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430
Svetoslav683914b2015-01-15 14:22:26 -0800431 Arguments args = new Arguments(uri, where, whereArgs, false);
432
433 // If a legacy table that is gone, done.
434 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
435 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700436 }
Svetoslav683914b2015-01-15 14:22:26 -0800437
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700438 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800439 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700440 }
Svetoslav683914b2015-01-15 14:22:26 -0800441
Svetoslav7ec28e82015-05-20 17:01:10 -0700442 switch (args.table) {
443 case TABLE_GLOBAL: {
444 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700445 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700446 }
Svetoslav683914b2015-01-15 14:22:26 -0800447
Svetoslav7ec28e82015-05-20 17:01:10 -0700448 case TABLE_SECURE: {
449 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700450 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700451 }
Svetoslav683914b2015-01-15 14:22:26 -0800452
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 case TABLE_SYSTEM: {
454 final int userId = UserHandle.getCallingUserId();
455 return deleteSystemSetting(args.name, userId) ? 1 : 0;
456 }
457
458 default: {
459 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800460 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700461 }
Svetoslav683914b2015-01-15 14:22:26 -0800462 }
463
464 @Override
465 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
466 if (DEBUG) {
467 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700468 }
Svetoslav683914b2015-01-15 14:22:26 -0800469
470 Arguments args = new Arguments(uri, where, whereArgs, false);
471
472 // If a legacy table that is gone, done.
473 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
474 return 0;
475 }
476
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700477 String name = values.getAsString(Settings.Secure.NAME);
478 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800479 return 0;
480 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700481 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800482
Svetoslav7ec28e82015-05-20 17:01:10 -0700483 switch (args.table) {
484 case TABLE_GLOBAL: {
485 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700486 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700487 }
Svetoslav683914b2015-01-15 14:22:26 -0800488
Svetoslav7ec28e82015-05-20 17:01:10 -0700489 case TABLE_SECURE: {
490 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700491 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700492 }
Svetoslav683914b2015-01-15 14:22:26 -0800493
Svetoslav7ec28e82015-05-20 17:01:10 -0700494 case TABLE_SYSTEM: {
495 final int userId = UserHandle.getCallingUserId();
496 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
497 }
Svetoslav683914b2015-01-15 14:22:26 -0800498
Svetoslav7ec28e82015-05-20 17:01:10 -0700499 default: {
500 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800501 }
502 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700503 }
504
505 @Override
506 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey413573a2016-02-22 17:52:45 -0700507 final String cacheName;
508 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
509 cacheName = Settings.System.RINGTONE_CACHE;
510 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
511 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
512 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
513 cacheName = Settings.System.ALARM_ALERT_CACHE;
514 } else {
515 throw new FileNotFoundException("Direct file access no longer supported; "
516 + "ringtone playback is available through android.media.Ringtone");
517 }
518
519 final File cacheFile = new File(
520 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
521 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
522 }
523
524 private File getRingtoneCacheDir(int userId) {
525 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
526 cacheDir.mkdir();
527 SELinux.restorecon(cacheDir);
528 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700529 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800530
Svetoslavb505ccc2015-02-17 12:41:04 -0800531 @Override
532 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
533 synchronized (mLock) {
534 final long identity = Binder.clearCallingIdentity();
535 try {
536 List<UserInfo> users = mUserManager.getUsers(true);
537 final int userCount = users.size();
538 for (int i = 0; i < userCount; i++) {
539 UserInfo user = users.get(i);
540 dumpForUser(user.id, pw);
541 }
542 } finally {
543 Binder.restoreCallingIdentity(identity);
544 }
545 }
546 }
547
548 private void dumpForUser(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700549 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800550 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700551 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800552 dumpSettings(globalCursor, pw);
553 pw.println();
554 }
555
556 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700557 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800558 dumpSettings(secureCursor, pw);
559 pw.println();
560
561 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700562 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800563 dumpSettings(systemCursor, pw);
564 pw.println();
565 }
566
567 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700568 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800569 return;
570 }
571
572 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
573 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
574 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
575
576 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700577 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
578 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
579 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800580 pw.println();
581 } while (cursor.moveToNext());
582 }
583
Svetoslav7e0683b2015-08-03 16:02:52 -0700584 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700585 if (s != null) {
586 return s;
587 }
588 return "{null}";
589 }
590
Svetoslav683914b2015-01-15 14:22:26 -0800591 private void registerBroadcastReceivers() {
592 IntentFilter userFilter = new IntentFilter();
593 userFilter.addAction(Intent.ACTION_USER_REMOVED);
594 userFilter.addAction(Intent.ACTION_USER_STOPPED);
595
596 getContext().registerReceiver(new BroadcastReceiver() {
597 @Override
598 public void onReceive(Context context, Intent intent) {
599 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700600 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800601
602 switch (intent.getAction()) {
603 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700604 synchronized (mLock) {
605 mSettingsRegistry.removeUserStateLocked(userId, true);
606 }
Svetoslav683914b2015-01-15 14:22:26 -0800607 } break;
608
609 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700610 synchronized (mLock) {
611 mSettingsRegistry.removeUserStateLocked(userId, false);
612 }
Svetoslav683914b2015-01-15 14:22:26 -0800613 } break;
614 }
615 }
616 }, userFilter);
617
618 PackageMonitor monitor = new PackageMonitor() {
619 @Override
620 public void onPackageRemoved(String packageName, int uid) {
621 synchronized (mLock) {
622 mSettingsRegistry.onPackageRemovedLocked(packageName,
623 UserHandle.getUserId(uid));
624 }
625 }
626 };
627
628 // package changes
629 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
630 UserHandle.ALL, true);
631 }
632
Svet Ganov53a441c2016-04-19 19:38:00 -0700633 private void startWatchingUserRestrictionChanges() {
634 // TODO: The current design of settings looking different based on user restrictions
635 // should be reworked to keep them separate and system code should check the setting
636 // first followed by checking the user restriction before performing an operation.
637 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
638 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
639 Bundle prevRestrictions) -> {
640 // We are changing the settings affected by restrictions to their current
641 // value with a forced update to ensure that all cross profile dependencies
642 // are taken into account. Also make sure the settings update to.. the same
643 // value passes the security checks, so clear binder calling id.
644 if (newRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)
645 != prevRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)) {
646 final long identity = Binder.clearCallingIdentity();
647 try {
648 synchronized (mLock) {
649 Setting setting = getSecureSetting(
650 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
651 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
652 setting != null ? setting.getValue() : null, userId, true);
653 }
654 } finally {
655 Binder.restoreCallingIdentity(identity);
656 }
657 }
658 if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
659 != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
660 final long identity = Binder.clearCallingIdentity();
661 try {
662 synchronized (mLock) {
663 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
664 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
665 setting != null ? setting.getValue() : null, userId, true);
666 }
667 } finally {
668 Binder.restoreCallingIdentity(identity);
669 }
670 }
671 if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
672 != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
673 final long identity = Binder.clearCallingIdentity();
674 try {
675 synchronized (mLock) {
676 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
677 updateGlobalSetting(Settings.Global.ADB_ENABLED,
678 setting != null ? setting.getValue() : null, userId, true);
679 }
680 } finally {
681 Binder.restoreCallingIdentity(identity);
682 }
683 }
684 if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
685 != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
686 final long identity = Binder.clearCallingIdentity();
687 try {
688 synchronized (mLock) {
689 Setting enable = getGlobalSetting(
690 Settings.Global.PACKAGE_VERIFIER_ENABLE);
691 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
692 enable != null ? enable.getValue() : null, userId, true);
693 Setting include = getGlobalSetting(
694 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
695 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
696 include != null ? include.getValue() : null, userId, true);
697 }
698 } finally {
699 Binder.restoreCallingIdentity(identity);
700 }
701 }
702 if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
703 != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
704 final long identity = Binder.clearCallingIdentity();
705 try {
706 synchronized (mLock) {
707 Setting setting = getGlobalSetting(
708 Settings.Global.PREFERRED_NETWORK_MODE);
709 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
710 setting != null ? setting.getValue() : null, userId, true);
711 }
712 } finally {
713 Binder.restoreCallingIdentity(identity);
714 }
715 }
716 });
717 }
718
Svetoslav7ec28e82015-05-20 17:01:10 -0700719 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800720 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700721 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800722 }
723
Svetoslav7ec28e82015-05-20 17:01:10 -0700724 synchronized (mLock) {
725 // Get the settings.
726 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700727 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800728
Svetoslav7ec28e82015-05-20 17:01:10 -0700729 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800730
Svetoslav7ec28e82015-05-20 17:01:10 -0700731 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800732
Svetoslav7ec28e82015-05-20 17:01:10 -0700733 String[] normalizedProjection = normalizeProjection(projection);
734 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800735
Svetoslav7ec28e82015-05-20 17:01:10 -0700736 // Anyone can get the global settings, so no security checks.
737 for (int i = 0; i < nameCount; i++) {
738 String name = names.get(i);
739 Setting setting = settingsState.getSettingLocked(name);
740 appendSettingToCursor(result, setting);
741 }
742
743 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800744 }
Svetoslav683914b2015-01-15 14:22:26 -0800745 }
746
Svetoslav7ec28e82015-05-20 17:01:10 -0700747 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800748 if (DEBUG) {
749 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
750 }
751
752 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700753 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700754 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700755 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800756 }
Svetoslav683914b2015-01-15 14:22:26 -0800757 }
758
Svet Ganov53a441c2016-04-19 19:38:00 -0700759 private boolean updateGlobalSetting(String name, String value, int requestingUserId,
760 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800761 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700762 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800763 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700764 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
765 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800766 }
767
Svet Ganov53a441c2016-04-19 19:38:00 -0700768 private boolean insertGlobalSetting(String name, String value, int requestingUserId,
769 boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700770 if (DEBUG) {
771 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
772 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700773 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
774 forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700775 }
776
Svet Ganov53a441c2016-04-19 19:38:00 -0700777 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800778 if (DEBUG) {
779 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
780 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700781 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
782 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800783 }
784
Svetoslav7ec28e82015-05-20 17:01:10 -0700785 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700786 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800787 // Make sure the caller can change the settings - treated as secure.
788 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
789
Svetoslav683914b2015-01-15 14:22:26 -0800790 // Resolve the userId on whose behalf the call is made.
791 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
792
Makoto Onuki28da2e32015-11-20 11:30:44 -0800793 // If this is a setting that is currently restricted for this user, do not allow
794 // unrestricting changes.
795 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800796 return false;
797 }
798
799 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700800 synchronized (mLock) {
801 switch (operation) {
802 case MUTATION_OPERATION_INSERT: {
803 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700804 .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
805 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700806 }
Svetoslav683914b2015-01-15 14:22:26 -0800807
Svetoslav7ec28e82015-05-20 17:01:10 -0700808 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700809 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
810 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700811 }
Svetoslav683914b2015-01-15 14:22:26 -0800812
Svetoslav7ec28e82015-05-20 17:01:10 -0700813 case MUTATION_OPERATION_UPDATE: {
814 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700815 .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
816 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700817 }
Svetoslav683914b2015-01-15 14:22:26 -0800818 }
819 }
820
821 return false;
822 }
823
Svetoslav7ec28e82015-05-20 17:01:10 -0700824 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800825 if (DEBUG) {
826 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
827 }
828
829 // Resolve the userId on whose behalf the call is made.
830 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
831
Svetoslav7ec28e82015-05-20 17:01:10 -0700832 synchronized (mLock) {
833 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700834 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800835
Svetoslav7ec28e82015-05-20 17:01:10 -0700836 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800837
Svetoslav7ec28e82015-05-20 17:01:10 -0700838 String[] normalizedProjection = normalizeProjection(projection);
839 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800840
Svetoslav7ec28e82015-05-20 17:01:10 -0700841 for (int i = 0; i < nameCount; i++) {
842 String name = names.get(i);
843 // Determine the owning user as some profile settings are cloned from the parent.
844 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
845 name);
Svetoslav683914b2015-01-15 14:22:26 -0800846
Svetoslav7ec28e82015-05-20 17:01:10 -0700847 // Special case for location (sigh).
848 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
849 return null;
850 }
Svetoslav683914b2015-01-15 14:22:26 -0800851
Svetoslav7ec28e82015-05-20 17:01:10 -0700852 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700853 SETTINGS_TYPE_SECURE, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700854 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800855 }
856
Svetoslav7ec28e82015-05-20 17:01:10 -0700857 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800858 }
Svetoslav683914b2015-01-15 14:22:26 -0800859 }
860
Svetoslav7ec28e82015-05-20 17:01:10 -0700861 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800862 if (DEBUG) {
863 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
864 }
865
866 // Resolve the userId on whose behalf the call is made.
867 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
868
869 // Determine the owning user as some profile settings are cloned from the parent.
870 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
871
872 // Special case for location (sigh).
873 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
874 return null;
875 }
876
877 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700878 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700879 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 owningUserId, name);
881 }
Svetoslav683914b2015-01-15 14:22:26 -0800882 }
883
Svet Ganov53a441c2016-04-19 19:38:00 -0700884 private boolean insertSecureSetting(String name, String value, int requestingUserId,
885 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800886 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800888 + requestingUserId + ")");
889 }
890
Svet Ganov53a441c2016-04-19 19:38:00 -0700891 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
892 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800893 }
894
Svet Ganov53a441c2016-04-19 19:38:00 -0700895 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800896 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700897 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800898 }
899
Svet Ganov53a441c2016-04-19 19:38:00 -0700900 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
901 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800902 }
903
Svet Ganov53a441c2016-04-19 19:38:00 -0700904 private boolean updateSecureSetting(String name, String value, int requestingUserId,
905 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800906 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700907 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800908 + requestingUserId + ")");
909 }
910
Svet Ganov53a441c2016-04-19 19:38:00 -0700911 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
912 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800913 }
914
Svetoslav7ec28e82015-05-20 17:01:10 -0700915 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700916 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800917 // Make sure the caller can change the settings.
918 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
919
Svetoslav683914b2015-01-15 14:22:26 -0800920 // Resolve the userId on whose behalf the call is made.
921 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
922
Makoto Onuki28da2e32015-11-20 11:30:44 -0800923 // If this is a setting that is currently restricted for this user, do not allow
924 // unrestricting changes.
925 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800926 return false;
927 }
928
929 // Determine the owning user as some profile settings are cloned from the parent.
930 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
931
932 // Only the owning user can change the setting.
933 if (owningUserId != callingUserId) {
934 return false;
935 }
936
937 // Special cases for location providers (sigh).
938 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700939 return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800940 }
941
942 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 synchronized (mLock) {
944 switch (operation) {
945 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700946 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
947 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700948 }
Svetoslav683914b2015-01-15 14:22:26 -0800949
Svetoslav7ec28e82015-05-20 17:01:10 -0700950 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700951 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
952 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700953 }
Svetoslav683914b2015-01-15 14:22:26 -0800954
Svetoslav7ec28e82015-05-20 17:01:10 -0700955 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700956 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
957 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700958 }
Svetoslav683914b2015-01-15 14:22:26 -0800959 }
960 }
961
962 return false;
963 }
964
Svetoslav7ec28e82015-05-20 17:01:10 -0700965 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800966 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700967 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800968 }
969
970 // Resolve the userId on whose behalf the call is made.
971 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
972
Svetoslav7ec28e82015-05-20 17:01:10 -0700973 synchronized (mLock) {
974 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700975 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800976
Svetoslav7ec28e82015-05-20 17:01:10 -0700977 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800978
Svetoslav7ec28e82015-05-20 17:01:10 -0700979 String[] normalizedProjection = normalizeProjection(projection);
980 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800981
Svetoslav7ec28e82015-05-20 17:01:10 -0700982 for (int i = 0; i < nameCount; i++) {
983 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800984
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 // Determine the owning user as some profile settings are cloned from the parent.
986 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
987 name);
Svetoslav683914b2015-01-15 14:22:26 -0800988
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700990 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700991 appendSettingToCursor(result, setting);
992 }
993
994 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800995 }
Svetoslav683914b2015-01-15 14:22:26 -0800996 }
997
Svetoslav7ec28e82015-05-20 17:01:10 -0700998 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800999 if (DEBUG) {
1000 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1001 }
1002
1003 // Resolve the userId on whose behalf the call is made.
1004 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1005
1006 // Determine the owning user as some profile settings are cloned from the parent.
1007 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1008
1009 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001010 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001011 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001012 }
Svetoslav683914b2015-01-15 14:22:26 -08001013 }
1014
Svetoslav7ec28e82015-05-20 17:01:10 -07001015 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001016 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001017 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001018 + requestingUserId + ")");
1019 }
1020
Svetoslav7ec28e82015-05-20 17:01:10 -07001021 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001022 }
1023
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001025 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001027 }
1028
Svetoslav7ec28e82015-05-20 17:01:10 -07001029 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001030 }
1031
Svetoslav7ec28e82015-05-20 17:01:10 -07001032 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001033 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001034 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001035 + requestingUserId + ")");
1036 }
1037
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001039 }
1040
Svetoslav7ec28e82015-05-20 17:01:10 -07001041 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001042 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001043 if (!hasWriteSecureSettingsPermission()) {
1044 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1045 // operation is allowed for the calling package through appops.
1046 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1047 Binder.getCallingUid(), getCallingPackage(), true)) {
1048 return false;
1049 }
Svetoslav683914b2015-01-15 14:22:26 -08001050 }
1051
Svetoslav683914b2015-01-15 14:22:26 -08001052 // Resolve the userId on whose behalf the call is made.
1053 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1054
Svetoslavd8d25e02015-11-20 13:09:26 -08001055 // Enforce what the calling package can mutate the system settings.
1056 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1057
Svetoslav683914b2015-01-15 14:22:26 -08001058 // Determine the owning user as some profile settings are cloned from the parent.
1059 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1060
1061 // Only the owning user id can change the setting.
1062 if (owningUserId != callingUserId) {
1063 return false;
1064 }
1065
Jeff Sharkey413573a2016-02-22 17:52:45 -07001066 // Invalidate any relevant cache files
1067 String cacheName = null;
1068 if (Settings.System.RINGTONE.equals(name)) {
1069 cacheName = Settings.System.RINGTONE_CACHE;
1070 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1071 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1072 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1073 cacheName = Settings.System.ALARM_ALERT_CACHE;
1074 }
1075 if (cacheName != null) {
1076 final File cacheFile = new File(
1077 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
1078 cacheFile.delete();
1079 }
1080
Svetoslav683914b2015-01-15 14:22:26 -08001081 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001082 synchronized (mLock) {
1083 switch (operation) {
1084 case MUTATION_OPERATION_INSERT: {
1085 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001086 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
1087 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001088 }
1089
1090 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001091 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1092 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001093 }
1094
1095 case MUTATION_OPERATION_UPDATE: {
1096 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001097 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1098 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001099 }
Svetoslav683914b2015-01-15 14:22:26 -08001100 }
1101
Svetoslav7ec28e82015-05-20 17:01:10 -07001102 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001103 }
Svetoslav683914b2015-01-15 14:22:26 -08001104 }
1105
Billy Lau6ad2d662015-07-18 00:26:58 +01001106 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001107 // Write secure settings is a more protected permission. If caller has it we are good.
1108 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1109 == PackageManager.PERMISSION_GRANTED) {
1110 return true;
1111 }
1112
Svetoslavf41334b2015-06-23 12:06:03 -07001113 return false;
1114 }
1115
Svetoslav683914b2015-01-15 14:22:26 -08001116 private void validateSystemSettingValue(String name, String value) {
1117 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1118 if (validator != null && !validator.validate(value)) {
1119 throw new IllegalArgumentException("Invalid value: " + value
1120 + " for setting: " + name);
1121 }
1122 }
1123
1124 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1125 int owningUserId) {
1126 // Optimization - location providers are restricted only for managed profiles.
1127 if (callingUserId == owningUserId) {
1128 return false;
1129 }
1130 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1131 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1132 new UserHandle(callingUserId))) {
1133 return true;
1134 }
1135 return false;
1136 }
1137
Makoto Onuki28da2e32015-11-20 11:30:44 -08001138 /**
1139 * Checks whether changing a setting to a value is prohibited by the corresponding user
1140 * restriction.
1141 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001142 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1143 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001144 *
1145 * @return true if the change is prohibited, false if the change is allowed.
1146 */
1147 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
1148 String value) {
1149 String restriction;
1150 switch (setting) {
1151 case Settings.Secure.LOCATION_MODE:
1152 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1153 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1154 // here normally, but we still protect it here from a direct provider write.
1155 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1156 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1157 break;
1158
1159 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1160 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1161 // a provider, which should be allowed even if the user restriction is set.
1162 if (value != null && value.startsWith("-")) return false;
1163 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1164 break;
1165
1166 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1167 if ("0".equals(value)) return false;
1168 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1169 break;
1170
1171 case Settings.Global.ADB_ENABLED:
1172 if ("0".equals(value)) return false;
1173 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1174 break;
1175
1176 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1177 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1178 if ("1".equals(value)) return false;
1179 restriction = UserManager.ENSURE_VERIFY_APPS;
1180 break;
1181
1182 case Settings.Global.PREFERRED_NETWORK_MODE:
1183 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1184 break;
1185
1186 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001187 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001188 if ("0".equals(value)) return false;
1189 restriction = UserManager.DISALLOW_DATA_ROAMING;
1190 break;
1191 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001192 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001193 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001194
1195 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001196 }
1197
1198 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1199 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1200 }
1201
1202 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1203 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1204 }
1205
1206 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1207 final int parentId = getGroupParentLocked(userId);
1208 if (parentId != userId && keys.contains(name)) {
1209 return parentId;
1210 }
1211 return userId;
1212 }
1213
Svetoslavf41334b2015-06-23 12:06:03 -07001214 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001215 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001216 // System/root/shell can mutate whatever secure settings they want.
1217 final int callingUid = Binder.getCallingUid();
1218 if (callingUid == android.os.Process.SYSTEM_UID
1219 || callingUid == Process.SHELL_UID
1220 || callingUid == Process.ROOT_UID) {
1221 return;
1222 }
1223
1224 switch (operation) {
1225 case MUTATION_OPERATION_INSERT:
1226 // Insert updates.
1227 case MUTATION_OPERATION_UPDATE: {
1228 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1229 return;
1230 }
1231
1232 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001233 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001234
1235 // Privileged apps can do whatever they want.
1236 if ((packageInfo.applicationInfo.privateFlags
1237 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1238 return;
1239 }
1240
1241 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1242 packageInfo.applicationInfo.targetSdkVersion, name);
1243 } break;
1244
1245 case MUTATION_OPERATION_DELETE: {
1246 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1247 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1248 throw new IllegalArgumentException("You cannot delete system defined"
1249 + " secure settings.");
1250 }
1251
1252 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001253 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001254
1255 // Privileged apps can do whatever they want.
1256 if ((packageInfo.applicationInfo.privateFlags &
1257 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1258 return;
1259 }
1260
1261 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1262 packageInfo.applicationInfo.targetSdkVersion, name);
1263 } break;
1264 }
1265 }
1266
Xiaohui Chen43765b72015-08-31 10:57:33 -07001267 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001268 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001269 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1270 getCallingPackage(), 0, userId);
1271 if (packageInfo != null) {
1272 return packageInfo;
1273 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001274 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001275 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001276 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001277 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001278 }
1279
1280 private int getGroupParentLocked(int userId) {
1281 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001282 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001283 return userId;
1284 }
1285 // We are in the same process with the user manager and the returned
1286 // user info is a cached instance, so just look up instead of cache.
1287 final long identity = Binder.clearCallingIdentity();
1288 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001289 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001290 UserInfo userInfo = mUserManager.getProfileParent(userId);
1291 return (userInfo != null) ? userInfo.id : userId;
1292 } finally {
1293 Binder.restoreCallingIdentity(identity);
1294 }
1295 }
1296
Svetoslav683914b2015-01-15 14:22:26 -08001297 private void enforceWritePermission(String permission) {
1298 if (getContext().checkCallingOrSelfPermission(permission)
1299 != PackageManager.PERMISSION_GRANTED) {
1300 throw new SecurityException("Permission denial: writing to settings requires:"
1301 + permission);
1302 }
1303 }
1304
1305 /*
1306 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1307 * This setting contains a list of the currently enabled location providers.
1308 * But helper functions in android.providers.Settings can enable or disable
1309 * a single provider by using a "+" or "-" prefix before the provider name.
1310 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001311 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1312 * is set, the said method will only allow values with the "-" prefix.
1313 *
Svetoslav683914b2015-01-15 14:22:26 -08001314 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001315 */
Svet Ganov53a441c2016-04-19 19:38:00 -07001316 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1317 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001318 if (TextUtils.isEmpty(value)) {
1319 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001320 }
1321
Svetoslav683914b2015-01-15 14:22:26 -08001322 final char prefix = value.charAt(0);
1323 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001324 if (forceNotify) {
1325 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1326 mSettingsRegistry.notifyForSettingsChange(key,
1327 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1328 }
Svetoslav683914b2015-01-15 14:22:26 -08001329 return false;
1330 }
1331
1332 // skip prefix
1333 value = value.substring(1);
1334
Svetoslav7ec28e82015-05-20 17:01:10 -07001335 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001336 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1337
1338 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1339
1340 int index = oldProviders.indexOf(value);
1341 int end = index + value.length();
1342
1343 // check for commas to avoid matching on partial string
1344 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1345 index = -1;
1346 }
1347
1348 // check for commas to avoid matching on partial string
1349 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1350 index = -1;
1351 }
1352
1353 String newProviders;
1354
1355 if (prefix == '+' && index < 0) {
1356 // append the provider to the list if not present
1357 if (oldProviders.length() == 0) {
1358 newProviders = value;
1359 } else {
1360 newProviders = oldProviders + ',' + value;
1361 }
1362 } else if (prefix == '-' && index >= 0) {
1363 // remove the provider from the list if present
1364 // remove leading or trailing comma
1365 if (index > 0) {
1366 index--;
1367 } else if (end < oldProviders.length()) {
1368 end++;
1369 }
1370
1371 newProviders = oldProviders.substring(0, index);
1372 if (end < oldProviders.length()) {
1373 newProviders += oldProviders.substring(end);
1374 }
1375 } else {
1376 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001377 if (forceNotify) {
1378 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1379 mSettingsRegistry.notifyForSettingsChange(key,
1380 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1381 }
Svetoslav683914b2015-01-15 14:22:26 -08001382 return false;
1383 }
1384
Svet Ganov53a441c2016-04-19 19:38:00 -07001385 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001386 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svet Ganov53a441c2016-04-19 19:38:00 -07001387 getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001388 }
1389
Svetoslav683914b2015-01-15 14:22:26 -08001390 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1391 int targetSdkVersion, String name) {
1392 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1393 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1394 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1395 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1396 + " This will soon become an error.");
1397 } else {
1398 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1399 + " This will soon become an error.");
1400 }
1401 } else {
1402 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1403 throw new IllegalArgumentException("You cannot change private secure settings.");
1404 } else {
1405 throw new IllegalArgumentException("You cannot keep your settings in"
1406 + " the secure settings.");
1407 }
1408 }
1409 }
1410
1411 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1412 if (requestingUserId == UserHandle.getCallingUserId()) {
1413 return requestingUserId;
1414 }
1415 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1416 Binder.getCallingUid(), requestingUserId, false, true,
1417 "get/set setting for user", null);
1418 }
1419
Svet Ganov53a441c2016-04-19 19:38:00 -07001420 private Bundle packageValueForCallResult(Setting setting,
1421 boolean trackingGeneration) {
1422 if (!trackingGeneration) {
1423 if (setting.isNull()) {
1424 return NULL_SETTING_BUNDLE;
1425 }
1426 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001427 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001428 Bundle result = new Bundle();
1429 result.putString(Settings.NameValueTable.VALUE,
1430 !setting.isNull() ? setting.getValue() : null);
1431 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1432 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001433 }
1434
1435 private static int getRequestingUserId(Bundle args) {
1436 final int callingUserId = UserHandle.getCallingUserId();
1437 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1438 : callingUserId;
1439 }
1440
Svet Ganov53a441c2016-04-19 19:38:00 -07001441 private boolean isTrackingGeneration(Bundle args) {
1442 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1443 }
1444
Svetoslav683914b2015-01-15 14:22:26 -08001445 private static String getSettingValue(Bundle args) {
1446 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1447 }
1448
1449 private static String getValidTableOrThrow(Uri uri) {
1450 if (uri.getPathSegments().size() > 0) {
1451 String table = uri.getPathSegments().get(0);
1452 if (DatabaseHelper.isValidTable(table)) {
1453 return table;
1454 }
1455 throw new IllegalArgumentException("Bad root path: " + table);
1456 }
1457 throw new IllegalArgumentException("Invalid URI:" + uri);
1458 }
1459
1460 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001461 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001462 return new MatrixCursor(projection, 0);
1463 }
1464 MatrixCursor cursor = new MatrixCursor(projection, 1);
1465 appendSettingToCursor(cursor, setting);
1466 return cursor;
1467 }
1468
1469 private static String[] normalizeProjection(String[] projection) {
1470 if (projection == null) {
1471 return ALL_COLUMNS;
1472 }
1473
1474 final int columnCount = projection.length;
1475 for (int i = 0; i < columnCount; i++) {
1476 String column = projection[i];
1477 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1478 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001479 }
1480 }
1481
Svetoslav683914b2015-01-15 14:22:26 -08001482 return projection;
1483 }
1484
1485 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001486 if (setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001487 return;
1488 }
Svetoslav683914b2015-01-15 14:22:26 -08001489 final int columnCount = cursor.getColumnCount();
1490
1491 String[] values = new String[columnCount];
1492
1493 for (int i = 0; i < columnCount; i++) {
1494 String column = cursor.getColumnName(i);
1495
1496 switch (column) {
1497 case Settings.NameValueTable._ID: {
1498 values[i] = setting.getId();
1499 } break;
1500
1501 case Settings.NameValueTable.NAME: {
1502 values[i] = setting.getName();
1503 } break;
1504
1505 case Settings.NameValueTable.VALUE: {
1506 values[i] = setting.getValue();
1507 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001508 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001509 }
1510
Svetoslav683914b2015-01-15 14:22:26 -08001511 cursor.addRow(values);
1512 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001513
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001514 private static boolean isKeyValid(String key) {
1515 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1516 }
1517
Svetoslav683914b2015-01-15 14:22:26 -08001518 private static final class Arguments {
1519 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1520 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1521
1522 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1523 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1524
1525 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1526 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1527
1528 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1529 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1530
1531 public final String table;
1532 public final String name;
1533
1534 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1535 final int segmentSize = uri.getPathSegments().size();
1536 switch (segmentSize) {
1537 case 1: {
1538 if (where != null
1539 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1540 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1541 && whereArgs.length == 1) {
1542 name = whereArgs[0];
1543 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001544 return;
Svetoslav683914b2015-01-15 14:22:26 -08001545 } else if (where != null
1546 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1547 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1548 final int startIndex = Math.max(where.indexOf("'"),
1549 where.indexOf("\"")) + 1;
1550 final int endIndex = Math.max(where.lastIndexOf("'"),
1551 where.lastIndexOf("\""));
1552 name = where.substring(startIndex, endIndex);
1553 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001554 return;
Svetoslav683914b2015-01-15 14:22:26 -08001555 } else if (supportAll && where == null && whereArgs == null) {
1556 name = null;
1557 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001558 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001559 }
Svetoslav683914b2015-01-15 14:22:26 -08001560 } break;
1561
Svetoslav28494652015-02-12 14:11:42 -08001562 case 2: {
1563 if (where == null && whereArgs == null) {
1564 name = uri.getPathSegments().get(1);
1565 table = computeTableForSetting(uri, name);
1566 return;
1567 }
1568 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001569 }
Svetoslav28494652015-02-12 14:11:42 -08001570
1571 EventLogTags.writeUnsupportedSettingsQuery(
1572 uri.toSafeString(), where, Arrays.toString(whereArgs));
1573 String message = String.format( "Supported SQL:\n"
1574 + " uri content://some_table/some_property with null where and where args\n"
1575 + " uri content://some_table with query name=? and single name as arg\n"
1576 + " uri content://some_table with query name=some_name and null args\n"
1577 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1578 Arrays.toString(whereArgs));
1579 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001580 }
1581
Svetoslav28494652015-02-12 14:11:42 -08001582 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001583 String table = getValidTableOrThrow(uri);
1584
1585 if (name != null) {
1586 if (sSystemMovedToSecureSettings.contains(name)) {
1587 table = TABLE_SECURE;
1588 }
1589
1590 if (sSystemMovedToGlobalSettings.contains(name)) {
1591 table = TABLE_GLOBAL;
1592 }
1593
1594 if (sSecureMovedToGlobalSettings.contains(name)) {
1595 table = TABLE_GLOBAL;
1596 }
1597
1598 if (sGlobalMovedToSecureSettings.contains(name)) {
1599 table = TABLE_SECURE;
1600 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001601 }
Svetoslav683914b2015-01-15 14:22:26 -08001602
1603 return table;
1604 }
1605 }
1606
1607 final class SettingsRegistry {
1608 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1609
Svetoslav683914b2015-01-15 14:22:26 -08001610 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1611 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1612 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1613
1614 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1615
Svet Ganov53a441c2016-04-19 19:38:00 -07001616 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001617
Svetoslav7e0683b2015-08-03 16:02:52 -07001618 private final Handler mHandler;
1619
Svet Ganov53a441c2016-04-19 19:38:00 -07001620 private final BackupManager mBackupManager;
1621
Svetoslav683914b2015-01-15 14:22:26 -08001622 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001623 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001624 mGenerationRegistry = new GenerationRegistry(mLock);
1625 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001626 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001627 }
1628
Svetoslav683914b2015-01-15 14:22:26 -08001629 public List<String> getSettingsNamesLocked(int type, int userId) {
1630 final int key = makeKey(type, userId);
1631 SettingsState settingsState = peekSettingsStateLocked(key);
1632 return settingsState.getSettingNamesLocked();
1633 }
1634
1635 public SettingsState getSettingsLocked(int type, int userId) {
1636 final int key = makeKey(type, userId);
1637 return peekSettingsStateLocked(key);
1638 }
1639
1640 public void ensureSettingsForUserLocked(int userId) {
1641 // Migrate the setting for this user if needed.
1642 migrateLegacySettingsForUserIfNeededLocked(userId);
1643
1644 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001645 if (userId == UserHandle.USER_SYSTEM) {
1646 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001647 ensureSettingsStateLocked(globalKey);
1648 }
1649
1650 // Ensure secure settings loaded.
1651 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1652 ensureSettingsStateLocked(secureKey);
1653
1654 // Make sure the secure settings have an Android id set.
1655 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1656 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1657
1658 // Ensure system settings loaded.
1659 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1660 ensureSettingsStateLocked(systemKey);
1661
1662 // Upgrade the settings to the latest version.
1663 UpgradeController upgrader = new UpgradeController(userId);
1664 upgrader.upgradeIfNeededLocked();
1665 }
1666
1667 private void ensureSettingsStateLocked(int key) {
1668 if (mSettingsStates.get(key) == null) {
1669 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1670 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1671 maxBytesPerPackage);
1672 mSettingsStates.put(key, settingsState);
1673 }
1674 }
1675
1676 public void removeUserStateLocked(int userId, boolean permanently) {
1677 // We always keep the global settings in memory.
1678
1679 // Nuke system settings.
1680 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1681 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1682 if (systemSettingsState != null) {
1683 if (permanently) {
1684 mSettingsStates.remove(systemKey);
1685 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001686 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001687 systemSettingsState.destroyLocked(new Runnable() {
1688 @Override
1689 public void run() {
1690 mSettingsStates.remove(systemKey);
1691 }
1692 });
1693 }
1694 }
1695
1696 // Nuke secure settings.
1697 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1698 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1699 if (secureSettingsState != null) {
1700 if (permanently) {
1701 mSettingsStates.remove(secureKey);
1702 secureSettingsState.destroyLocked(null);
1703 } else {
1704 secureSettingsState.destroyLocked(new Runnable() {
1705 @Override
1706 public void run() {
1707 mSettingsStates.remove(secureKey);
1708 }
1709 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001710 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001711 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001712
1713 // Nuke generation tracking data
1714 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001715 }
1716
Svetoslav683914b2015-01-15 14:22:26 -08001717 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001718 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001719 final int key = makeKey(type, userId);
1720
1721 SettingsState settingsState = peekSettingsStateLocked(key);
1722 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1723
Svet Ganov53a441c2016-04-19 19:38:00 -07001724 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001725 notifyForSettingsChange(key, name);
1726 }
1727 return success;
1728 }
1729
Svet Ganov53a441c2016-04-19 19:38:00 -07001730 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001731 final int key = makeKey(type, userId);
1732
1733 SettingsState settingsState = peekSettingsStateLocked(key);
1734 final boolean success = settingsState.deleteSettingLocked(name);
1735
Svet Ganov53a441c2016-04-19 19:38:00 -07001736 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001737 notifyForSettingsChange(key, name);
1738 }
1739 return success;
1740 }
1741
1742 public Setting getSettingLocked(int type, int userId, String name) {
1743 final int key = makeKey(type, userId);
1744
1745 SettingsState settingsState = peekSettingsStateLocked(key);
1746 return settingsState.getSettingLocked(name);
1747 }
1748
1749 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001750 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001751 final int key = makeKey(type, userId);
1752
1753 SettingsState settingsState = peekSettingsStateLocked(key);
1754 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1755
Svet Ganov53a441c2016-04-19 19:38:00 -07001756 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001757 notifyForSettingsChange(key, name);
1758 }
1759
1760 return success;
1761 }
1762
1763 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001764 // Global and secure settings are signature protected. Apps signed
1765 // by the platform certificate are generally not uninstalled and
1766 // the main exception is tests. We trust components signed
1767 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001768
1769 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1770 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001771 if (systemSettings != null) {
1772 systemSettings.onPackageRemovedLocked(packageName);
1773 }
Svetoslav683914b2015-01-15 14:22:26 -08001774 }
1775
1776 private SettingsState peekSettingsStateLocked(int key) {
1777 SettingsState settingsState = mSettingsStates.get(key);
1778 if (settingsState != null) {
1779 return settingsState;
1780 }
1781
1782 ensureSettingsForUserLocked(getUserIdFromKey(key));
1783 return mSettingsStates.get(key);
1784 }
1785
1786 private void migrateAllLegacySettingsIfNeeded() {
1787 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001788 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001789 File globalFile = getSettingsFile(key);
1790 if (globalFile.exists()) {
1791 return;
1792 }
1793
1794 final long identity = Binder.clearCallingIdentity();
1795 try {
1796 List<UserInfo> users = mUserManager.getUsers(true);
1797
1798 final int userCount = users.size();
1799 for (int i = 0; i < userCount; i++) {
1800 final int userId = users.get(i).id;
1801
1802 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1803 SQLiteDatabase database = dbHelper.getWritableDatabase();
1804 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1805
1806 // Upgrade to the latest version.
1807 UpgradeController upgrader = new UpgradeController(userId);
1808 upgrader.upgradeIfNeededLocked();
1809
1810 // Drop from memory if not a running user.
1811 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1812 removeUserStateLocked(userId, false);
1813 }
1814 }
1815 } finally {
1816 Binder.restoreCallingIdentity(identity);
1817 }
1818 }
1819 }
1820
1821 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1822 // Every user has secure settings and if no file we need to migrate.
1823 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1824 File secureFile = getSettingsFile(secureKey);
1825 if (secureFile.exists()) {
1826 return;
1827 }
1828
1829 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1830 SQLiteDatabase database = dbHelper.getWritableDatabase();
1831
1832 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1833 }
1834
1835 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1836 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001837 // Move over the system settings.
1838 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1839 ensureSettingsStateLocked(systemKey);
1840 SettingsState systemSettings = mSettingsStates.get(systemKey);
1841 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1842 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001843
1844 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001845 // Do this after System settings, since this is the first thing we check when deciding
1846 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001847 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1848 ensureSettingsStateLocked(secureKey);
1849 SettingsState secureSettings = mSettingsStates.get(secureKey);
1850 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1851 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1852 secureSettings.persistSyncLocked();
1853
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001854 // Move over the global settings if owner.
1855 // Do this last, since this is the first thing we check when deciding
1856 // to skip over migration from db to xml for owner user.
1857 if (userId == UserHandle.USER_SYSTEM) {
1858 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1859 ensureSettingsStateLocked(globalKey);
1860 SettingsState globalSettings = mSettingsStates.get(globalKey);
1861 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1862 globalSettings.persistSyncLocked();
1863 }
Svetoslav683914b2015-01-15 14:22:26 -08001864
1865 // Drop the database as now all is moved and persisted.
1866 if (DROP_DATABASE_ON_MIGRATION) {
1867 dbHelper.dropDatabase();
1868 } else {
1869 dbHelper.backupDatabase();
1870 }
1871 }
1872
1873 private void migrateLegacySettingsLocked(SettingsState settingsState,
1874 SQLiteDatabase database, String table) {
1875 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1876 queryBuilder.setTables(table);
1877
1878 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1879 null, null, null, null, null);
1880
1881 if (cursor == null) {
1882 return;
1883 }
1884
1885 try {
1886 if (!cursor.moveToFirst()) {
1887 return;
1888 }
1889
1890 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1891 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1892
1893 settingsState.setVersionLocked(database.getVersion());
1894
1895 while (!cursor.isAfterLast()) {
1896 String name = cursor.getString(nameColumnIdx);
1897 String value = cursor.getString(valueColumnIdx);
1898 settingsState.insertSettingLocked(name, value,
1899 SettingsState.SYSTEM_PACKAGE_NAME);
1900 cursor.moveToNext();
1901 }
1902 } finally {
1903 cursor.close();
1904 }
1905 }
1906
1907 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1908 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1909
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09001910 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001911 return;
1912 }
1913
1914 final int userId = getUserIdFromKey(secureSettings.mKey);
1915
1916 final UserInfo user;
1917 final long identity = Binder.clearCallingIdentity();
1918 try {
1919 user = mUserManager.getUserInfo(userId);
1920 } finally {
1921 Binder.restoreCallingIdentity(identity);
1922 }
1923 if (user == null) {
1924 // Can happen due to races when deleting users - treat as benign.
1925 return;
1926 }
1927
1928 String androidId = Long.toHexString(new SecureRandom().nextLong());
1929 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1930 SettingsState.SYSTEM_PACKAGE_NAME);
1931
1932 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1933 + "] for user " + userId);
1934
1935 // Write a drop box entry if it's a restricted profile
1936 if (user.isRestricted()) {
1937 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1938 Context.DROPBOX_SERVICE);
1939 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1940 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1941 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1942 }
1943 }
1944 }
1945
1946 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001947 final int userId = getUserIdFromKey(key);
1948 Uri uri = getNotificationUriFor(key, name);
1949
Svetoslav7e0683b2015-08-03 16:02:52 -07001950 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1951 userId, 0, uri).sendToTarget();
1952
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001953 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001954 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1955 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001956 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001957 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1958 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001959 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001960
1961 mGenerationRegistry.incrementGeneration(key);
1962
1963 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001964 }
1965
Svet Ganov53a441c2016-04-19 19:38:00 -07001966 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001967 Set<String> keysCloned) {
1968 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001969 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001970 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001971 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001972 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001973 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07001974 final int key = makeKey(type, profileId);
1975 mGenerationRegistry.incrementGeneration(key);
1976
1977 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001978 }
1979 }
1980 }
Svetoslav683914b2015-01-15 14:22:26 -08001981 }
1982
Svetoslav683914b2015-01-15 14:22:26 -08001983 private boolean isGlobalSettingsKey(int key) {
1984 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1985 }
1986
1987 private boolean isSystemSettingsKey(int key) {
1988 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1989 }
1990
1991 private boolean isSecureSettingsKey(int key) {
1992 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1993 }
1994
1995 private File getSettingsFile(int key) {
1996 if (isGlobalSettingsKey(key)) {
1997 final int userId = getUserIdFromKey(key);
1998 return new File(Environment.getUserSystemDirectory(userId),
1999 SETTINGS_FILE_GLOBAL);
2000 } else if (isSystemSettingsKey(key)) {
2001 final int userId = getUserIdFromKey(key);
2002 return new File(Environment.getUserSystemDirectory(userId),
2003 SETTINGS_FILE_SYSTEM);
2004 } else if (isSecureSettingsKey(key)) {
2005 final int userId = getUserIdFromKey(key);
2006 return new File(Environment.getUserSystemDirectory(userId),
2007 SETTINGS_FILE_SECURE);
2008 } else {
2009 throw new IllegalArgumentException("Invalid settings key:" + key);
2010 }
2011 }
2012
2013 private Uri getNotificationUriFor(int key, String name) {
2014 if (isGlobalSettingsKey(key)) {
2015 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2016 : Settings.Global.CONTENT_URI;
2017 } else if (isSecureSettingsKey(key)) {
2018 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2019 : Settings.Secure.CONTENT_URI;
2020 } else if (isSystemSettingsKey(key)) {
2021 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2022 : Settings.System.CONTENT_URI;
2023 } else {
2024 throw new IllegalArgumentException("Invalid settings key:" + key);
2025 }
2026 }
2027
2028 private int getMaxBytesPerPackageForType(int type) {
2029 switch (type) {
2030 case SETTINGS_TYPE_GLOBAL:
2031 case SETTINGS_TYPE_SECURE: {
2032 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2033 }
2034
2035 default: {
2036 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2037 }
2038 }
2039 }
2040
Svetoslav7e0683b2015-08-03 16:02:52 -07002041 private final class MyHandler extends Handler {
2042 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2043 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2044
2045 public MyHandler(Looper looper) {
2046 super(looper);
2047 }
2048
2049 @Override
2050 public void handleMessage(Message msg) {
2051 switch (msg.what) {
2052 case MSG_NOTIFY_URI_CHANGED: {
2053 final int userId = msg.arg1;
2054 Uri uri = (Uri) msg.obj;
2055 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2056 if (DEBUG) {
2057 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2058 }
2059 } break;
2060
2061 case MSG_NOTIFY_DATA_CHANGED: {
2062 mBackupManager.dataChanged();
2063 } break;
2064 }
2065 }
2066 }
2067
Svetoslav683914b2015-01-15 14:22:26 -08002068 private final class UpgradeController {
Daniel U02ba6122016-04-01 18:41:42 +01002069 private static final int SETTINGS_VERSION = 127;
Svetoslav683914b2015-01-15 14:22:26 -08002070
2071 private final int mUserId;
2072
2073 public UpgradeController(int userId) {
2074 mUserId = userId;
2075 }
2076
2077 public void upgradeIfNeededLocked() {
2078 // The version of all settings for a user is the same (all users have secure).
2079 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002080 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002081
2082 // Try an update from the current state.
2083 final int oldVersion = secureSettings.getVersionLocked();
2084 final int newVersion = SETTINGS_VERSION;
2085
Svet Ganovc9755bc2015-03-28 13:21:22 -07002086 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002087 if (oldVersion == newVersion) {
2088 return;
2089 }
2090
2091 // Try to upgrade.
2092 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2093
2094 // If upgrade failed start from scratch and upgrade.
2095 if (curVersion != newVersion) {
2096 // Drop state we have for this user.
2097 removeUserStateLocked(mUserId, true);
2098
2099 // Recreate the database.
2100 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2101 SQLiteDatabase database = dbHelper.getWritableDatabase();
2102 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2103
2104 // Migrate the settings for this user.
2105 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2106
2107 // Now upgrade should work fine.
2108 onUpgradeLocked(mUserId, oldVersion, newVersion);
2109 }
2110
2111 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002112 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002113 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002114 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002115 globalSettings.setVersionLocked(newVersion);
2116 }
2117
2118 // Set the secure settings version.
2119 secureSettings.setVersionLocked(newVersion);
2120
2121 // Set the system settings version.
2122 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002123 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002124 systemSettings.setVersionLocked(newVersion);
2125 }
2126
2127 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002128 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002129 }
2130
2131 private SettingsState getSecureSettingsLocked(int userId) {
2132 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2133 }
2134
2135 private SettingsState getSystemSettingsLocked(int userId) {
2136 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2137 }
2138
Jeff Brown503cffc2015-03-26 18:08:51 -07002139 /**
2140 * You must perform all necessary mutations to bring the settings
2141 * for this user from the old to the new version. When you add a new
2142 * upgrade step you *must* update SETTINGS_VERSION.
2143 *
2144 * This is an example of moving a setting from secure to global.
2145 *
2146 * // v119: Example settings changes.
2147 * if (currentVersion == 118) {
2148 * if (userId == UserHandle.USER_OWNER) {
2149 * // Remove from the secure settings.
2150 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2151 * String name = "example_setting_to_move";
2152 * String value = secureSettings.getSetting(name);
2153 * secureSettings.deleteSetting(name);
2154 *
2155 * // Add to the global settings.
2156 * SettingsState globalSettings = getGlobalSettingsLocked();
2157 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2158 * }
2159 *
2160 * // Update the current version.
2161 * currentVersion = 119;
2162 * }
2163 */
Svetoslav683914b2015-01-15 14:22:26 -08002164 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2165 if (DEBUG) {
2166 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2167 + oldVersion + " to version: " + newVersion);
2168 }
2169
Jeff Brown503cffc2015-03-26 18:08:51 -07002170 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002171
John Spurlocke11ae112015-05-11 16:09:03 -04002172 // v119: Reset zen + ringer mode.
2173 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002174 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002175 final SettingsState globalSettings = getGlobalSettingsLocked();
2176 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2177 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2178 SettingsState.SYSTEM_PACKAGE_NAME);
2179 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2180 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2181 SettingsState.SYSTEM_PACKAGE_NAME);
2182 }
2183 currentVersion = 119;
2184 }
2185
Jason Monk27bbb2d2015-03-31 16:46:39 -04002186 // v120: Add double tap to wake setting.
2187 if (currentVersion == 119) {
2188 SettingsState secureSettings = getSecureSettingsLocked(userId);
2189 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2190 getContext().getResources().getBoolean(
2191 R.bool.def_double_tap_to_wake) ? "1" : "0",
2192 SettingsState.SYSTEM_PACKAGE_NAME);
2193
2194 currentVersion = 120;
2195 }
2196
Svetoslav7e0683b2015-08-03 16:02:52 -07002197 if (currentVersion == 120) {
2198 // Before 121, we used a different string encoding logic. We just bump the
2199 // version here; SettingsState knows how to handle pre-version 120 files.
2200 currentVersion = 121;
2201 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002202
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002203 if (currentVersion == 121) {
2204 // Version 122: allow OEMs to set a default payment component in resources.
2205 // Note that we only write the default if no default has been set;
2206 // if there is, we just leave the default at whatever it currently is.
2207 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2208 String defaultComponent = (getContext().getResources().getString(
2209 R.string.def_nfc_payment_component));
2210 Setting currentSetting = secureSettings.getSettingLocked(
2211 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2212 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002213 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002214 secureSettings.insertSettingLocked(
2215 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2216 defaultComponent,
2217 SettingsState.SYSTEM_PACKAGE_NAME);
2218 }
2219 currentVersion = 122;
2220 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002221
2222 if (currentVersion == 122) {
2223 // Version 123: Adding a default value for the ability to add a user from
2224 // the lock screen.
2225 if (userId == UserHandle.USER_SYSTEM) {
2226 final SettingsState globalSettings = getGlobalSettingsLocked();
2227 Setting currentSetting = globalSettings.getSettingLocked(
2228 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002229 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002230 globalSettings.insertSettingLocked(
2231 Settings.Global.ADD_USERS_WHEN_LOCKED,
2232 getContext().getResources().getBoolean(
2233 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2234 SettingsState.SYSTEM_PACKAGE_NAME);
2235 }
2236 }
2237 currentVersion = 123;
2238 }
Bryce Leebd179282015-12-17 19:01:37 -08002239
2240 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002241 final SettingsState globalSettings = getGlobalSettingsLocked();
2242 String defaultDisabledProfiles = (getContext().getResources().getString(
2243 R.string.def_bluetooth_disabled_profiles));
2244 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2245 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002246 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002247 }
2248
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002249 if (currentVersion == 124) {
2250 // Version 124: allow OEMs to set a default value for whether IME should be
2251 // shown when a physical keyboard is connected.
2252 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2253 Setting currentSetting = secureSettings.getSettingLocked(
2254 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002255 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002256 secureSettings.insertSettingLocked(
2257 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2258 getContext().getResources().getBoolean(
2259 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2260 SettingsState.SYSTEM_PACKAGE_NAME);
2261 }
2262 currentVersion = 125;
2263 }
2264
Ruben Brunk98576cf2016-03-07 18:54:28 -08002265 if (currentVersion == 125) {
2266 // Version 125: Allow OEMs to set the default VR service.
2267 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2268
2269 Setting currentSetting = secureSettings.getSettingLocked(
2270 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002271 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002272 ArraySet<ComponentName> l =
2273 SystemConfig.getInstance().getDefaultVrComponents();
2274
2275 if (l != null && !l.isEmpty()) {
2276 StringBuilder b = new StringBuilder();
2277 boolean start = true;
2278 for (ComponentName c : l) {
2279 if (!start) {
2280 b.append(':');
2281 }
2282 b.append(c.flattenToString());
2283 start = false;
2284 }
2285 secureSettings.insertSettingLocked(
2286 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2287 SettingsState.SYSTEM_PACKAGE_NAME);
2288 }
2289
2290 }
2291 currentVersion = 126;
2292 }
2293
Daniel U02ba6122016-04-01 18:41:42 +01002294 if (currentVersion == 126) {
2295 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2296 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2297 if (mUserManager.isManagedProfile(userId)) {
2298 final SettingsState systemSecureSettings =
2299 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2300
2301 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2302 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002303 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002304 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2305 secureSettings.insertSettingLocked(
2306 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2307 showNotifications.getValue(),
2308 SettingsState.SYSTEM_PACKAGE_NAME);
2309 }
2310
2311 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2312 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002313 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002314 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2315 secureSettings.insertSettingLocked(
2316 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2317 allowPrivate.getValue(),
2318 SettingsState.SYSTEM_PACKAGE_NAME);
2319 }
2320 }
2321 currentVersion = 127;
2322 }
2323
Jeff Brown503cffc2015-03-26 18:08:51 -07002324 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002325
Jeff Brown503cffc2015-03-26 18:08:51 -07002326 // Return the current version.
2327 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002328 }
2329 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002330 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002331}