blob: cbbb8094d06df55e66204435f4f6693a89664500 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
Svetoslav683914b2015-01-15 14:22:26 -080019import android.Manifest;
Christopher Tated5fe1472012-09-10 15:48:38 -070020import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070021import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080022import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070023import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080024import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070026import android.content.ContentValues;
27import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.Intent;
29import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080030import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070031import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070034import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040040import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070045import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070047import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070048import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070049import 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;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070055import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070056import android.os.UserHandle;
57import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070058import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059import android.provider.Settings;
Jeremy Joslin8bdad342016-12-14 11:46:47 -080060import android.provider.Settings.Global;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010062import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080063import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000064import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070065import android.util.Slog;
66import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070067import android.util.SparseBooleanArray;
John Spurlocke11ae112015-05-11 16:09:03 -040068
Svetoslav683914b2015-01-15 14:22:26 -080069import com.android.internal.annotations.GuardedBy;
70import com.android.internal.content.PackageMonitor;
71import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080072import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070073import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080074import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040075
Svetoslav683914b2015-01-15 14:22:26 -080076import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080077import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080078import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080079import java.io.PrintWriter;
Mark Rathjend891f012017-01-19 04:10:37 +000080import java.nio.charset.StandardCharsets;
Mark Rathjen7599f132017-01-23 14:15:54 -080081import java.nio.ByteBuffer;
82import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000083import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080084import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070085import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080086import java.util.Arrays;
Mark Rathjend891f012017-01-19 04:10:37 +000087import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080089import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010090import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.util.Set;
92import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080093import javax.crypto.Mac;
94import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070095
Svetoslav Ganove080da92016-12-21 17:10:35 -080096import static android.os.Process.ROOT_UID;
97import static android.os.Process.SYSTEM_UID;
98import static android.os.Process.SHELL_UID;
99
Svetoslav683914b2015-01-15 14:22:26 -0800100/**
101 * <p>
102 * This class is a content provider that publishes the system settings.
103 * It can be accessed via the content provider APIs or via custom call
104 * commands. The latter is a bit faster and is the preferred way to access
105 * the platform settings.
106 * </p>
107 * <p>
108 * There are three settings types, global (with signature level protection
109 * and shared across users), secure (with signature permission level
110 * protection and per user), and system (with dangerous permission level
111 * protection and per user). Global settings are stored under the device owner.
112 * Each of these settings is represented by a {@link
113 * com.android.providers.settings.SettingsState} object mapped to an integer
114 * key derived from the setting type in the most significant bits and user
115 * id in the least significant bits. Settings are synchronously loaded on
116 * instantiation of a SettingsState and asynchronously persisted on mutation.
117 * Settings are stored in the user specific system directory.
118 * </p>
119 * <p>
120 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
121 * and get a warning. Targeting higher API version prohibits this as the
122 * system settings are not a place for apps to save their state. When a package
123 * is removed the settings it added are deleted. Apps cannot delete system
124 * settings added by the platform. System settings values are validated to
125 * ensure the clients do not put bad values. Global and secure settings are
126 * changed only by trusted parties, therefore no validation is performed. Also
127 * there is a limit on the amount of app specific settings that can be added
128 * to prevent unlimited growth of the system process memory footprint.
129 * </p>
130 */
131@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700132public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700133 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700134
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700135 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800136
137 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700138
Christopher Tate06efb532012-08-24 15:29:27 -0700139 private static final String TABLE_SYSTEM = "system";
140 private static final String TABLE_SECURE = "secure";
141 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800142
143 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private static final String TABLE_FAVORITES = "favorites";
145 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800146 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
147 private static final String TABLE_BOOKMARKS = "bookmarks";
148 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Svetoslav683914b2015-01-15 14:22:26 -0800150 // The set of removed legacy tables.
151 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700152 static {
Svetoslav683914b2015-01-15 14:22:26 -0800153 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
154 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
155 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
156 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
157 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
158 }
Christopher Tate06efb532012-08-24 15:29:27 -0700159
Svetoslav683914b2015-01-15 14:22:26 -0800160 private static final int MUTATION_OPERATION_INSERT = 1;
161 private static final int MUTATION_OPERATION_DELETE = 2;
162 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800163 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400164
Svetoslav683914b2015-01-15 14:22:26 -0800165 private static final String[] ALL_COLUMNS = new String[] {
166 Settings.NameValueTable._ID,
167 Settings.NameValueTable.NAME,
168 Settings.NameValueTable.VALUE
169 };
170
Svet Ganov53a441c2016-04-19 19:38:00 -0700171 public static final int SETTINGS_TYPE_GLOBAL = 0;
172 public static final int SETTINGS_TYPE_SYSTEM = 1;
173 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000174 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800175
Svet Ganov53a441c2016-04-19 19:38:00 -0700176 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
177 public static final int SETTINGS_TYPE_SHIFT = 28;
178
179 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
180 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700181
Svetoslav683914b2015-01-15 14:22:26 -0800182 // Per user secure settings that moved to the for all users global settings.
183 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
184 static {
185 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700186 }
187
Svetoslav683914b2015-01-15 14:22:26 -0800188 // Per user system settings that moved to the for all users global settings.
189 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
190 static {
191 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700192 }
193
Svetoslav683914b2015-01-15 14:22:26 -0800194 // Per user system settings that moved to the per user secure settings.
195 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
196 static {
197 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700198 }
199
Svetoslav683914b2015-01-15 14:22:26 -0800200 // Per all users global settings that moved to the per user secure settings.
201 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
202 static {
203 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700204 }
205
Svetoslav683914b2015-01-15 14:22:26 -0800206 // Per user secure settings that are cloned for the managed profiles of the user.
207 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
208 static {
209 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700210 }
211
Svetoslav683914b2015-01-15 14:22:26 -0800212 // Per user system settings that are cloned for the managed profiles of the user.
213 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
214 static {
215 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400216 }
217
Andre Lago3fa139c2016-08-04 13:53:44 +0100218 // Per user system settings that are cloned from the profile's parent when a dependency
219 // in {@link Settings.Secure} is set to "1".
220 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
221 static {
222 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
223 }
224
Svetoslav683914b2015-01-15 14:22:26 -0800225 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700226
Svetoslav683914b2015-01-15 14:22:26 -0800227 @GuardedBy("mLock")
228 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700229
Svet Ganova8f90262016-05-10 08:44:48 -0700230 @GuardedBy("mLock")
231 private HandlerThread mHandlerThread;
232
Svetoslav7ec28e82015-05-20 17:01:10 -0700233 // We have to call in the user manager with no lock held,
234 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800235
Svetoslav7ec28e82015-05-20 17:01:10 -0700236 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700237 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700238
Svet Ganov53a441c2016-04-19 19:38:00 -0700239 public static int makeKey(int type, int userId) {
240 return (type << SETTINGS_TYPE_SHIFT) | userId;
241 }
242
243 public static int getTypeFromKey(int key) {
244 return key >>> SETTINGS_TYPE_SHIFT;
245 }
246
247 public static int getUserIdFromKey(int key) {
248 return key & ~SETTINGS_TYPE_MASK;
249 }
250
251 public static String settingTypeToString(int type) {
252 switch (type) {
253 case SETTINGS_TYPE_GLOBAL: {
254 return "SETTINGS_GLOBAL";
255 }
256 case SETTINGS_TYPE_SECURE: {
257 return "SETTINGS_SECURE";
258 }
259 case SETTINGS_TYPE_SYSTEM: {
260 return "SETTINGS_SYSTEM";
261 }
Mark Rathjend891f012017-01-19 04:10:37 +0000262 case SETTINGS_TYPE_SSAID: {
263 return "SETTINGS_SSAID";
264 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700265 default: {
266 return "UNKNOWN";
267 }
268 }
269 }
270
271 public static String keyToString(int key) {
272 return "Key[user=" + getUserIdFromKey(key) + ";type="
273 + settingTypeToString(getTypeFromKey(key)) + "]";
274 }
275
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 @Override
277 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800278 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700279 mUserManager = UserManager.get(getContext());
280 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700281 mHandlerThread = new HandlerThread(LOG_TAG,
282 Process.THREAD_PRIORITY_BACKGROUND);
283 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800284 mSettingsRegistry = new SettingsRegistry();
285 }
286 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700287 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700288 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700289 return true;
290 }
291
Svetoslav683914b2015-01-15 14:22:26 -0800292 @Override
293 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700294 final int requestingUserId = getRequestingUserId(args);
295 switch (method) {
296 case Settings.CALL_METHOD_GET_GLOBAL: {
297 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700298 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800299 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700300
301 case Settings.CALL_METHOD_GET_SECURE: {
302 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700303 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700304 }
305
306 case Settings.CALL_METHOD_GET_SYSTEM: {
307 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700308 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700309 }
310
311 case Settings.CALL_METHOD_PUT_GLOBAL: {
312 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800313 String tag = getSettingTag(args);
314 final boolean makeDefault = getSettingMakeDefault(args);
315 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700316 break;
317 }
318
319 case Settings.CALL_METHOD_PUT_SECURE: {
320 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800321 String tag = getSettingTag(args);
322 final boolean makeDefault = getSettingMakeDefault(args);
323 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700324 break;
325 }
326
327 case Settings.CALL_METHOD_PUT_SYSTEM: {
328 String value = getSettingValue(args);
329 insertSystemSetting(name, value, requestingUserId);
330 break;
331 }
332
Svetoslav Ganove080da92016-12-21 17:10:35 -0800333 case Settings.CALL_METHOD_RESET_GLOBAL: {
334 final int mode = getResetModeEnforcingPermission(args);
335 String tag = getSettingTag(args);
336 resetGlobalSetting(requestingUserId, mode, tag);
337 break;
338 }
339
340 case Settings.CALL_METHOD_RESET_SECURE: {
341 final int mode = getResetModeEnforcingPermission(args);
342 String tag = getSettingTag(args);
343 resetSecureSetting(requestingUserId, mode, tag);
344 break;
345 }
346
Svetoslav7ec28e82015-05-20 17:01:10 -0700347 default: {
348 Slog.w(LOG_TAG, "call() with invalid method: " + method);
349 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700350 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700351
Christopher Tate06efb532012-08-24 15:29:27 -0700352 return null;
353 }
354
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800355 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800356 public String getType(Uri uri) {
357 Arguments args = new Arguments(uri, null, null, true);
358 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 return "vnd.android.cursor.dir/" + args.table;
360 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700361 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700362 }
363 }
364
365 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800366 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
367 String order) {
368 if (DEBUG) {
369 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370 }
371
Svetoslav683914b2015-01-15 14:22:26 -0800372 Arguments args = new Arguments(uri, where, whereArgs, true);
373 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700374
Svetoslav683914b2015-01-15 14:22:26 -0800375 // If a legacy table that is gone, done.
376 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
377 return new MatrixCursor(normalizedProjection, 0);
378 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700379
Svetoslav7ec28e82015-05-20 17:01:10 -0700380 switch (args.table) {
381 case TABLE_GLOBAL: {
382 if (args.name != null) {
383 Setting setting = getGlobalSetting(args.name);
384 return packageSettingForQuery(setting, normalizedProjection);
385 } else {
386 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700387 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700388 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700389
Svetoslav7ec28e82015-05-20 17:01:10 -0700390 case TABLE_SECURE: {
391 final int userId = UserHandle.getCallingUserId();
392 if (args.name != null) {
393 Setting setting = getSecureSetting(args.name, userId);
394 return packageSettingForQuery(setting, normalizedProjection);
395 } else {
396 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800397 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700398 }
Svetoslav683914b2015-01-15 14:22:26 -0800399
Svetoslav7ec28e82015-05-20 17:01:10 -0700400 case TABLE_SYSTEM: {
401 final int userId = UserHandle.getCallingUserId();
402 if (args.name != null) {
403 Setting setting = getSystemSetting(args.name, userId);
404 return packageSettingForQuery(setting, normalizedProjection);
405 } else {
406 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800407 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700408 }
Svetoslav683914b2015-01-15 14:22:26 -0800409
Svetoslav7ec28e82015-05-20 17:01:10 -0700410 default: {
411 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700412 }
413 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700414 }
415
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700416 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800417 public Uri insert(Uri uri, ContentValues values) {
418 if (DEBUG) {
419 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700420 }
421
Svetoslav683914b2015-01-15 14:22:26 -0800422 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700423
Svetoslav683914b2015-01-15 14:22:26 -0800424 // If a legacy table that is gone, done.
425 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 return null;
427 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700428
Svetoslav683914b2015-01-15 14:22:26 -0800429 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700430 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800431 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700432 }
433
Svetoslav683914b2015-01-15 14:22:26 -0800434 String value = values.getAsString(Settings.Secure.VALUE);
435
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 switch (table) {
437 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800438 if (insertGlobalSetting(name, value, null, false,
439 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700440 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700441 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700442 } break;
443
444 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800445 if (insertSecureSetting(name, value, null, false,
446 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700447 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
448 }
449 } break;
450
451 case TABLE_SYSTEM: {
452 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
453 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
454 }
455 } break;
456
457 default: {
458 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700459 }
460 }
461
Svetoslav683914b2015-01-15 14:22:26 -0800462 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700463 }
464
465 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800466 public int bulkInsert(Uri uri, ContentValues[] allValues) {
467 if (DEBUG) {
468 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700470
Svetoslav683914b2015-01-15 14:22:26 -0800471 int insertionCount = 0;
472 final int valuesCount = allValues.length;
473 for (int i = 0; i < valuesCount; i++) {
474 ContentValues values = allValues[i];
475 if (insert(uri, values) != null) {
476 insertionCount++;
477 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700478 }
Svetoslav683914b2015-01-15 14:22:26 -0800479
480 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700481 }
482
483 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800484 public int delete(Uri uri, String where, String[] whereArgs) {
485 if (DEBUG) {
486 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700488
Svetoslav683914b2015-01-15 14:22:26 -0800489 Arguments args = new Arguments(uri, where, whereArgs, false);
490
491 // If a legacy table that is gone, done.
492 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
493 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700494 }
Svetoslav683914b2015-01-15 14:22:26 -0800495
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700496 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800497 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700498 }
Svetoslav683914b2015-01-15 14:22:26 -0800499
Svetoslav7ec28e82015-05-20 17:01:10 -0700500 switch (args.table) {
501 case TABLE_GLOBAL: {
502 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700503 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700504 }
Svetoslav683914b2015-01-15 14:22:26 -0800505
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 case TABLE_SECURE: {
507 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700508 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700509 }
Svetoslav683914b2015-01-15 14:22:26 -0800510
Svetoslav7ec28e82015-05-20 17:01:10 -0700511 case TABLE_SYSTEM: {
512 final int userId = UserHandle.getCallingUserId();
513 return deleteSystemSetting(args.name, userId) ? 1 : 0;
514 }
515
516 default: {
517 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800518 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700519 }
Svetoslav683914b2015-01-15 14:22:26 -0800520 }
521
522 @Override
523 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
524 if (DEBUG) {
525 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700526 }
Svetoslav683914b2015-01-15 14:22:26 -0800527
528 Arguments args = new Arguments(uri, where, whereArgs, false);
529
530 // If a legacy table that is gone, done.
531 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
532 return 0;
533 }
534
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700535 String name = values.getAsString(Settings.Secure.NAME);
536 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800537 return 0;
538 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700539 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800540
Svetoslav7ec28e82015-05-20 17:01:10 -0700541 switch (args.table) {
542 case TABLE_GLOBAL: {
543 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800544 return updateGlobalSetting(args.name, value, null, false,
545 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700546 }
Svetoslav683914b2015-01-15 14:22:26 -0800547
Svetoslav7ec28e82015-05-20 17:01:10 -0700548 case TABLE_SECURE: {
549 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800550 return updateSecureSetting(args.name, value, null, false,
551 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 }
Svetoslav683914b2015-01-15 14:22:26 -0800553
Svetoslav7ec28e82015-05-20 17:01:10 -0700554 case TABLE_SYSTEM: {
555 final int userId = UserHandle.getCallingUserId();
556 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
557 }
Svetoslav683914b2015-01-15 14:22:26 -0800558
Svetoslav7ec28e82015-05-20 17:01:10 -0700559 default: {
560 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800561 }
562 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700563 }
564
565 @Override
566 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100567 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
568 if (userId != UserHandle.getCallingUserId()) {
569 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
570 "Access files from the settings of another user");
571 }
572 uri = ContentProvider.getUriWithoutUserId(uri);
573
Andre Lago3fa139c2016-08-04 13:53:44 +0100574 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700575 final String cacheName;
576 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100577 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700578 cacheName = Settings.System.RINGTONE_CACHE;
579 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100580 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700581 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
582 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100583 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700584 cacheName = Settings.System.ALARM_ALERT_CACHE;
585 } else {
586 throw new FileNotFoundException("Direct file access no longer supported; "
587 + "ringtone playback is available through android.media.Ringtone");
588 }
589
Andre Lago3fa139c2016-08-04 13:53:44 +0100590 int actualCacheOwner;
591 // Redirect cache to parent if ringtone setting is owned by profile parent
592 synchronized (mLock) {
593 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
594 cacheRingtoneSetting);
595 }
596 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700597 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
598 }
599
600 private File getRingtoneCacheDir(int userId) {
601 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
602 cacheDir.mkdir();
603 SELinux.restorecon(cacheDir);
604 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700605 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800606
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700607 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800608 synchronized (mLock) {
609 final long identity = Binder.clearCallingIdentity();
610 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700611 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800612 final int userCount = users.size();
613 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700614 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800615 }
616 } finally {
617 Binder.restoreCallingIdentity(identity);
618 }
619 }
620 }
621
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700622 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700623 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800624 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700625 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
626 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700627 if (globalSettings != null) {
628 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800629 pw.println();
630 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700631 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800632 }
633
634 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700635 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
636 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700637 if (secureSettings != null) {
638 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800639 pw.println();
640 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700641 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700642
Svetoslavb505ccc2015-02-17 12:41:04 -0800643 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700644 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
645 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700646 if (systemSettings != null) {
647 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800648 pw.println();
649 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700650 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800651 }
652
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700653 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
654 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800655
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700656 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800657
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700658 for (int i = 0; i < nameCount; i++) {
659 String name = names.get(i);
660 Setting setting = settingsState.getSettingLocked(name);
661 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
662 pw.print(" name:"); pw.print(toDumpString(name));
663 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800664 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700665 }
666 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800667 if (setting.getDefaultValue() != null) {
668 pw.print(" default:"); pw.print(setting.getDefaultValue());
669 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultSystemSet());
670 }
671 if (setting.getTag() != null) {
672 pw.print(" tag:"); pw.print(setting.getTag());
673 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800674 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700675 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800676 }
677
Svetoslav7e0683b2015-08-03 16:02:52 -0700678 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700679 if (s != null) {
680 return s;
681 }
682 return "{null}";
683 }
684
Svetoslav683914b2015-01-15 14:22:26 -0800685 private void registerBroadcastReceivers() {
686 IntentFilter userFilter = new IntentFilter();
687 userFilter.addAction(Intent.ACTION_USER_REMOVED);
688 userFilter.addAction(Intent.ACTION_USER_STOPPED);
689
690 getContext().registerReceiver(new BroadcastReceiver() {
691 @Override
692 public void onReceive(Context context, Intent intent) {
693 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700694 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800695
696 switch (intent.getAction()) {
697 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700698 synchronized (mLock) {
699 mSettingsRegistry.removeUserStateLocked(userId, true);
700 }
Svetoslav683914b2015-01-15 14:22:26 -0800701 } break;
702
703 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700704 synchronized (mLock) {
705 mSettingsRegistry.removeUserStateLocked(userId, false);
706 }
Svetoslav683914b2015-01-15 14:22:26 -0800707 } break;
708 }
709 }
710 }, userFilter);
711
712 PackageMonitor monitor = new PackageMonitor() {
713 @Override
714 public void onPackageRemoved(String packageName, int uid) {
715 synchronized (mLock) {
716 mSettingsRegistry.onPackageRemovedLocked(packageName,
717 UserHandle.getUserId(uid));
718 }
719 }
Mark Rathjend891f012017-01-19 04:10:37 +0000720
721 @Override
722 public void onUidRemoved(int uid) {
723 synchronized (mLock) {
724 mSettingsRegistry.onUidRemovedLocked(uid);
725 }
726 }
Svetoslav683914b2015-01-15 14:22:26 -0800727 };
728
729 // package changes
730 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
731 UserHandle.ALL, true);
732 }
733
Svet Ganov53a441c2016-04-19 19:38:00 -0700734 private void startWatchingUserRestrictionChanges() {
735 // TODO: The current design of settings looking different based on user restrictions
736 // should be reworked to keep them separate and system code should check the setting
737 // first followed by checking the user restriction before performing an operation.
738 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
739 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
740 Bundle prevRestrictions) -> {
741 // We are changing the settings affected by restrictions to their current
742 // value with a forced update to ensure that all cross profile dependencies
743 // are taken into account. Also make sure the settings update to.. the same
744 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800745 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
746 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700747 final long identity = Binder.clearCallingIdentity();
748 try {
749 synchronized (mLock) {
750 Setting setting = getSecureSetting(
751 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
752 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800753 setting != null ? setting.getValue() : null, null,
754 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700755 }
756 } finally {
757 Binder.restoreCallingIdentity(identity);
758 }
759 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800760 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
761 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700762 final long identity = Binder.clearCallingIdentity();
763 try {
764 synchronized (mLock) {
765 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800766 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700767 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800768 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700769 }
770 } finally {
771 Binder.restoreCallingIdentity(identity);
772 }
773 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800774 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
775 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700776 final long identity = Binder.clearCallingIdentity();
777 try {
778 synchronized (mLock) {
779 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800780 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700781 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800782 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700783 }
784 } finally {
785 Binder.restoreCallingIdentity(identity);
786 }
787 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800788 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
789 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700790 final long identity = Binder.clearCallingIdentity();
791 try {
792 synchronized (mLock) {
793 Setting enable = getGlobalSetting(
794 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800795 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700796 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800797 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700798 Setting include = getGlobalSetting(
799 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800800 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700801 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800802 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 }
804 } finally {
805 Binder.restoreCallingIdentity(identity);
806 }
807 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800808 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
809 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700810 final long identity = Binder.clearCallingIdentity();
811 try {
812 synchronized (mLock) {
813 Setting setting = getGlobalSetting(
814 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700816 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800817 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700818 }
819 } finally {
820 Binder.restoreCallingIdentity(identity);
821 }
822 }
823 });
824 }
825
Svetoslav7ec28e82015-05-20 17:01:10 -0700826 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800827 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700828 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800829 }
830
Svetoslav7ec28e82015-05-20 17:01:10 -0700831 synchronized (mLock) {
832 // Get the settings.
833 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700834 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800835
Svetoslav7ec28e82015-05-20 17:01:10 -0700836 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800837
Svetoslav7ec28e82015-05-20 17:01:10 -0700838 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800839
Svetoslav7ec28e82015-05-20 17:01:10 -0700840 String[] normalizedProjection = normalizeProjection(projection);
841 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800842
Svetoslav7ec28e82015-05-20 17:01:10 -0700843 // Anyone can get the global settings, so no security checks.
844 for (int i = 0; i < nameCount; i++) {
845 String name = names.get(i);
846 Setting setting = settingsState.getSettingLocked(name);
847 appendSettingToCursor(result, setting);
848 }
849
850 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800851 }
Svetoslav683914b2015-01-15 14:22:26 -0800852 }
853
Svetoslav7ec28e82015-05-20 17:01:10 -0700854 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800855 if (DEBUG) {
856 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
857 }
858
859 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700860 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700861 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700862 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800863 }
Svetoslav683914b2015-01-15 14:22:26 -0800864 }
865
Svetoslav Ganove080da92016-12-21 17:10:35 -0800866 private boolean updateGlobalSetting(String name, String value, String tag,
867 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800868 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800869 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
870 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
871 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800872 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800873 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
874 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800875 }
876
Svetoslav Ganove080da92016-12-21 17:10:35 -0800877 private boolean insertGlobalSetting(String name, String value, String tag,
878 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700879 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800880 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
881 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
882 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700883 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800884 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
885 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700886 }
887
Svet Ganov53a441c2016-04-19 19:38:00 -0700888 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800889 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800890 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
891 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800892 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800893 return mutateGlobalSetting(name, null, null, false, requestingUserId,
894 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800895 }
896
Svetoslav Ganove080da92016-12-21 17:10:35 -0800897 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
898 if (DEBUG) {
899 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
900 + mode + ", " + tag + ")");
901 }
902 mutateGlobalSetting(null, null, tag, false, requestingUserId,
903 MUTATION_OPERATION_RESET, false, mode);
904 }
905
906 private boolean mutateGlobalSetting(String name, String value, String tag,
907 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
908 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800909 // Make sure the caller can change the settings - treated as secure.
910 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
911
Svetoslav683914b2015-01-15 14:22:26 -0800912 // Resolve the userId on whose behalf the call is made.
913 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
914
Makoto Onuki28da2e32015-11-20 11:30:44 -0800915 // If this is a setting that is currently restricted for this user, do not allow
916 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800917 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100918 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800919 return false;
920 }
921
922 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700923 synchronized (mLock) {
924 switch (operation) {
925 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800926 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
927 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
928 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700929 }
Svetoslav683914b2015-01-15 14:22:26 -0800930
Svetoslav7ec28e82015-05-20 17:01:10 -0700931 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700932 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
933 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700934 }
Svetoslav683914b2015-01-15 14:22:26 -0800935
Svetoslav7ec28e82015-05-20 17:01:10 -0700936 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800937 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
938 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
939 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700940 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800941
942 case MUTATION_OPERATION_RESET: {
943 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
944 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
945 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800946 }
947 }
948
949 return false;
950 }
951
Svetoslav7ec28e82015-05-20 17:01:10 -0700952 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800953 if (DEBUG) {
954 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
955 }
956
957 // Resolve the userId on whose behalf the call is made.
958 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
959
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 synchronized (mLock) {
961 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700962 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800963
Svetoslav7ec28e82015-05-20 17:01:10 -0700964 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800965
Svetoslav7ec28e82015-05-20 17:01:10 -0700966 String[] normalizedProjection = normalizeProjection(projection);
967 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800968
Svetoslav7ec28e82015-05-20 17:01:10 -0700969 for (int i = 0; i < nameCount; i++) {
970 String name = names.get(i);
971 // Determine the owning user as some profile settings are cloned from the parent.
972 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
973 name);
Svetoslav683914b2015-01-15 14:22:26 -0800974
Svetoslav7ec28e82015-05-20 17:01:10 -0700975 // Special case for location (sigh).
976 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700977 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700978 }
Svetoslav683914b2015-01-15 14:22:26 -0800979
Mark Rathjen7599f132017-01-23 14:15:54 -0800980 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +0000981 // SETTINGS_FILE_SSAID, unless accessed by a system process.
982 final Setting setting;
983 if (isNewSsaidSetting(name)) {
984 setting = getSsaidSettingLocked(owningUserId);
985 } else {
986 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
987 name);
988 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800990 }
991
Svetoslav7ec28e82015-05-20 17:01:10 -0700992 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800993 }
Svetoslav683914b2015-01-15 14:22:26 -0800994 }
995
Svetoslav7ec28e82015-05-20 17:01:10 -0700996 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800997 if (DEBUG) {
998 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
999 }
1000
1001 // Resolve the userId on whose behalf the call is made.
1002 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1003
1004 // Determine the owning user as some profile settings are cloned from the parent.
1005 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1006
1007 // Special case for location (sigh).
1008 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001009 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1010 owningUserId);
1011 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001012 }
1013
1014 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001015 synchronized (mLock) {
Mark Rathjen7599f132017-01-23 14:15:54 -08001016 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001017 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1018 if (isNewSsaidSetting(name)) {
1019 return getSsaidSettingLocked(owningUserId);
1020 }
1021
Svet Ganov53a441c2016-04-19 19:38:00 -07001022 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001023 owningUserId, name);
1024 }
Svetoslav683914b2015-01-15 14:22:26 -08001025 }
1026
Mark Rathjend891f012017-01-19 04:10:37 +00001027 private boolean isNewSsaidSetting(String name) {
1028 return Settings.Secure.ANDROID_ID.equals(name)
1029 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1030 }
1031
1032 private Setting getSsaidSettingLocked(int owningUserId) {
1033 // Get uid of caller (key) used to store ssaid value
1034 String name = Integer.toString(
1035 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1036
1037 if (DEBUG) {
1038 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1039 }
1040
1041 // Retrieve the ssaid from the table if present.
1042 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1043 name);
1044
1045 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001046 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001047 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1048 }
1049
1050 return ssaid;
1051 }
1052
Svetoslav Ganove080da92016-12-21 17:10:35 -08001053 private boolean insertSecureSetting(String name, String value, String tag,
1054 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001055 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001056 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001057 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1058 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001059 }
1060
Svetoslav Ganove080da92016-12-21 17:10:35 -08001061 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1062 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001063 }
1064
Svet Ganov53a441c2016-04-19 19:38:00 -07001065 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001066 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001067 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1068 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001069 }
1070
Svetoslav Ganove080da92016-12-21 17:10:35 -08001071 return mutateSecureSetting(name, null, null, false, requestingUserId,
1072 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001073 }
1074
Svetoslav Ganove080da92016-12-21 17:10:35 -08001075 private boolean updateSecureSetting(String name, String value, String tag,
1076 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001077 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001078 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001079 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1080 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001081 }
1082
Svetoslav Ganove080da92016-12-21 17:10:35 -08001083 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1084 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001085 }
1086
Svetoslav Ganove080da92016-12-21 17:10:35 -08001087 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1088 if (DEBUG) {
1089 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1090 + mode + ", " + tag + ")");
1091 }
1092
1093 mutateSecureSetting(null, null, tag, false, requestingUserId,
1094 MUTATION_OPERATION_RESET, false, mode);
1095 }
1096
1097 private boolean mutateSecureSetting(String name, String value, String tag,
1098 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1099 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001100 // Make sure the caller can change the settings.
1101 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1102
Svetoslav683914b2015-01-15 14:22:26 -08001103 // Resolve the userId on whose behalf the call is made.
1104 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1105
Makoto Onuki28da2e32015-11-20 11:30:44 -08001106 // If this is a setting that is currently restricted for this user, do not allow
1107 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001108 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001109 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001110 return false;
1111 }
1112
1113 // Determine the owning user as some profile settings are cloned from the parent.
1114 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1115
1116 // Only the owning user can change the setting.
1117 if (owningUserId != callingUserId) {
1118 return false;
1119 }
1120
1121 // Special cases for location providers (sigh).
1122 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001123 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1124 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001125 }
1126
1127 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001128 synchronized (mLock) {
1129 switch (operation) {
1130 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001131 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001132 owningUserId, name, value, tag, makeDefault,
1133 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001134 }
Svetoslav683914b2015-01-15 14:22:26 -08001135
Svetoslav7ec28e82015-05-20 17:01:10 -07001136 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001137 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
1138 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001139 }
Svetoslav683914b2015-01-15 14:22:26 -08001140
Svetoslav7ec28e82015-05-20 17:01:10 -07001141 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001142 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001143 owningUserId, name, value, tag, makeDefault,
1144 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001145 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001146
1147 case MUTATION_OPERATION_RESET: {
1148 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1149 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1150 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001151 }
1152 }
1153
1154 return false;
1155 }
1156
Svetoslav7ec28e82015-05-20 17:01:10 -07001157 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001158 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001159 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001160 }
1161
1162 // Resolve the userId on whose behalf the call is made.
1163 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1164
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 synchronized (mLock) {
1166 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001167 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001168
Svetoslav7ec28e82015-05-20 17:01:10 -07001169 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001170
Svetoslav7ec28e82015-05-20 17:01:10 -07001171 String[] normalizedProjection = normalizeProjection(projection);
1172 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001173
Svetoslav7ec28e82015-05-20 17:01:10 -07001174 for (int i = 0; i < nameCount; i++) {
1175 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001176
Svetoslav7ec28e82015-05-20 17:01:10 -07001177 // Determine the owning user as some profile settings are cloned from the parent.
1178 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1179 name);
Svetoslav683914b2015-01-15 14:22:26 -08001180
Svetoslav7ec28e82015-05-20 17:01:10 -07001181 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001182 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001183 appendSettingToCursor(result, setting);
1184 }
1185
1186 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001187 }
Svetoslav683914b2015-01-15 14:22:26 -08001188 }
1189
Svetoslav7ec28e82015-05-20 17:01:10 -07001190 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001191 if (DEBUG) {
1192 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1193 }
1194
1195 // Resolve the userId on whose behalf the call is made.
1196 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1197
1198 // Determine the owning user as some profile settings are cloned from the parent.
1199 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1200
1201 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001202 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001203 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001204 }
Svetoslav683914b2015-01-15 14:22:26 -08001205 }
1206
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001208 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001209 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001210 + requestingUserId + ")");
1211 }
1212
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001214 }
1215
Svetoslav7ec28e82015-05-20 17:01:10 -07001216 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001217 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001218 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001219 }
1220
Svetoslav7ec28e82015-05-20 17:01:10 -07001221 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001222 }
1223
Svetoslav7ec28e82015-05-20 17:01:10 -07001224 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001225 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001226 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001227 + requestingUserId + ")");
1228 }
1229
Svetoslav7ec28e82015-05-20 17:01:10 -07001230 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001231 }
1232
Svetoslav7ec28e82015-05-20 17:01:10 -07001233 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001234 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001235 if (!hasWriteSecureSettingsPermission()) {
1236 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1237 // operation is allowed for the calling package through appops.
1238 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1239 Binder.getCallingUid(), getCallingPackage(), true)) {
1240 return false;
1241 }
Svetoslav683914b2015-01-15 14:22:26 -08001242 }
1243
Svetoslav683914b2015-01-15 14:22:26 -08001244 // Resolve the userId on whose behalf the call is made.
1245 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1246
Svetoslavd8d25e02015-11-20 13:09:26 -08001247 // Enforce what the calling package can mutate the system settings.
1248 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1249
Svetoslav683914b2015-01-15 14:22:26 -08001250 // Determine the owning user as some profile settings are cloned from the parent.
1251 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1252
1253 // Only the owning user id can change the setting.
1254 if (owningUserId != callingUserId) {
1255 return false;
1256 }
1257
Jeff Sharkey413573a2016-02-22 17:52:45 -07001258 // Invalidate any relevant cache files
1259 String cacheName = null;
1260 if (Settings.System.RINGTONE.equals(name)) {
1261 cacheName = Settings.System.RINGTONE_CACHE;
1262 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1263 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1264 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1265 cacheName = Settings.System.ALARM_ALERT_CACHE;
1266 }
1267 if (cacheName != null) {
1268 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001269 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001270 cacheFile.delete();
1271 }
1272
Svetoslav683914b2015-01-15 14:22:26 -08001273 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 synchronized (mLock) {
1275 switch (operation) {
1276 case MUTATION_OPERATION_INSERT: {
1277 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001278 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001279 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001280 }
1281
1282 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001283 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1284 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001285 }
1286
1287 case MUTATION_OPERATION_UPDATE: {
1288 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001289 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001290 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001291 }
Svetoslav683914b2015-01-15 14:22:26 -08001292 }
1293
Svetoslav7ec28e82015-05-20 17:01:10 -07001294 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001295 }
Svetoslav683914b2015-01-15 14:22:26 -08001296 }
1297
Billy Lau6ad2d662015-07-18 00:26:58 +01001298 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001299 // Write secure settings is a more protected permission. If caller has it we are good.
1300 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1301 == PackageManager.PERMISSION_GRANTED) {
1302 return true;
1303 }
1304
Svetoslavf41334b2015-06-23 12:06:03 -07001305 return false;
1306 }
1307
Svetoslav683914b2015-01-15 14:22:26 -08001308 private void validateSystemSettingValue(String name, String value) {
1309 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1310 if (validator != null && !validator.validate(value)) {
1311 throw new IllegalArgumentException("Invalid value: " + value
1312 + " for setting: " + name);
1313 }
1314 }
1315
1316 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1317 int owningUserId) {
1318 // Optimization - location providers are restricted only for managed profiles.
1319 if (callingUserId == owningUserId) {
1320 return false;
1321 }
1322 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1323 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1324 new UserHandle(callingUserId))) {
1325 return true;
1326 }
1327 return false;
1328 }
1329
Makoto Onuki28da2e32015-11-20 11:30:44 -08001330 /**
1331 * Checks whether changing a setting to a value is prohibited by the corresponding user
1332 * restriction.
1333 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001334 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1335 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001336 *
1337 * @return true if the change is prohibited, false if the change is allowed.
1338 */
1339 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001340 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001341 String restriction;
1342 switch (setting) {
1343 case Settings.Secure.LOCATION_MODE:
1344 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1345 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1346 // here normally, but we still protect it here from a direct provider write.
1347 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1348 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1349 break;
1350
1351 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1352 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1353 // a provider, which should be allowed even if the user restriction is set.
1354 if (value != null && value.startsWith("-")) return false;
1355 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1356 break;
1357
1358 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1359 if ("0".equals(value)) return false;
1360 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1361 break;
1362
1363 case Settings.Global.ADB_ENABLED:
1364 if ("0".equals(value)) return false;
1365 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1366 break;
1367
1368 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1369 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1370 if ("1".equals(value)) return false;
1371 restriction = UserManager.ENSURE_VERIFY_APPS;
1372 break;
1373
1374 case Settings.Global.PREFERRED_NETWORK_MODE:
1375 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1376 break;
1377
Victor Chang9c7b7062016-07-12 23:47:29 +01001378 case Settings.Secure.ALWAYS_ON_VPN_APP:
1379 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1380 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001381 final int appId = UserHandle.getAppId(callingUid);
1382 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001383 return false;
1384 }
1385 restriction = UserManager.DISALLOW_CONFIG_VPN;
1386 break;
1387
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001388 case Settings.Global.SAFE_BOOT_DISALLOWED:
1389 if ("1".equals(value)) return false;
1390 restriction = UserManager.DISALLOW_SAFE_BOOT;
1391 break;
1392
Makoto Onuki28da2e32015-11-20 11:30:44 -08001393 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001394 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001395 if ("0".equals(value)) return false;
1396 restriction = UserManager.DISALLOW_DATA_ROAMING;
1397 break;
1398 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001399 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001400 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001401
1402 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001403 }
1404
1405 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1406 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1407 }
1408
1409 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001410 final int parentId;
1411 // Resolves dependency if setting has a dependency and the calling user has a parent
1412 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1413 && (parentId = getGroupParentLocked(userId)) != userId) {
1414 // The setting has a dependency and the profile has a parent
1415 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001416 Setting settingObj = getSecureSetting(dependency, userId);
1417 if (settingObj != null && settingObj.getValue().equals("1")) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001418 return parentId;
1419 }
1420 }
Svetoslav683914b2015-01-15 14:22:26 -08001421 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1422 }
1423
1424 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1425 final int parentId = getGroupParentLocked(userId);
1426 if (parentId != userId && keys.contains(name)) {
1427 return parentId;
1428 }
1429 return userId;
1430 }
1431
Svetoslavf41334b2015-06-23 12:06:03 -07001432 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001433 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001434 // System/root/shell can mutate whatever secure settings they want.
1435 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001436 final int appId = UserHandle.getAppId(callingUid);
1437 if (appId == android.os.Process.SYSTEM_UID
1438 || appId == Process.SHELL_UID
1439 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001440 return;
1441 }
1442
1443 switch (operation) {
1444 case MUTATION_OPERATION_INSERT:
1445 // Insert updates.
1446 case MUTATION_OPERATION_UPDATE: {
1447 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1448 return;
1449 }
1450
1451 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001452 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001453
1454 // Privileged apps can do whatever they want.
1455 if ((packageInfo.applicationInfo.privateFlags
1456 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1457 return;
1458 }
1459
1460 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1461 packageInfo.applicationInfo.targetSdkVersion, name);
1462 } break;
1463
1464 case MUTATION_OPERATION_DELETE: {
1465 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1466 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1467 throw new IllegalArgumentException("You cannot delete system defined"
1468 + " secure settings.");
1469 }
1470
1471 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001472 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001473
1474 // Privileged apps can do whatever they want.
1475 if ((packageInfo.applicationInfo.privateFlags &
1476 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1477 return;
1478 }
1479
1480 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1481 packageInfo.applicationInfo.targetSdkVersion, name);
1482 } break;
1483 }
1484 }
1485
Xiaohui Chen43765b72015-08-31 10:57:33 -07001486 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001487 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001488 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1489 getCallingPackage(), 0, userId);
1490 if (packageInfo != null) {
1491 return packageInfo;
1492 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001493 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001494 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001495 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001496 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001497 }
1498
1499 private int getGroupParentLocked(int userId) {
1500 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001501 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001502 return userId;
1503 }
1504 // We are in the same process with the user manager and the returned
1505 // user info is a cached instance, so just look up instead of cache.
1506 final long identity = Binder.clearCallingIdentity();
1507 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001508 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001509 UserInfo userInfo = mUserManager.getProfileParent(userId);
1510 return (userInfo != null) ? userInfo.id : userId;
1511 } finally {
1512 Binder.restoreCallingIdentity(identity);
1513 }
1514 }
1515
Svetoslav683914b2015-01-15 14:22:26 -08001516 private void enforceWritePermission(String permission) {
1517 if (getContext().checkCallingOrSelfPermission(permission)
1518 != PackageManager.PERMISSION_GRANTED) {
1519 throw new SecurityException("Permission denial: writing to settings requires:"
1520 + permission);
1521 }
1522 }
1523
1524 /*
1525 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1526 * This setting contains a list of the currently enabled location providers.
1527 * But helper functions in android.providers.Settings can enable or disable
1528 * a single provider by using a "+" or "-" prefix before the provider name.
1529 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001530 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1531 * is set, the said method will only allow values with the "-" prefix.
1532 *
Svetoslav683914b2015-01-15 14:22:26 -08001533 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001534 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001535 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1536 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001537 if (TextUtils.isEmpty(value)) {
1538 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001539 }
1540
Svetoslav683914b2015-01-15 14:22:26 -08001541 final char prefix = value.charAt(0);
1542 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001543 if (forceNotify) {
1544 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1545 mSettingsRegistry.notifyForSettingsChange(key,
1546 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1547 }
Svetoslav683914b2015-01-15 14:22:26 -08001548 return false;
1549 }
1550
1551 // skip prefix
1552 value = value.substring(1);
1553
Svetoslav7ec28e82015-05-20 17:01:10 -07001554 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001555 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001556 if (settingValue == null) {
1557 return false;
1558 }
Svetoslav683914b2015-01-15 14:22:26 -08001559
1560 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1561
1562 int index = oldProviders.indexOf(value);
1563 int end = index + value.length();
1564
1565 // check for commas to avoid matching on partial string
1566 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1567 index = -1;
1568 }
1569
1570 // check for commas to avoid matching on partial string
1571 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1572 index = -1;
1573 }
1574
1575 String newProviders;
1576
1577 if (prefix == '+' && index < 0) {
1578 // append the provider to the list if not present
1579 if (oldProviders.length() == 0) {
1580 newProviders = value;
1581 } else {
1582 newProviders = oldProviders + ',' + value;
1583 }
1584 } else if (prefix == '-' && index >= 0) {
1585 // remove the provider from the list if present
1586 // remove leading or trailing comma
1587 if (index > 0) {
1588 index--;
1589 } else if (end < oldProviders.length()) {
1590 end++;
1591 }
1592
1593 newProviders = oldProviders.substring(0, index);
1594 if (end < oldProviders.length()) {
1595 newProviders += oldProviders.substring(end);
1596 }
1597 } else {
1598 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001599 if (forceNotify) {
1600 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1601 mSettingsRegistry.notifyForSettingsChange(key,
1602 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1603 }
Svetoslav683914b2015-01-15 14:22:26 -08001604 return false;
1605 }
1606
Svet Ganov53a441c2016-04-19 19:38:00 -07001607 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001608 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001609 tag, makeDefault, getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001610 }
1611
Svetoslav683914b2015-01-15 14:22:26 -08001612 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1613 int targetSdkVersion, String name) {
1614 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1615 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1616 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1617 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1618 + " This will soon become an error.");
1619 } else {
1620 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1621 + " This will soon become an error.");
1622 }
1623 } else {
1624 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1625 throw new IllegalArgumentException("You cannot change private secure settings.");
1626 } else {
1627 throw new IllegalArgumentException("You cannot keep your settings in"
1628 + " the secure settings.");
1629 }
1630 }
1631 }
1632
1633 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1634 if (requestingUserId == UserHandle.getCallingUserId()) {
1635 return requestingUserId;
1636 }
1637 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1638 Binder.getCallingUid(), requestingUserId, false, true,
1639 "get/set setting for user", null);
1640 }
1641
Svet Ganov53a441c2016-04-19 19:38:00 -07001642 private Bundle packageValueForCallResult(Setting setting,
1643 boolean trackingGeneration) {
1644 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001645 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001646 return NULL_SETTING_BUNDLE;
1647 }
1648 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001649 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001650 Bundle result = new Bundle();
1651 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001652 !setting.isNull() ? setting.getValue() : null);
1653 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001654 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001655 }
1656
1657 private static int getRequestingUserId(Bundle args) {
1658 final int callingUserId = UserHandle.getCallingUserId();
1659 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1660 : callingUserId;
1661 }
1662
Svet Ganov53a441c2016-04-19 19:38:00 -07001663 private boolean isTrackingGeneration(Bundle args) {
1664 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1665 }
1666
Svetoslav683914b2015-01-15 14:22:26 -08001667 private static String getSettingValue(Bundle args) {
1668 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1669 }
1670
Svetoslav Ganove080da92016-12-21 17:10:35 -08001671 private static String getSettingTag(Bundle args) {
1672 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1673 }
1674
1675 private static boolean getSettingMakeDefault(Bundle args) {
1676 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1677 }
1678
1679 private static int getResetModeEnforcingPermission(Bundle args) {
1680 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1681 switch (mode) {
1682 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1683 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1684 throw new SecurityException("Only system, shell/root on a "
1685 + "debuggable build can reset to untrusted defaults");
1686 }
1687 return mode;
1688 }
1689 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1690 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1691 throw new SecurityException("Only system, shell/root on a "
1692 + "debuggable build can reset untrusted changes");
1693 }
1694 return mode;
1695 }
1696 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1697 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1698 throw new SecurityException("Only system, shell/root on a "
1699 + "debuggable build can reset to trusted defaults");
1700 }
1701 return mode;
1702 }
1703 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1704 return mode;
1705 }
1706 }
1707 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1708 }
1709
1710 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1711 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1712 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1713 && (appId == SHELL_UID || appId == ROOT_UID));
1714 }
1715
Svetoslav683914b2015-01-15 14:22:26 -08001716 private static String getValidTableOrThrow(Uri uri) {
1717 if (uri.getPathSegments().size() > 0) {
1718 String table = uri.getPathSegments().get(0);
1719 if (DatabaseHelper.isValidTable(table)) {
1720 return table;
1721 }
1722 throw new IllegalArgumentException("Bad root path: " + table);
1723 }
1724 throw new IllegalArgumentException("Invalid URI:" + uri);
1725 }
1726
1727 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001728 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001729 return new MatrixCursor(projection, 0);
1730 }
1731 MatrixCursor cursor = new MatrixCursor(projection, 1);
1732 appendSettingToCursor(cursor, setting);
1733 return cursor;
1734 }
1735
1736 private static String[] normalizeProjection(String[] projection) {
1737 if (projection == null) {
1738 return ALL_COLUMNS;
1739 }
1740
1741 final int columnCount = projection.length;
1742 for (int i = 0; i < columnCount; i++) {
1743 String column = projection[i];
1744 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1745 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001746 }
1747 }
1748
Svetoslav683914b2015-01-15 14:22:26 -08001749 return projection;
1750 }
1751
1752 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001753 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001754 return;
1755 }
Svetoslav683914b2015-01-15 14:22:26 -08001756 final int columnCount = cursor.getColumnCount();
1757
1758 String[] values = new String[columnCount];
1759
1760 for (int i = 0; i < columnCount; i++) {
1761 String column = cursor.getColumnName(i);
1762
1763 switch (column) {
1764 case Settings.NameValueTable._ID: {
1765 values[i] = setting.getId();
1766 } break;
1767
1768 case Settings.NameValueTable.NAME: {
1769 values[i] = setting.getName();
1770 } break;
1771
1772 case Settings.NameValueTable.VALUE: {
1773 values[i] = setting.getValue();
1774 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001775 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001776 }
1777
Svetoslav683914b2015-01-15 14:22:26 -08001778 cursor.addRow(values);
1779 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001780
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001781 private static boolean isKeyValid(String key) {
1782 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1783 }
1784
Svetoslav683914b2015-01-15 14:22:26 -08001785 private static final class Arguments {
1786 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1787 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1788
1789 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1790 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1791
1792 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1793 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1794
1795 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1796 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1797
1798 public final String table;
1799 public final String name;
1800
1801 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1802 final int segmentSize = uri.getPathSegments().size();
1803 switch (segmentSize) {
1804 case 1: {
1805 if (where != null
1806 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1807 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1808 && whereArgs.length == 1) {
1809 name = whereArgs[0];
1810 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001811 return;
Svetoslav683914b2015-01-15 14:22:26 -08001812 } else if (where != null
1813 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1814 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1815 final int startIndex = Math.max(where.indexOf("'"),
1816 where.indexOf("\"")) + 1;
1817 final int endIndex = Math.max(where.lastIndexOf("'"),
1818 where.lastIndexOf("\""));
1819 name = where.substring(startIndex, endIndex);
1820 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001821 return;
Svetoslav683914b2015-01-15 14:22:26 -08001822 } else if (supportAll && where == null && whereArgs == null) {
1823 name = null;
1824 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001825 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001826 }
Svetoslav683914b2015-01-15 14:22:26 -08001827 } break;
1828
Svetoslav28494652015-02-12 14:11:42 -08001829 case 2: {
1830 if (where == null && whereArgs == null) {
1831 name = uri.getPathSegments().get(1);
1832 table = computeTableForSetting(uri, name);
1833 return;
1834 }
1835 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001836 }
Svetoslav28494652015-02-12 14:11:42 -08001837
1838 EventLogTags.writeUnsupportedSettingsQuery(
1839 uri.toSafeString(), where, Arrays.toString(whereArgs));
1840 String message = String.format( "Supported SQL:\n"
1841 + " uri content://some_table/some_property with null where and where args\n"
1842 + " uri content://some_table with query name=? and single name as arg\n"
1843 + " uri content://some_table with query name=some_name and null args\n"
1844 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1845 Arrays.toString(whereArgs));
1846 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001847 }
1848
Svetoslav28494652015-02-12 14:11:42 -08001849 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001850 String table = getValidTableOrThrow(uri);
1851
1852 if (name != null) {
1853 if (sSystemMovedToSecureSettings.contains(name)) {
1854 table = TABLE_SECURE;
1855 }
1856
1857 if (sSystemMovedToGlobalSettings.contains(name)) {
1858 table = TABLE_GLOBAL;
1859 }
1860
1861 if (sSecureMovedToGlobalSettings.contains(name)) {
1862 table = TABLE_GLOBAL;
1863 }
1864
1865 if (sGlobalMovedToSecureSettings.contains(name)) {
1866 table = TABLE_SECURE;
1867 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001868 }
Svetoslav683914b2015-01-15 14:22:26 -08001869
1870 return table;
1871 }
1872 }
1873
1874 final class SettingsRegistry {
1875 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1876
Svetoslav683914b2015-01-15 14:22:26 -08001877 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1878 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1879 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00001880 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
1881
1882 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08001883
1884 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1885
Svet Ganov53a441c2016-04-19 19:38:00 -07001886 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001887
Svetoslav7e0683b2015-08-03 16:02:52 -07001888 private final Handler mHandler;
1889
Svet Ganov53a441c2016-04-19 19:38:00 -07001890 private final BackupManager mBackupManager;
1891
Svetoslav683914b2015-01-15 14:22:26 -08001892 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001893 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001894 mGenerationRegistry = new GenerationRegistry(mLock);
1895 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001896 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00001897 syncSsaidTableOnStart();
1898 }
1899
1900 private void generateUserKeyLocked(int userId) {
1901 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08001902 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00001903 final SecureRandom rand = new SecureRandom();
1904 rand.nextBytes(keyBytes);
1905
1906 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08001907 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00001908
1909 // Store the key in the ssaid table.
1910 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1911 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
1912 true, SettingsState.SYSTEM_PACKAGE_NAME);
1913
1914 if (!success) {
1915 throw new IllegalStateException("Ssaid settings not accessible");
1916 }
1917 }
1918
Mark Rathjen7599f132017-01-23 14:15:54 -08001919 private byte[] getLengthPrefix(byte[] data) {
1920 return ByteBuffer.allocate(4).putInt(data.length).array();
1921 }
1922
Mark Rathjend891f012017-01-19 04:10:37 +00001923 public Setting generateSsaidLocked(String packageName, int userId) {
1924 final PackageInfo packageInfo;
1925 try {
1926 packageInfo = mPackageManager.getPackageInfo(packageName,
1927 PackageManager.GET_SIGNATURES, userId);
1928 } catch (RemoteException e) {
1929 throw new IllegalStateException("Package info doesn't exist");
1930 }
1931
1932 // Read the user's key from the ssaid table.
1933 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08001934 if (userKeySetting == null || userKeySetting.isNull()
1935 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001936 // Lazy initialize and store the user key.
1937 generateUserKeyLocked(userId);
1938 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08001939 if (userKeySetting == null || userKeySetting.isNull()
1940 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001941 throw new IllegalStateException("User key not accessible");
1942 }
1943 }
1944 final String userKey = userKeySetting.getValue();
1945
1946 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08001947 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
1948
1949 // Validate that the key is of expected length.
1950 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
1951 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00001952 throw new IllegalStateException("User key invalid");
1953 }
1954
Mark Rathjen7599f132017-01-23 14:15:54 -08001955 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00001956 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08001957 m = Mac.getInstance("HmacSHA256");
1958 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00001959 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08001960 throw new IllegalStateException("HmacSHA256 is not available", e);
1961 } catch (InvalidKeyException e) {
1962 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00001963 }
Mark Rathjen7599f132017-01-23 14:15:54 -08001964
1965 // Mac the package name and each of the signatures.
1966 byte[] packageNameBytes = packageInfo.packageName.getBytes(StandardCharsets.UTF_8);
1967 m.update(getLengthPrefix(packageNameBytes), 0, 4);
1968 m.update(packageNameBytes);
1969 for (int i = 0; i < packageInfo.signatures.length; i++) {
1970 byte[] sig = packageInfo.signatures[i].toByteArray();
1971 m.update(getLengthPrefix(sig), 0, 4);
1972 m.update(sig);
1973 }
Mark Rathjend891f012017-01-19 04:10:37 +00001974
1975 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08001976 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
1977 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00001978
1979 // Save the ssaid in the ssaid table.
1980 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
1981 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1982 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
1983 packageName);
1984
1985 if (!success) {
1986 throw new IllegalStateException("Ssaid settings not accessible");
1987 }
1988
1989 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
1990 }
1991
1992 public void syncSsaidTableOnStart() {
1993 synchronized (mLock) {
1994 // Verify that each user's packages and ssaid's are in sync.
1995 for (UserInfo user : mUserManager.getUsers(true)) {
1996 // Get all uids for the user's packages.
1997 final List<PackageInfo> packages;
1998 try {
1999 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2000 } catch (RemoteException e) {
2001 throw new IllegalStateException("Package manager not available");
2002 }
2003 final Set<String> appUids = new HashSet<>();
2004 for (PackageInfo info : packages) {
2005 appUids.add(Integer.toString(info.applicationInfo.uid));
2006 }
2007
2008 // Get all uids currently stored in the user's ssaid table.
2009 final Set<String> ssaidUids = new HashSet<>(
2010 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2011 ssaidUids.remove(SSAID_USER_KEY);
2012
2013 // Perform a set difference for the appUids and ssaidUids.
2014 ssaidUids.removeAll(appUids);
2015
2016 // If there are ssaidUids left over they need to be removed from the table.
2017 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2018 user.id);
2019 for (String uid : ssaidUids) {
2020 ssaidSettings.deleteSettingLocked(uid);
2021 }
2022 }
2023 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002024 }
2025
Svetoslav683914b2015-01-15 14:22:26 -08002026 public List<String> getSettingsNamesLocked(int type, int userId) {
2027 final int key = makeKey(type, userId);
2028 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002029 if (settingsState == null) {
2030 return new ArrayList<String>();
2031 }
Svetoslav683914b2015-01-15 14:22:26 -08002032 return settingsState.getSettingNamesLocked();
2033 }
2034
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002035 public SparseBooleanArray getKnownUsersLocked() {
2036 SparseBooleanArray users = new SparseBooleanArray();
2037 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2038 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2039 }
2040 return users;
2041 }
2042
Svetoslav683914b2015-01-15 14:22:26 -08002043 public SettingsState getSettingsLocked(int type, int userId) {
2044 final int key = makeKey(type, userId);
2045 return peekSettingsStateLocked(key);
2046 }
2047
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002048 public boolean ensureSettingsForUserLocked(int userId) {
2049 // First make sure this user actually exists.
2050 if (mUserManager.getUserInfo(userId) == null) {
2051 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2052 return false;
2053 }
2054
Svetoslav683914b2015-01-15 14:22:26 -08002055 // Migrate the setting for this user if needed.
2056 migrateLegacySettingsForUserIfNeededLocked(userId);
2057
2058 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002059 if (userId == UserHandle.USER_SYSTEM) {
2060 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002061 ensureSettingsStateLocked(globalKey);
2062 }
2063
2064 // Ensure secure settings loaded.
2065 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2066 ensureSettingsStateLocked(secureKey);
2067
2068 // Make sure the secure settings have an Android id set.
2069 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2070 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2071
2072 // Ensure system settings loaded.
2073 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2074 ensureSettingsStateLocked(systemKey);
2075
Mark Rathjend891f012017-01-19 04:10:37 +00002076 // Ensure secure settings loaded.
2077 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2078 ensureSettingsStateLocked(ssaidKey);
2079
Svetoslav683914b2015-01-15 14:22:26 -08002080 // Upgrade the settings to the latest version.
2081 UpgradeController upgrader = new UpgradeController(userId);
2082 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002083 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002084 }
2085
2086 private void ensureSettingsStateLocked(int key) {
2087 if (mSettingsStates.get(key) == null) {
2088 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002089 SettingsState settingsState = new SettingsState(getContext(), mLock,
2090 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002091 mSettingsStates.put(key, settingsState);
2092 }
2093 }
2094
2095 public void removeUserStateLocked(int userId, boolean permanently) {
2096 // We always keep the global settings in memory.
2097
2098 // Nuke system settings.
2099 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2100 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2101 if (systemSettingsState != null) {
2102 if (permanently) {
2103 mSettingsStates.remove(systemKey);
2104 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002105 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002106 systemSettingsState.destroyLocked(new Runnable() {
2107 @Override
2108 public void run() {
2109 mSettingsStates.remove(systemKey);
2110 }
2111 });
2112 }
2113 }
2114
2115 // Nuke secure settings.
2116 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2117 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2118 if (secureSettingsState != null) {
2119 if (permanently) {
2120 mSettingsStates.remove(secureKey);
2121 secureSettingsState.destroyLocked(null);
2122 } else {
2123 secureSettingsState.destroyLocked(new Runnable() {
2124 @Override
2125 public void run() {
2126 mSettingsStates.remove(secureKey);
2127 }
2128 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002129 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002130 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002131
Mark Rathjend891f012017-01-19 04:10:37 +00002132 // Nuke ssaid settings.
2133 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2134 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2135 if (ssaidSettingsState != null) {
2136 if (permanently) {
2137 mSettingsStates.remove(ssaidKey);
2138 ssaidSettingsState.destroyLocked(null);
2139 } else {
2140 ssaidSettingsState.destroyLocked(new Runnable() {
2141 @Override
2142 public void run() {
2143 mSettingsStates.remove(ssaidKey);
2144 }
2145 });
2146 }
2147 }
2148
Svet Ganov53a441c2016-04-19 19:38:00 -07002149 // Nuke generation tracking data
2150 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002151 }
2152
Svetoslav683914b2015-01-15 14:22:26 -08002153 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002154 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002155 final int key = makeKey(type, userId);
2156
Svetoslav Ganove080da92016-12-21 17:10:35 -08002157 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002158 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002159 if (settingsState != null) {
2160 success = settingsState.insertSettingLocked(name, value,
2161 tag, makeDefault, packageName);
2162 }
Svetoslav683914b2015-01-15 14:22:26 -08002163
Svet Ganov53a441c2016-04-19 19:38:00 -07002164 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002165 notifyForSettingsChange(key, name);
2166 }
2167 return success;
2168 }
2169
Svet Ganov53a441c2016-04-19 19:38:00 -07002170 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002171 final int key = makeKey(type, userId);
2172
Svetoslav Ganove080da92016-12-21 17:10:35 -08002173 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002174 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002175 if (settingsState != null) {
2176 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002177 }
Svetoslav683914b2015-01-15 14:22:26 -08002178
Svet Ganov53a441c2016-04-19 19:38:00 -07002179 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002180 notifyForSettingsChange(key, name);
2181 }
2182 return success;
2183 }
2184
2185 public Setting getSettingLocked(int type, int userId, String name) {
2186 final int key = makeKey(type, userId);
2187
2188 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002189 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002190 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002191 }
Mark Rathjend891f012017-01-19 04:10:37 +00002192
2193 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002194 return settingsState.getSettingLocked(name);
2195 }
2196
2197 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002198 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002199 final int key = makeKey(type, userId);
2200
Svetoslav Ganove080da92016-12-21 17:10:35 -08002201 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002202 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002203 if (settingsState != null) {
2204 success = settingsState.updateSettingLocked(name, value, tag,
2205 makeDefault, packageName);
2206 }
Svetoslav683914b2015-01-15 14:22:26 -08002207
Svet Ganov53a441c2016-04-19 19:38:00 -07002208 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002209 notifyForSettingsChange(key, name);
2210 }
2211
2212 return success;
2213 }
2214
Svetoslav Ganove080da92016-12-21 17:10:35 -08002215 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2216 String tag) {
2217 final int key = makeKey(type, userId);
2218 SettingsState settingsState = peekSettingsStateLocked(key);
2219 if (settingsState == null) {
2220 return;
2221 }
2222
2223 switch (mode) {
2224 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2225 for (String name : settingsState.getSettingNamesLocked()) {
2226 Setting setting = settingsState.getSettingLocked(name);
2227 if (packageName.equals(setting.getPackageName())) {
2228 if (tag != null && !tag.equals(setting.getTag())) {
2229 continue;
2230 }
2231 if (settingsState.resetSettingLocked(name, packageName)) {
2232 notifyForSettingsChange(key, name);
2233 }
2234 }
2235 }
2236 } break;
2237
2238 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2239 for (String name : settingsState.getSettingNamesLocked()) {
2240 Setting setting = settingsState.getSettingLocked(name);
2241 if (!SettingsState.isSystemPackage(getContext(),
2242 setting.getPackageName())) {
2243 if (settingsState.resetSettingLocked(name, packageName)) {
2244 notifyForSettingsChange(key, name);
2245 }
2246 }
2247 }
2248 } break;
2249
2250 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2251 for (String name : settingsState.getSettingNamesLocked()) {
2252 Setting setting = settingsState.getSettingLocked(name);
2253 if (!SettingsState.isSystemPackage(getContext(),
2254 setting.getPackageName())) {
2255 if (setting.isDefaultSystemSet()) {
2256 if (settingsState.resetSettingLocked(name, packageName)) {
2257 notifyForSettingsChange(key, name);
2258 }
2259 } else if (settingsState.deleteSettingLocked(name)) {
2260 notifyForSettingsChange(key, name);
2261 }
2262 }
2263 }
2264 } break;
2265
2266 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2267 for (String name : settingsState.getSettingNamesLocked()) {
2268 Setting setting = settingsState.getSettingLocked(name);
2269 if (setting.isDefaultSystemSet()) {
2270 if (settingsState.resetSettingLocked(name, packageName)) {
2271 notifyForSettingsChange(key, name);
2272 }
2273 } else if (settingsState.deleteSettingLocked(name)) {
2274 notifyForSettingsChange(key, name);
2275 }
2276 }
2277 } break;
2278 }
2279 }
2280
Svetoslav683914b2015-01-15 14:22:26 -08002281 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002282 // Global and secure settings are signature protected. Apps signed
2283 // by the platform certificate are generally not uninstalled and
2284 // the main exception is tests. We trust components signed
2285 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002286
2287 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2288 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002289 if (systemSettings != null) {
2290 systemSettings.onPackageRemovedLocked(packageName);
2291 }
Svetoslav683914b2015-01-15 14:22:26 -08002292 }
2293
Mark Rathjend891f012017-01-19 04:10:37 +00002294 public void onUidRemovedLocked(int uid) {
2295 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2296 UserHandle.getUserId(uid));
2297 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2298 }
2299
Svetoslav683914b2015-01-15 14:22:26 -08002300 private SettingsState peekSettingsStateLocked(int key) {
2301 SettingsState settingsState = mSettingsStates.get(key);
2302 if (settingsState != null) {
2303 return settingsState;
2304 }
2305
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002306 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2307 return null;
2308 }
Svetoslav683914b2015-01-15 14:22:26 -08002309 return mSettingsStates.get(key);
2310 }
2311
2312 private void migrateAllLegacySettingsIfNeeded() {
2313 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002314 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002315 File globalFile = getSettingsFile(key);
2316 if (globalFile.exists()) {
2317 return;
2318 }
2319
2320 final long identity = Binder.clearCallingIdentity();
2321 try {
2322 List<UserInfo> users = mUserManager.getUsers(true);
2323
2324 final int userCount = users.size();
2325 for (int i = 0; i < userCount; i++) {
2326 final int userId = users.get(i).id;
2327
2328 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2329 SQLiteDatabase database = dbHelper.getWritableDatabase();
2330 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2331
2332 // Upgrade to the latest version.
2333 UpgradeController upgrader = new UpgradeController(userId);
2334 upgrader.upgradeIfNeededLocked();
2335
2336 // Drop from memory if not a running user.
2337 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2338 removeUserStateLocked(userId, false);
2339 }
2340 }
2341 } finally {
2342 Binder.restoreCallingIdentity(identity);
2343 }
2344 }
2345 }
2346
2347 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2348 // Every user has secure settings and if no file we need to migrate.
2349 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2350 File secureFile = getSettingsFile(secureKey);
2351 if (secureFile.exists()) {
2352 return;
2353 }
2354
2355 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2356 SQLiteDatabase database = dbHelper.getWritableDatabase();
2357
2358 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2359 }
2360
2361 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2362 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002363 // Move over the system settings.
2364 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2365 ensureSettingsStateLocked(systemKey);
2366 SettingsState systemSettings = mSettingsStates.get(systemKey);
2367 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2368 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002369
2370 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002371 // Do this after System settings, since this is the first thing we check when deciding
2372 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002373 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2374 ensureSettingsStateLocked(secureKey);
2375 SettingsState secureSettings = mSettingsStates.get(secureKey);
2376 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2377 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2378 secureSettings.persistSyncLocked();
2379
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002380 // Move over the global settings if owner.
2381 // Do this last, since this is the first thing we check when deciding
2382 // to skip over migration from db to xml for owner user.
2383 if (userId == UserHandle.USER_SYSTEM) {
2384 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2385 ensureSettingsStateLocked(globalKey);
2386 SettingsState globalSettings = mSettingsStates.get(globalKey);
2387 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2388 globalSettings.persistSyncLocked();
2389 }
Svetoslav683914b2015-01-15 14:22:26 -08002390
2391 // Drop the database as now all is moved and persisted.
2392 if (DROP_DATABASE_ON_MIGRATION) {
2393 dbHelper.dropDatabase();
2394 } else {
2395 dbHelper.backupDatabase();
2396 }
2397 }
2398
2399 private void migrateLegacySettingsLocked(SettingsState settingsState,
2400 SQLiteDatabase database, String table) {
2401 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2402 queryBuilder.setTables(table);
2403
2404 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2405 null, null, null, null, null);
2406
2407 if (cursor == null) {
2408 return;
2409 }
2410
2411 try {
2412 if (!cursor.moveToFirst()) {
2413 return;
2414 }
2415
2416 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2417 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2418
2419 settingsState.setVersionLocked(database.getVersion());
2420
2421 while (!cursor.isAfterLast()) {
2422 String name = cursor.getString(nameColumnIdx);
2423 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002424 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002425 SettingsState.SYSTEM_PACKAGE_NAME);
2426 cursor.moveToNext();
2427 }
2428 } finally {
2429 cursor.close();
2430 }
2431 }
2432
2433 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2434 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2435
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002436 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002437 return;
2438 }
2439
2440 final int userId = getUserIdFromKey(secureSettings.mKey);
2441
2442 final UserInfo user;
2443 final long identity = Binder.clearCallingIdentity();
2444 try {
2445 user = mUserManager.getUserInfo(userId);
2446 } finally {
2447 Binder.restoreCallingIdentity(identity);
2448 }
2449 if (user == null) {
2450 // Can happen due to races when deleting users - treat as benign.
2451 return;
2452 }
2453
2454 String androidId = Long.toHexString(new SecureRandom().nextLong());
2455 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002456 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002457
2458 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2459 + "] for user " + userId);
2460
2461 // Write a drop box entry if it's a restricted profile
2462 if (user.isRestricted()) {
2463 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2464 Context.DROPBOX_SERVICE);
2465 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2466 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2467 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2468 }
2469 }
2470 }
2471
2472 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002473 final int userId = getUserIdFromKey(key);
2474 Uri uri = getNotificationUriFor(key, name);
2475
Phil Weaver83fec002016-05-11 10:55:29 -07002476 mGenerationRegistry.incrementGeneration(key);
2477
Svetoslav7e0683b2015-08-03 16:02:52 -07002478 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2479 userId, 0, uri).sendToTarget();
2480
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002481 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002482 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2483 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002484 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002485 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2486 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002487 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002488
Svet Ganov53a441c2016-04-19 19:38:00 -07002489 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002490 }
2491
Svet Ganov53a441c2016-04-19 19:38:00 -07002492 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002493 Set<String> keysCloned) {
2494 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002495 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002496 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002497 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002498 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002499 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002500 final int key = makeKey(type, profileId);
2501 mGenerationRegistry.incrementGeneration(key);
2502
2503 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002504 }
2505 }
2506 }
Svetoslav683914b2015-01-15 14:22:26 -08002507 }
2508
Svetoslav683914b2015-01-15 14:22:26 -08002509 private boolean isGlobalSettingsKey(int key) {
2510 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2511 }
2512
2513 private boolean isSystemSettingsKey(int key) {
2514 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2515 }
2516
2517 private boolean isSecureSettingsKey(int key) {
2518 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2519 }
2520
Mark Rathjend891f012017-01-19 04:10:37 +00002521 private boolean isSsaidSettingsKey(int key) {
2522 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2523 }
2524
Svetoslav683914b2015-01-15 14:22:26 -08002525 private File getSettingsFile(int key) {
2526 if (isGlobalSettingsKey(key)) {
2527 final int userId = getUserIdFromKey(key);
2528 return new File(Environment.getUserSystemDirectory(userId),
2529 SETTINGS_FILE_GLOBAL);
2530 } else if (isSystemSettingsKey(key)) {
2531 final int userId = getUserIdFromKey(key);
2532 return new File(Environment.getUserSystemDirectory(userId),
2533 SETTINGS_FILE_SYSTEM);
2534 } else if (isSecureSettingsKey(key)) {
2535 final int userId = getUserIdFromKey(key);
2536 return new File(Environment.getUserSystemDirectory(userId),
2537 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002538 } else if (isSsaidSettingsKey(key)) {
2539 final int userId = getUserIdFromKey(key);
2540 return new File(Environment.getUserSystemDirectory(userId),
2541 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002542 } else {
2543 throw new IllegalArgumentException("Invalid settings key:" + key);
2544 }
2545 }
2546
2547 private Uri getNotificationUriFor(int key, String name) {
2548 if (isGlobalSettingsKey(key)) {
2549 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2550 : Settings.Global.CONTENT_URI;
2551 } else if (isSecureSettingsKey(key)) {
2552 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2553 : Settings.Secure.CONTENT_URI;
2554 } else if (isSystemSettingsKey(key)) {
2555 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2556 : Settings.System.CONTENT_URI;
2557 } else {
2558 throw new IllegalArgumentException("Invalid settings key:" + key);
2559 }
2560 }
2561
2562 private int getMaxBytesPerPackageForType(int type) {
2563 switch (type) {
2564 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002565 case SETTINGS_TYPE_SECURE:
2566 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002567 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2568 }
2569
2570 default: {
2571 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2572 }
2573 }
2574 }
2575
Svetoslav7e0683b2015-08-03 16:02:52 -07002576 private final class MyHandler extends Handler {
2577 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2578 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2579
2580 public MyHandler(Looper looper) {
2581 super(looper);
2582 }
2583
2584 @Override
2585 public void handleMessage(Message msg) {
2586 switch (msg.what) {
2587 case MSG_NOTIFY_URI_CHANGED: {
2588 final int userId = msg.arg1;
2589 Uri uri = (Uri) msg.obj;
2590 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2591 if (DEBUG) {
2592 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2593 }
2594 } break;
2595
2596 case MSG_NOTIFY_DATA_CHANGED: {
2597 mBackupManager.dataChanged();
2598 } break;
2599 }
2600 }
2601 }
2602
Svetoslav683914b2015-01-15 14:22:26 -08002603 private final class UpgradeController {
Mark Rathjend891f012017-01-19 04:10:37 +00002604 private static final int SETTINGS_VERSION = 137;
Svetoslav683914b2015-01-15 14:22:26 -08002605
2606 private final int mUserId;
2607
2608 public UpgradeController(int userId) {
2609 mUserId = userId;
2610 }
2611
2612 public void upgradeIfNeededLocked() {
2613 // The version of all settings for a user is the same (all users have secure).
2614 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002615 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002616
2617 // Try an update from the current state.
2618 final int oldVersion = secureSettings.getVersionLocked();
2619 final int newVersion = SETTINGS_VERSION;
2620
Svet Ganovc9755bc2015-03-28 13:21:22 -07002621 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002622 if (oldVersion == newVersion) {
2623 return;
2624 }
2625
2626 // Try to upgrade.
2627 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2628
2629 // If upgrade failed start from scratch and upgrade.
2630 if (curVersion != newVersion) {
2631 // Drop state we have for this user.
2632 removeUserStateLocked(mUserId, true);
2633
2634 // Recreate the database.
2635 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2636 SQLiteDatabase database = dbHelper.getWritableDatabase();
2637 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2638
2639 // Migrate the settings for this user.
2640 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2641
2642 // Now upgrade should work fine.
2643 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002644
2645 // Make a note what happened, so we don't wonder why data was lost
2646 String reason = "Settings rebuilt! Current version: "
2647 + curVersion + " while expected: " + newVersion;
2648 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002649 Settings.Global.DATABASE_DOWNGRADE_REASON,
2650 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002651 }
2652
2653 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002654 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002655 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002656 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002657 globalSettings.setVersionLocked(newVersion);
2658 }
2659
2660 // Set the secure settings version.
2661 secureSettings.setVersionLocked(newVersion);
2662
2663 // Set the system settings version.
2664 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002665 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002666 systemSettings.setVersionLocked(newVersion);
2667 }
2668
2669 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002670 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002671 }
2672
2673 private SettingsState getSecureSettingsLocked(int userId) {
2674 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2675 }
2676
Mark Rathjend891f012017-01-19 04:10:37 +00002677 private SettingsState getSsaidSettingsLocked(int userId) {
2678 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2679 }
2680
Svetoslav683914b2015-01-15 14:22:26 -08002681 private SettingsState getSystemSettingsLocked(int userId) {
2682 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2683 }
2684
Jeff Brown503cffc2015-03-26 18:08:51 -07002685 /**
2686 * You must perform all necessary mutations to bring the settings
2687 * for this user from the old to the new version. When you add a new
2688 * upgrade step you *must* update SETTINGS_VERSION.
2689 *
2690 * This is an example of moving a setting from secure to global.
2691 *
2692 * // v119: Example settings changes.
2693 * if (currentVersion == 118) {
2694 * if (userId == UserHandle.USER_OWNER) {
2695 * // Remove from the secure settings.
2696 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2697 * String name = "example_setting_to_move";
2698 * String value = secureSettings.getSetting(name);
2699 * secureSettings.deleteSetting(name);
2700 *
2701 * // Add to the global settings.
2702 * SettingsState globalSettings = getGlobalSettingsLocked();
2703 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2704 * }
2705 *
2706 * // Update the current version.
2707 * currentVersion = 119;
2708 * }
2709 */
Svetoslav683914b2015-01-15 14:22:26 -08002710 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2711 if (DEBUG) {
2712 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2713 + oldVersion + " to version: " + newVersion);
2714 }
2715
Jeff Brown503cffc2015-03-26 18:08:51 -07002716 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002717
John Spurlocke11ae112015-05-11 16:09:03 -04002718 // v119: Reset zen + ringer mode.
2719 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002720 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002721 final SettingsState globalSettings = getGlobalSettingsLocked();
2722 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002723 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2724 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002725 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002726 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2727 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002728 }
2729 currentVersion = 119;
2730 }
2731
Jason Monk27bbb2d2015-03-31 16:46:39 -04002732 // v120: Add double tap to wake setting.
2733 if (currentVersion == 119) {
2734 SettingsState secureSettings = getSecureSettingsLocked(userId);
2735 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2736 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002737 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002738 SettingsState.SYSTEM_PACKAGE_NAME);
2739
2740 currentVersion = 120;
2741 }
2742
Svetoslav7e0683b2015-08-03 16:02:52 -07002743 if (currentVersion == 120) {
2744 // Before 121, we used a different string encoding logic. We just bump the
2745 // version here; SettingsState knows how to handle pre-version 120 files.
2746 currentVersion = 121;
2747 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002748
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002749 if (currentVersion == 121) {
2750 // Version 122: allow OEMs to set a default payment component in resources.
2751 // Note that we only write the default if no default has been set;
2752 // if there is, we just leave the default at whatever it currently is.
2753 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2754 String defaultComponent = (getContext().getResources().getString(
2755 R.string.def_nfc_payment_component));
2756 Setting currentSetting = secureSettings.getSettingLocked(
2757 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2758 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002759 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002760 secureSettings.insertSettingLocked(
2761 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002762 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002763 }
2764 currentVersion = 122;
2765 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002766
2767 if (currentVersion == 122) {
2768 // Version 123: Adding a default value for the ability to add a user from
2769 // the lock screen.
2770 if (userId == UserHandle.USER_SYSTEM) {
2771 final SettingsState globalSettings = getGlobalSettingsLocked();
2772 Setting currentSetting = globalSettings.getSettingLocked(
2773 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002774 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002775 globalSettings.insertSettingLocked(
2776 Settings.Global.ADD_USERS_WHEN_LOCKED,
2777 getContext().getResources().getBoolean(
2778 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002779 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002780 }
2781 }
2782 currentVersion = 123;
2783 }
Bryce Leebd179282015-12-17 19:01:37 -08002784
2785 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002786 final SettingsState globalSettings = getGlobalSettingsLocked();
2787 String defaultDisabledProfiles = (getContext().getResources().getString(
2788 R.string.def_bluetooth_disabled_profiles));
2789 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002790 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002791 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002792 }
2793
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002794 if (currentVersion == 124) {
2795 // Version 124: allow OEMs to set a default value for whether IME should be
2796 // shown when a physical keyboard is connected.
2797 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2798 Setting currentSetting = secureSettings.getSettingLocked(
2799 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002800 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002801 secureSettings.insertSettingLocked(
2802 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2803 getContext().getResources().getBoolean(
2804 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002805 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002806 }
2807 currentVersion = 125;
2808 }
2809
Ruben Brunk98576cf2016-03-07 18:54:28 -08002810 if (currentVersion == 125) {
2811 // Version 125: Allow OEMs to set the default VR service.
2812 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2813
2814 Setting currentSetting = secureSettings.getSettingLocked(
2815 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002816 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002817 ArraySet<ComponentName> l =
2818 SystemConfig.getInstance().getDefaultVrComponents();
2819
2820 if (l != null && !l.isEmpty()) {
2821 StringBuilder b = new StringBuilder();
2822 boolean start = true;
2823 for (ComponentName c : l) {
2824 if (!start) {
2825 b.append(':');
2826 }
2827 b.append(c.flattenToString());
2828 start = false;
2829 }
2830 secureSettings.insertSettingLocked(
2831 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002832 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002833 }
2834
2835 }
2836 currentVersion = 126;
2837 }
2838
Daniel U02ba6122016-04-01 18:41:42 +01002839 if (currentVersion == 126) {
2840 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2841 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2842 if (mUserManager.isManagedProfile(userId)) {
2843 final SettingsState systemSecureSettings =
2844 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2845
2846 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2847 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002848 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002849 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2850 secureSettings.insertSettingLocked(
2851 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002852 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002853 SettingsState.SYSTEM_PACKAGE_NAME);
2854 }
2855
2856 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2857 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002858 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002859 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2860 secureSettings.insertSettingLocked(
2861 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002862 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002863 SettingsState.SYSTEM_PACKAGE_NAME);
2864 }
2865 }
2866 currentVersion = 127;
2867 }
2868
Steven Ngdc20ba62016-04-26 18:19:04 +01002869 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002870 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002871 currentVersion = 128;
2872 }
2873
Julia Reynolds1f721e12016-07-11 08:50:58 -04002874 if (currentVersion == 128) {
2875 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2876 // the new apps are appended to the list of already approved apps.
2877 final SettingsState systemSecureSettings =
2878 getSecureSettingsLocked(userId);
2879
2880 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2881 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2882 String defaultPolicyAccess = getContext().getResources().getString(
2883 com.android.internal.R.string.config_defaultDndAccessPackages);
2884 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2885 if (policyAccess.isNull()) {
2886 systemSecureSettings.insertSettingLocked(
2887 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002888 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002889 SettingsState.SYSTEM_PACKAGE_NAME);
2890 } else {
2891 StringBuilder currentSetting =
2892 new StringBuilder(policyAccess.getValue());
2893 currentSetting.append(":");
2894 currentSetting.append(defaultPolicyAccess);
2895 systemSecureSettings.updateSettingLocked(
2896 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002897 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002898 SettingsState.SYSTEM_PACKAGE_NAME);
2899 }
2900 }
2901
2902 currentVersion = 129;
2903 }
2904
Dan Sandler71f85e92016-07-20 13:46:05 -04002905 if (currentVersion == 129) {
2906 // default longpress timeout changed from 500 to 400. If unchanged from the old
2907 // default, update to the new default.
2908 final SettingsState systemSecureSettings =
2909 getSecureSettingsLocked(userId);
2910 final String oldValue = systemSecureSettings.getSettingLocked(
2911 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2912 if (TextUtils.equals("500", oldValue)) {
2913 systemSecureSettings.insertSettingLocked(
2914 Settings.Secure.LONG_PRESS_TIMEOUT,
2915 String.valueOf(getContext().getResources().getInteger(
2916 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002917 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04002918 }
2919 currentVersion = 130;
2920 }
2921
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002922 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07002923 // Split Ambient settings
2924 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2925 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
2926 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
2927
2928 if (dozeExplicitlyDisabled) {
2929 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002930 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002931 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002932 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002933 }
2934 currentVersion = 131;
2935 }
2936
2937 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002938 // Initialize new multi-press timeout to default value
2939 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2940 final String oldValue = systemSecureSettings.getSettingLocked(
2941 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2942 if (TextUtils.equals(null, oldValue)) {
2943 systemSecureSettings.insertSettingLocked(
2944 Settings.Secure.MULTI_PRESS_TIMEOUT,
2945 String.valueOf(getContext().getResources().getInteger(
2946 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002947 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002948 }
2949
Adrian Roos69741a22016-10-21 14:49:17 -07002950 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002951 }
2952
Adrian Roos69741a22016-10-21 14:49:17 -07002953 if (currentVersion == 132) {
2954 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01002955 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2956 String defaultSyncParentSounds = (getContext().getResources()
2957 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
2958 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002959 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
2960 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002961 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01002962 }
2963
Adrian Roos69741a22016-10-21 14:49:17 -07002964 if (currentVersion == 133) {
2965 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07002966 final SettingsState systemSettings = getSystemSettingsLocked(userId);
2967 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
2968 null) {
2969 String defaultEndButtonBehavior = Integer.toString(getContext()
2970 .getResources().getInteger(R.integer.def_end_button_behavior));
2971 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002972 defaultEndButtonBehavior, null, true,
2973 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07002974 }
Adrian Roos69741a22016-10-21 14:49:17 -07002975 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07002976 }
2977
Phil Weaver89e3ffc2016-09-19 13:51:10 -07002978 if (currentVersion == 134) {
2979 // Remove setting that specifies if magnification values should be preserved.
2980 // This setting defaulted to true and never has a UI.
2981 getSecureSettingsLocked(userId).deleteSettingLocked(
2982 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
2983 currentVersion = 135;
2984 }
2985
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002986 if (currentVersion == 135) {
2987 // Version 135: Migrating the NETWORK_SCORER_APP setting to the
2988 // NETWORK_RECOMMENDATIONS_ENABLED setting.
2989 if (userId == UserHandle.USER_SYSTEM) {
2990 final SettingsState globalSettings = getGlobalSettingsLocked();
2991 Setting currentSetting = globalSettings.getSettingLocked(
2992 Global.NETWORK_SCORER_APP);
2993 if (!currentSetting.isNull()) {
2994 // A scorer was set so enable recommendations.
2995 globalSettings.insertSettingLocked(
2996 Global.NETWORK_RECOMMENDATIONS_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002997 "1", null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002998 SettingsState.SYSTEM_PACKAGE_NAME);
2999
3000 // and clear the scorer setting since it's no longer needed.
3001 globalSettings.insertSettingLocked(
3002 Global.NETWORK_SCORER_APP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003003 null, null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003004 SettingsState.SYSTEM_PACKAGE_NAME);
3005 }
3006 }
3007 currentVersion = 136;
3008 }
3009
Mark Rathjend891f012017-01-19 04:10:37 +00003010 if (currentVersion == 136) {
3011 // Version 136: Store legacy SSAID for all apps currently installed on the
3012 // device as first step in migrating SSAID to be unique per application.
3013
3014 final boolean isUpgrade;
3015 try {
3016 isUpgrade = mPackageManager.isUpgrade();
3017 } catch (RemoteException e) {
3018 throw new IllegalStateException("Package manager not available");
3019 }
3020 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3021 // user data or first boot on a new device should use new ssaid generation.
3022 if (isUpgrade) {
3023 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003024 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3025 userId, Settings.Secure.ANDROID_ID);
3026 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3027 || legacySsaidSetting.getValue() == null) {
3028 throw new IllegalStateException("Legacy ssaid not accessible");
3029 }
3030 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003031
3032 // Fill each uid with the legacy ssaid to be backwards compatible.
3033 final List<PackageInfo> packages;
3034 try {
3035 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3036 } catch (RemoteException e) {
3037 throw new IllegalStateException("Package manager not available");
3038 }
3039
3040 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3041 for (PackageInfo info : packages) {
3042 // Check if the UID already has an entry in the table.
3043 final String uid = Integer.toString(info.applicationInfo.uid);
3044 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3045
3046 if (ssaid.isNull() || ssaid.getValue() == null) {
3047 // Android Id doesn't exist for this package so create it.
3048 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3049 info.packageName);
3050 }
3051 }
3052 }
3053
3054 currentVersion = 137;
3055 }
3056
Dan Sandler71f85e92016-07-20 13:46:05 -04003057 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003058 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003059 + newVersion + " left it at "
3060 + currentVersion + " instead; this is probably a bug", new Throwable());
3061 if (DEBUG) {
3062 throw new RuntimeException("db upgrade error");
3063 }
3064 }
3065
Jeff Brown503cffc2015-03-26 18:08:51 -07003066 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003067
Jeff Brown503cffc2015-03-26 18:08:51 -07003068 // Return the current version.
3069 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003070 }
3071 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003072 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003073}