blob: 058e38a5ede10cd3e17657a36138aefe9ef4fa5b [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;
81import java.security.MessageDigest;
82import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080083import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070084import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080085import java.util.Arrays;
Mark Rathjend891f012017-01-19 04:10:37 +000086import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080087import java.util.List;
Andre Lago3fa139c2016-08-04 13:53:44 +010088import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.util.Set;
90import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070091
Svetoslav Ganove080da92016-12-21 17:10:35 -080092import static android.os.Process.ROOT_UID;
93import static android.os.Process.SYSTEM_UID;
94import static android.os.Process.SHELL_UID;
95
Svetoslav683914b2015-01-15 14:22:26 -080096/**
97 * <p>
98 * This class is a content provider that publishes the system settings.
99 * It can be accessed via the content provider APIs or via custom call
100 * commands. The latter is a bit faster and is the preferred way to access
101 * the platform settings.
102 * </p>
103 * <p>
104 * There are three settings types, global (with signature level protection
105 * and shared across users), secure (with signature permission level
106 * protection and per user), and system (with dangerous permission level
107 * protection and per user). Global settings are stored under the device owner.
108 * Each of these settings is represented by a {@link
109 * com.android.providers.settings.SettingsState} object mapped to an integer
110 * key derived from the setting type in the most significant bits and user
111 * id in the least significant bits. Settings are synchronously loaded on
112 * instantiation of a SettingsState and asynchronously persisted on mutation.
113 * Settings are stored in the user specific system directory.
114 * </p>
115 * <p>
116 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
117 * and get a warning. Targeting higher API version prohibits this as the
118 * system settings are not a place for apps to save their state. When a package
119 * is removed the settings it added are deleted. Apps cannot delete system
120 * settings added by the platform. System settings values are validated to
121 * ensure the clients do not put bad values. Global and secure settings are
122 * changed only by trusted parties, therefore no validation is performed. Also
123 * there is a limit on the amount of app specific settings that can be added
124 * to prevent unlimited growth of the system process memory footprint.
125 * </p>
126 */
127@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700128public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700129 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700130
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700131 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800132
133 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700134
Christopher Tate06efb532012-08-24 15:29:27 -0700135 private static final String TABLE_SYSTEM = "system";
136 private static final String TABLE_SECURE = "secure";
137 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800138
139 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 private static final String TABLE_FAVORITES = "favorites";
141 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800142 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
143 private static final String TABLE_BOOKMARKS = "bookmarks";
144 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
Svetoslav683914b2015-01-15 14:22:26 -0800146 // The set of removed legacy tables.
147 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700148 static {
Svetoslav683914b2015-01-15 14:22:26 -0800149 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
150 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
151 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
152 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
153 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
154 }
Christopher Tate06efb532012-08-24 15:29:27 -0700155
Svetoslav683914b2015-01-15 14:22:26 -0800156 private static final int MUTATION_OPERATION_INSERT = 1;
157 private static final int MUTATION_OPERATION_DELETE = 2;
158 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800159 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400160
Svetoslav683914b2015-01-15 14:22:26 -0800161 private static final String[] ALL_COLUMNS = new String[] {
162 Settings.NameValueTable._ID,
163 Settings.NameValueTable.NAME,
164 Settings.NameValueTable.VALUE
165 };
166
Svet Ganov53a441c2016-04-19 19:38:00 -0700167 public static final int SETTINGS_TYPE_GLOBAL = 0;
168 public static final int SETTINGS_TYPE_SYSTEM = 1;
169 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000170 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800171
Svet Ganov53a441c2016-04-19 19:38:00 -0700172 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
173 public static final int SETTINGS_TYPE_SHIFT = 28;
174
175 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
176 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700177
Svetoslav683914b2015-01-15 14:22:26 -0800178 // Per user secure settings that moved to the for all users global settings.
179 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
180 static {
181 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700182 }
183
Svetoslav683914b2015-01-15 14:22:26 -0800184 // Per user system settings that moved to the for all users global settings.
185 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
186 static {
187 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700188 }
189
Svetoslav683914b2015-01-15 14:22:26 -0800190 // Per user system settings that moved to the per user secure settings.
191 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
192 static {
193 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700194 }
195
Svetoslav683914b2015-01-15 14:22:26 -0800196 // Per all users global settings that moved to the per user secure settings.
197 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
198 static {
199 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700200 }
201
Svetoslav683914b2015-01-15 14:22:26 -0800202 // Per user secure settings that are cloned for the managed profiles of the user.
203 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
204 static {
205 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700206 }
207
Svetoslav683914b2015-01-15 14:22:26 -0800208 // Per user system settings that are cloned for the managed profiles of the user.
209 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
210 static {
211 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400212 }
213
Andre Lago3fa139c2016-08-04 13:53:44 +0100214 // Per user system settings that are cloned from the profile's parent when a dependency
215 // in {@link Settings.Secure} is set to "1".
216 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
217 static {
218 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
219 }
220
Svetoslav683914b2015-01-15 14:22:26 -0800221 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700222
Svetoslav683914b2015-01-15 14:22:26 -0800223 @GuardedBy("mLock")
224 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700225
Svet Ganova8f90262016-05-10 08:44:48 -0700226 @GuardedBy("mLock")
227 private HandlerThread mHandlerThread;
228
Svetoslav7ec28e82015-05-20 17:01:10 -0700229 // We have to call in the user manager with no lock held,
230 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800231
Svetoslav7ec28e82015-05-20 17:01:10 -0700232 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700233 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700234
Svet Ganov53a441c2016-04-19 19:38:00 -0700235 public static int makeKey(int type, int userId) {
236 return (type << SETTINGS_TYPE_SHIFT) | userId;
237 }
238
239 public static int getTypeFromKey(int key) {
240 return key >>> SETTINGS_TYPE_SHIFT;
241 }
242
243 public static int getUserIdFromKey(int key) {
244 return key & ~SETTINGS_TYPE_MASK;
245 }
246
247 public static String settingTypeToString(int type) {
248 switch (type) {
249 case SETTINGS_TYPE_GLOBAL: {
250 return "SETTINGS_GLOBAL";
251 }
252 case SETTINGS_TYPE_SECURE: {
253 return "SETTINGS_SECURE";
254 }
255 case SETTINGS_TYPE_SYSTEM: {
256 return "SETTINGS_SYSTEM";
257 }
Mark Rathjend891f012017-01-19 04:10:37 +0000258 case SETTINGS_TYPE_SSAID: {
259 return "SETTINGS_SSAID";
260 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700261 default: {
262 return "UNKNOWN";
263 }
264 }
265 }
266
267 public static String keyToString(int key) {
268 return "Key[user=" + getUserIdFromKey(key) + ";type="
269 + settingTypeToString(getTypeFromKey(key)) + "]";
270 }
271
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700272 @Override
273 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800274 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700275 mUserManager = UserManager.get(getContext());
276 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700277 mHandlerThread = new HandlerThread(LOG_TAG,
278 Process.THREAD_PRIORITY_BACKGROUND);
279 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800280 mSettingsRegistry = new SettingsRegistry();
281 }
282 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700283 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700284 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700285 return true;
286 }
287
Svetoslav683914b2015-01-15 14:22:26 -0800288 @Override
289 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700290 final int requestingUserId = getRequestingUserId(args);
291 switch (method) {
292 case Settings.CALL_METHOD_GET_GLOBAL: {
293 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700294 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800295 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700296
297 case Settings.CALL_METHOD_GET_SECURE: {
298 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700299 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700300 }
301
302 case Settings.CALL_METHOD_GET_SYSTEM: {
303 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700305 }
306
307 case Settings.CALL_METHOD_PUT_GLOBAL: {
308 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800309 String tag = getSettingTag(args);
310 final boolean makeDefault = getSettingMakeDefault(args);
311 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700312 break;
313 }
314
315 case Settings.CALL_METHOD_PUT_SECURE: {
316 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800317 String tag = getSettingTag(args);
318 final boolean makeDefault = getSettingMakeDefault(args);
319 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700320 break;
321 }
322
323 case Settings.CALL_METHOD_PUT_SYSTEM: {
324 String value = getSettingValue(args);
325 insertSystemSetting(name, value, requestingUserId);
326 break;
327 }
328
Svetoslav Ganove080da92016-12-21 17:10:35 -0800329 case Settings.CALL_METHOD_RESET_GLOBAL: {
330 final int mode = getResetModeEnforcingPermission(args);
331 String tag = getSettingTag(args);
332 resetGlobalSetting(requestingUserId, mode, tag);
333 break;
334 }
335
336 case Settings.CALL_METHOD_RESET_SECURE: {
337 final int mode = getResetModeEnforcingPermission(args);
338 String tag = getSettingTag(args);
339 resetSecureSetting(requestingUserId, mode, tag);
340 break;
341 }
342
Svetoslav7ec28e82015-05-20 17:01:10 -0700343 default: {
344 Slog.w(LOG_TAG, "call() with invalid method: " + method);
345 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700346 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700347
Christopher Tate06efb532012-08-24 15:29:27 -0700348 return null;
349 }
350
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800351 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800352 public String getType(Uri uri) {
353 Arguments args = new Arguments(uri, null, null, true);
354 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700355 return "vnd.android.cursor.dir/" + args.table;
356 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700357 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700358 }
359 }
360
361 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800362 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
363 String order) {
364 if (DEBUG) {
365 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700366 }
367
Svetoslav683914b2015-01-15 14:22:26 -0800368 Arguments args = new Arguments(uri, where, whereArgs, true);
369 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700370
Svetoslav683914b2015-01-15 14:22:26 -0800371 // If a legacy table that is gone, done.
372 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
373 return new MatrixCursor(normalizedProjection, 0);
374 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700375
Svetoslav7ec28e82015-05-20 17:01:10 -0700376 switch (args.table) {
377 case TABLE_GLOBAL: {
378 if (args.name != null) {
379 Setting setting = getGlobalSetting(args.name);
380 return packageSettingForQuery(setting, normalizedProjection);
381 } else {
382 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700383 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700384 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700385
Svetoslav7ec28e82015-05-20 17:01:10 -0700386 case TABLE_SECURE: {
387 final int userId = UserHandle.getCallingUserId();
388 if (args.name != null) {
389 Setting setting = getSecureSetting(args.name, userId);
390 return packageSettingForQuery(setting, normalizedProjection);
391 } else {
392 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800393 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700394 }
Svetoslav683914b2015-01-15 14:22:26 -0800395
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 case TABLE_SYSTEM: {
397 final int userId = UserHandle.getCallingUserId();
398 if (args.name != null) {
399 Setting setting = getSystemSetting(args.name, userId);
400 return packageSettingForQuery(setting, normalizedProjection);
401 } else {
402 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800403 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700404 }
Svetoslav683914b2015-01-15 14:22:26 -0800405
Svetoslav7ec28e82015-05-20 17:01:10 -0700406 default: {
407 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700408 }
409 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700410 }
411
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700412 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800413 public Uri insert(Uri uri, ContentValues values) {
414 if (DEBUG) {
415 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700416 }
417
Svetoslav683914b2015-01-15 14:22:26 -0800418 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700419
Svetoslav683914b2015-01-15 14:22:26 -0800420 // If a legacy table that is gone, done.
421 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 return null;
423 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700424
Svetoslav683914b2015-01-15 14:22:26 -0800425 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700426 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800427 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700428 }
429
Svetoslav683914b2015-01-15 14:22:26 -0800430 String value = values.getAsString(Settings.Secure.VALUE);
431
Svetoslav7ec28e82015-05-20 17:01:10 -0700432 switch (table) {
433 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800434 if (insertGlobalSetting(name, value, null, false,
435 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700437 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700438 } break;
439
440 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800441 if (insertSecureSetting(name, value, null, false,
442 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700443 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
444 }
445 } break;
446
447 case TABLE_SYSTEM: {
448 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
449 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
450 }
451 } break;
452
453 default: {
454 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700455 }
456 }
457
Svetoslav683914b2015-01-15 14:22:26 -0800458 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700459 }
460
461 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800462 public int bulkInsert(Uri uri, ContentValues[] allValues) {
463 if (DEBUG) {
464 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700466
Svetoslav683914b2015-01-15 14:22:26 -0800467 int insertionCount = 0;
468 final int valuesCount = allValues.length;
469 for (int i = 0; i < valuesCount; i++) {
470 ContentValues values = allValues[i];
471 if (insert(uri, values) != null) {
472 insertionCount++;
473 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700474 }
Svetoslav683914b2015-01-15 14:22:26 -0800475
476 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700477 }
478
479 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800480 public int delete(Uri uri, String where, String[] whereArgs) {
481 if (DEBUG) {
482 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700484
Svetoslav683914b2015-01-15 14:22:26 -0800485 Arguments args = new Arguments(uri, where, whereArgs, false);
486
487 // If a legacy table that is gone, done.
488 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
489 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700490 }
Svetoslav683914b2015-01-15 14:22:26 -0800491
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700492 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800493 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700494 }
Svetoslav683914b2015-01-15 14:22:26 -0800495
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 switch (args.table) {
497 case TABLE_GLOBAL: {
498 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700499 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700500 }
Svetoslav683914b2015-01-15 14:22:26 -0800501
Svetoslav7ec28e82015-05-20 17:01:10 -0700502 case TABLE_SECURE: {
503 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700504 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700505 }
Svetoslav683914b2015-01-15 14:22:26 -0800506
Svetoslav7ec28e82015-05-20 17:01:10 -0700507 case TABLE_SYSTEM: {
508 final int userId = UserHandle.getCallingUserId();
509 return deleteSystemSetting(args.name, userId) ? 1 : 0;
510 }
511
512 default: {
513 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800514 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700515 }
Svetoslav683914b2015-01-15 14:22:26 -0800516 }
517
518 @Override
519 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
520 if (DEBUG) {
521 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700522 }
Svetoslav683914b2015-01-15 14:22:26 -0800523
524 Arguments args = new Arguments(uri, where, whereArgs, false);
525
526 // If a legacy table that is gone, done.
527 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
528 return 0;
529 }
530
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700531 String name = values.getAsString(Settings.Secure.NAME);
532 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800533 return 0;
534 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700535 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800536
Svetoslav7ec28e82015-05-20 17:01:10 -0700537 switch (args.table) {
538 case TABLE_GLOBAL: {
539 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800540 return updateGlobalSetting(args.name, value, null, false,
541 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700542 }
Svetoslav683914b2015-01-15 14:22:26 -0800543
Svetoslav7ec28e82015-05-20 17:01:10 -0700544 case TABLE_SECURE: {
545 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800546 return updateSecureSetting(args.name, value, null, false,
547 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700548 }
Svetoslav683914b2015-01-15 14:22:26 -0800549
Svetoslav7ec28e82015-05-20 17:01:10 -0700550 case TABLE_SYSTEM: {
551 final int userId = UserHandle.getCallingUserId();
552 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
553 }
Svetoslav683914b2015-01-15 14:22:26 -0800554
Svetoslav7ec28e82015-05-20 17:01:10 -0700555 default: {
556 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800557 }
558 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700559 }
560
561 @Override
562 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100563 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
564 if (userId != UserHandle.getCallingUserId()) {
565 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
566 "Access files from the settings of another user");
567 }
568 uri = ContentProvider.getUriWithoutUserId(uri);
569
Andre Lago3fa139c2016-08-04 13:53:44 +0100570 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700571 final String cacheName;
572 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100573 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700574 cacheName = Settings.System.RINGTONE_CACHE;
575 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100576 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700577 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
578 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100579 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700580 cacheName = Settings.System.ALARM_ALERT_CACHE;
581 } else {
582 throw new FileNotFoundException("Direct file access no longer supported; "
583 + "ringtone playback is available through android.media.Ringtone");
584 }
585
Andre Lago3fa139c2016-08-04 13:53:44 +0100586 int actualCacheOwner;
587 // Redirect cache to parent if ringtone setting is owned by profile parent
588 synchronized (mLock) {
589 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
590 cacheRingtoneSetting);
591 }
592 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700593 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
594 }
595
596 private File getRingtoneCacheDir(int userId) {
597 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
598 cacheDir.mkdir();
599 SELinux.restorecon(cacheDir);
600 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700601 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800602
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700603 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800604 synchronized (mLock) {
605 final long identity = Binder.clearCallingIdentity();
606 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700607 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800608 final int userCount = users.size();
609 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700610 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800611 }
612 } finally {
613 Binder.restoreCallingIdentity(identity);
614 }
615 }
616 }
617
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700618 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700619 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800620 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700621 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
622 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700623 if (globalSettings != null) {
624 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800625 pw.println();
626 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700627 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800628 }
629
630 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700631 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
632 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700633 if (secureSettings != null) {
634 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800635 pw.println();
636 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700637 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700638
Svetoslavb505ccc2015-02-17 12:41:04 -0800639 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700640 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
641 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700642 if (systemSettings != null) {
643 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800644 pw.println();
645 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700646 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800647 }
648
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700649 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
650 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800651
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700652 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800653
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700654 for (int i = 0; i < nameCount; i++) {
655 String name = names.get(i);
656 Setting setting = settingsState.getSettingLocked(name);
657 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
658 pw.print(" name:"); pw.print(toDumpString(name));
659 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800660 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700661 }
662 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800663 if (setting.getDefaultValue() != null) {
664 pw.print(" default:"); pw.print(setting.getDefaultValue());
665 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultSystemSet());
666 }
667 if (setting.getTag() != null) {
668 pw.print(" tag:"); pw.print(setting.getTag());
669 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800670 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700671 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800672 }
673
Svetoslav7e0683b2015-08-03 16:02:52 -0700674 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700675 if (s != null) {
676 return s;
677 }
678 return "{null}";
679 }
680
Svetoslav683914b2015-01-15 14:22:26 -0800681 private void registerBroadcastReceivers() {
682 IntentFilter userFilter = new IntentFilter();
683 userFilter.addAction(Intent.ACTION_USER_REMOVED);
684 userFilter.addAction(Intent.ACTION_USER_STOPPED);
685
686 getContext().registerReceiver(new BroadcastReceiver() {
687 @Override
688 public void onReceive(Context context, Intent intent) {
689 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700690 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800691
692 switch (intent.getAction()) {
693 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700694 synchronized (mLock) {
695 mSettingsRegistry.removeUserStateLocked(userId, true);
696 }
Svetoslav683914b2015-01-15 14:22:26 -0800697 } break;
698
699 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700700 synchronized (mLock) {
701 mSettingsRegistry.removeUserStateLocked(userId, false);
702 }
Svetoslav683914b2015-01-15 14:22:26 -0800703 } break;
704 }
705 }
706 }, userFilter);
707
708 PackageMonitor monitor = new PackageMonitor() {
709 @Override
710 public void onPackageRemoved(String packageName, int uid) {
711 synchronized (mLock) {
712 mSettingsRegistry.onPackageRemovedLocked(packageName,
713 UserHandle.getUserId(uid));
714 }
715 }
Mark Rathjend891f012017-01-19 04:10:37 +0000716
717 @Override
718 public void onUidRemoved(int uid) {
719 synchronized (mLock) {
720 mSettingsRegistry.onUidRemovedLocked(uid);
721 }
722 }
Svetoslav683914b2015-01-15 14:22:26 -0800723 };
724
725 // package changes
726 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
727 UserHandle.ALL, true);
728 }
729
Svet Ganov53a441c2016-04-19 19:38:00 -0700730 private void startWatchingUserRestrictionChanges() {
731 // TODO: The current design of settings looking different based on user restrictions
732 // should be reworked to keep them separate and system code should check the setting
733 // first followed by checking the user restriction before performing an operation.
734 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
735 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
736 Bundle prevRestrictions) -> {
737 // We are changing the settings affected by restrictions to their current
738 // value with a forced update to ensure that all cross profile dependencies
739 // are taken into account. Also make sure the settings update to.. the same
740 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800741 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
742 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700743 final long identity = Binder.clearCallingIdentity();
744 try {
745 synchronized (mLock) {
746 Setting setting = getSecureSetting(
747 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
748 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800749 setting != null ? setting.getValue() : null, null,
750 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700751 }
752 } finally {
753 Binder.restoreCallingIdentity(identity);
754 }
755 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800756 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
757 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700758 final long identity = Binder.clearCallingIdentity();
759 try {
760 synchronized (mLock) {
761 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800762 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700763 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800764 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700765 }
766 } finally {
767 Binder.restoreCallingIdentity(identity);
768 }
769 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800770 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
771 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700772 final long identity = Binder.clearCallingIdentity();
773 try {
774 synchronized (mLock) {
775 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800776 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700777 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800778 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700779 }
780 } finally {
781 Binder.restoreCallingIdentity(identity);
782 }
783 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800784 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
785 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700786 final long identity = Binder.clearCallingIdentity();
787 try {
788 synchronized (mLock) {
789 Setting enable = getGlobalSetting(
790 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800791 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700792 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800793 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700794 Setting include = getGlobalSetting(
795 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800796 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700797 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800798 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700799 }
800 } finally {
801 Binder.restoreCallingIdentity(identity);
802 }
803 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800804 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
805 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700806 final long identity = Binder.clearCallingIdentity();
807 try {
808 synchronized (mLock) {
809 Setting setting = getGlobalSetting(
810 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800811 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700812 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800813 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700814 }
815 } finally {
816 Binder.restoreCallingIdentity(identity);
817 }
818 }
819 });
820 }
821
Svetoslav7ec28e82015-05-20 17:01:10 -0700822 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800823 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700824 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800825 }
826
Svetoslav7ec28e82015-05-20 17:01:10 -0700827 synchronized (mLock) {
828 // Get the settings.
829 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700830 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800831
Svetoslav7ec28e82015-05-20 17:01:10 -0700832 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800833
Svetoslav7ec28e82015-05-20 17:01:10 -0700834 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800835
Svetoslav7ec28e82015-05-20 17:01:10 -0700836 String[] normalizedProjection = normalizeProjection(projection);
837 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800838
Svetoslav7ec28e82015-05-20 17:01:10 -0700839 // Anyone can get the global settings, so no security checks.
840 for (int i = 0; i < nameCount; i++) {
841 String name = names.get(i);
842 Setting setting = settingsState.getSettingLocked(name);
843 appendSettingToCursor(result, setting);
844 }
845
846 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800847 }
Svetoslav683914b2015-01-15 14:22:26 -0800848 }
849
Svetoslav7ec28e82015-05-20 17:01:10 -0700850 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800851 if (DEBUG) {
852 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
853 }
854
855 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700856 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700857 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700858 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800859 }
Svetoslav683914b2015-01-15 14:22:26 -0800860 }
861
Svetoslav Ganove080da92016-12-21 17:10:35 -0800862 private boolean updateGlobalSetting(String name, String value, String tag,
863 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800864 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800865 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
866 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
867 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800868 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800869 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
870 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800871 }
872
Svetoslav Ganove080da92016-12-21 17:10:35 -0800873 private boolean insertGlobalSetting(String name, String value, String tag,
874 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700875 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800876 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
877 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
878 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700879 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800880 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
881 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700882 }
883
Svet Ganov53a441c2016-04-19 19:38:00 -0700884 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800885 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800886 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
887 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800888 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800889 return mutateGlobalSetting(name, null, null, false, requestingUserId,
890 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800891 }
892
Svetoslav Ganove080da92016-12-21 17:10:35 -0800893 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
894 if (DEBUG) {
895 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
896 + mode + ", " + tag + ")");
897 }
898 mutateGlobalSetting(null, null, tag, false, requestingUserId,
899 MUTATION_OPERATION_RESET, false, mode);
900 }
901
902 private boolean mutateGlobalSetting(String name, String value, String tag,
903 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
904 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800905 // Make sure the caller can change the settings - treated as secure.
906 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
907
Svetoslav683914b2015-01-15 14:22:26 -0800908 // Resolve the userId on whose behalf the call is made.
909 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
910
Makoto Onuki28da2e32015-11-20 11:30:44 -0800911 // If this is a setting that is currently restricted for this user, do not allow
912 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800913 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100914 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800915 return false;
916 }
917
918 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700919 synchronized (mLock) {
920 switch (operation) {
921 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800922 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
923 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
924 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700925 }
Svetoslav683914b2015-01-15 14:22:26 -0800926
Svetoslav7ec28e82015-05-20 17:01:10 -0700927 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700928 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
929 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700930 }
Svetoslav683914b2015-01-15 14:22:26 -0800931
Svetoslav7ec28e82015-05-20 17:01:10 -0700932 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800933 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
934 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
935 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700936 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800937
938 case MUTATION_OPERATION_RESET: {
939 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
940 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
941 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800942 }
943 }
944
945 return false;
946 }
947
Svetoslav7ec28e82015-05-20 17:01:10 -0700948 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800949 if (DEBUG) {
950 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
951 }
952
953 // Resolve the userId on whose behalf the call is made.
954 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
955
Svetoslav7ec28e82015-05-20 17:01:10 -0700956 synchronized (mLock) {
957 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700958 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800959
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800961
Svetoslav7ec28e82015-05-20 17:01:10 -0700962 String[] normalizedProjection = normalizeProjection(projection);
963 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800964
Svetoslav7ec28e82015-05-20 17:01:10 -0700965 for (int i = 0; i < nameCount; i++) {
966 String name = names.get(i);
967 // Determine the owning user as some profile settings are cloned from the parent.
968 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
969 name);
Svetoslav683914b2015-01-15 14:22:26 -0800970
Svetoslav7ec28e82015-05-20 17:01:10 -0700971 // Special case for location (sigh).
972 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700973 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700974 }
Svetoslav683914b2015-01-15 14:22:26 -0800975
Mark Rathjend891f012017-01-19 04:10:37 +0000976 // As of Android O (API 24), the SSAID is read from an app-specific entry in table
977 // SETTINGS_FILE_SSAID, unless accessed by a system process.
978 final Setting setting;
979 if (isNewSsaidSetting(name)) {
980 setting = getSsaidSettingLocked(owningUserId);
981 } else {
982 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
983 name);
984 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800986 }
987
Svetoslav7ec28e82015-05-20 17:01:10 -0700988 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800989 }
Svetoslav683914b2015-01-15 14:22:26 -0800990 }
991
Svetoslav7ec28e82015-05-20 17:01:10 -0700992 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800993 if (DEBUG) {
994 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
995 }
996
997 // Resolve the userId on whose behalf the call is made.
998 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
999
1000 // Determine the owning user as some profile settings are cloned from the parent.
1001 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1002
1003 // Special case for location (sigh).
1004 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001005 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1006 owningUserId);
1007 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001008 }
1009
1010 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001011 synchronized (mLock) {
Mark Rathjend891f012017-01-19 04:10:37 +00001012 // As of Android O (API 24), the SSAID is read from an app-specific entry in table
1013 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1014 if (isNewSsaidSetting(name)) {
1015 return getSsaidSettingLocked(owningUserId);
1016 }
1017
Svet Ganov53a441c2016-04-19 19:38:00 -07001018 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001019 owningUserId, name);
1020 }
Svetoslav683914b2015-01-15 14:22:26 -08001021 }
1022
Mark Rathjend891f012017-01-19 04:10:37 +00001023 private boolean isNewSsaidSetting(String name) {
1024 return Settings.Secure.ANDROID_ID.equals(name)
1025 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1026 }
1027
1028 private Setting getSsaidSettingLocked(int owningUserId) {
1029 // Get uid of caller (key) used to store ssaid value
1030 String name = Integer.toString(
1031 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1032
1033 if (DEBUG) {
1034 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1035 }
1036
1037 // Retrieve the ssaid from the table if present.
1038 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1039 name);
1040
1041 // Lazy initialize ssaid if not yet present in ssaid table.
1042 if (ssaid.isNull() || ssaid.getValue() == null) {
1043 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1044 }
1045
1046 return ssaid;
1047 }
1048
Svetoslav Ganove080da92016-12-21 17:10:35 -08001049 private boolean insertSecureSetting(String name, String value, String tag,
1050 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001051 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001052 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001053 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1054 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001055 }
1056
Svetoslav Ganove080da92016-12-21 17:10:35 -08001057 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1058 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001059 }
1060
Svet Ganov53a441c2016-04-19 19:38:00 -07001061 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001062 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001063 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1064 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001065 }
1066
Svetoslav Ganove080da92016-12-21 17:10:35 -08001067 return mutateSecureSetting(name, null, null, false, requestingUserId,
1068 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001069 }
1070
Svetoslav Ganove080da92016-12-21 17:10:35 -08001071 private boolean updateSecureSetting(String name, String value, String tag,
1072 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001073 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001074 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001075 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1076 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001077 }
1078
Svetoslav Ganove080da92016-12-21 17:10:35 -08001079 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1080 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001081 }
1082
Svetoslav Ganove080da92016-12-21 17:10:35 -08001083 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1084 if (DEBUG) {
1085 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1086 + mode + ", " + tag + ")");
1087 }
1088
1089 mutateSecureSetting(null, null, tag, false, requestingUserId,
1090 MUTATION_OPERATION_RESET, false, mode);
1091 }
1092
1093 private boolean mutateSecureSetting(String name, String value, String tag,
1094 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1095 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001096 // Make sure the caller can change the settings.
1097 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1098
Svetoslav683914b2015-01-15 14:22:26 -08001099 // Resolve the userId on whose behalf the call is made.
1100 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1101
Makoto Onuki28da2e32015-11-20 11:30:44 -08001102 // If this is a setting that is currently restricted for this user, do not allow
1103 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001104 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001105 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001106 return false;
1107 }
1108
1109 // Determine the owning user as some profile settings are cloned from the parent.
1110 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1111
1112 // Only the owning user can change the setting.
1113 if (owningUserId != callingUserId) {
1114 return false;
1115 }
1116
1117 // Special cases for location providers (sigh).
1118 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001119 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1120 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001121 }
1122
1123 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001124 synchronized (mLock) {
1125 switch (operation) {
1126 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001127 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001128 owningUserId, name, value, tag, makeDefault,
1129 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001130 }
Svetoslav683914b2015-01-15 14:22:26 -08001131
Svetoslav7ec28e82015-05-20 17:01:10 -07001132 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001133 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
1134 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001135 }
Svetoslav683914b2015-01-15 14:22:26 -08001136
Svetoslav7ec28e82015-05-20 17:01:10 -07001137 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001138 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001139 owningUserId, name, value, tag, makeDefault,
1140 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001141 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001142
1143 case MUTATION_OPERATION_RESET: {
1144 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1145 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1146 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001147 }
1148 }
1149
1150 return false;
1151 }
1152
Svetoslav7ec28e82015-05-20 17:01:10 -07001153 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001154 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001155 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001156 }
1157
1158 // Resolve the userId on whose behalf the call is made.
1159 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1160
Svetoslav7ec28e82015-05-20 17:01:10 -07001161 synchronized (mLock) {
1162 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001163 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001164
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001166
Svetoslav7ec28e82015-05-20 17:01:10 -07001167 String[] normalizedProjection = normalizeProjection(projection);
1168 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001169
Svetoslav7ec28e82015-05-20 17:01:10 -07001170 for (int i = 0; i < nameCount; i++) {
1171 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001172
Svetoslav7ec28e82015-05-20 17:01:10 -07001173 // Determine the owning user as some profile settings are cloned from the parent.
1174 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1175 name);
Svetoslav683914b2015-01-15 14:22:26 -08001176
Svetoslav7ec28e82015-05-20 17:01:10 -07001177 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001178 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001179 appendSettingToCursor(result, setting);
1180 }
1181
1182 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001183 }
Svetoslav683914b2015-01-15 14:22:26 -08001184 }
1185
Svetoslav7ec28e82015-05-20 17:01:10 -07001186 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001187 if (DEBUG) {
1188 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1189 }
1190
1191 // Resolve the userId on whose behalf the call is made.
1192 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1193
1194 // Determine the owning user as some profile settings are cloned from the parent.
1195 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1196
1197 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001198 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001199 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001200 }
Svetoslav683914b2015-01-15 14:22:26 -08001201 }
1202
Svetoslav7ec28e82015-05-20 17:01:10 -07001203 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001204 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001205 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001206 + requestingUserId + ")");
1207 }
1208
Svetoslav7ec28e82015-05-20 17:01:10 -07001209 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001210 }
1211
Svetoslav7ec28e82015-05-20 17:01:10 -07001212 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001213 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001214 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001215 }
1216
Svetoslav7ec28e82015-05-20 17:01:10 -07001217 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001218 }
1219
Svetoslav7ec28e82015-05-20 17:01:10 -07001220 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001221 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001222 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001223 + requestingUserId + ")");
1224 }
1225
Svetoslav7ec28e82015-05-20 17:01:10 -07001226 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001227 }
1228
Svetoslav7ec28e82015-05-20 17:01:10 -07001229 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001230 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001231 if (!hasWriteSecureSettingsPermission()) {
1232 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1233 // operation is allowed for the calling package through appops.
1234 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1235 Binder.getCallingUid(), getCallingPackage(), true)) {
1236 return false;
1237 }
Svetoslav683914b2015-01-15 14:22:26 -08001238 }
1239
Svetoslav683914b2015-01-15 14:22:26 -08001240 // Resolve the userId on whose behalf the call is made.
1241 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1242
Svetoslavd8d25e02015-11-20 13:09:26 -08001243 // Enforce what the calling package can mutate the system settings.
1244 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1245
Svetoslav683914b2015-01-15 14:22:26 -08001246 // Determine the owning user as some profile settings are cloned from the parent.
1247 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1248
1249 // Only the owning user id can change the setting.
1250 if (owningUserId != callingUserId) {
1251 return false;
1252 }
1253
Jeff Sharkey413573a2016-02-22 17:52:45 -07001254 // Invalidate any relevant cache files
1255 String cacheName = null;
1256 if (Settings.System.RINGTONE.equals(name)) {
1257 cacheName = Settings.System.RINGTONE_CACHE;
1258 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1259 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1260 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1261 cacheName = Settings.System.ALARM_ALERT_CACHE;
1262 }
1263 if (cacheName != null) {
1264 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001265 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001266 cacheFile.delete();
1267 }
1268
Svetoslav683914b2015-01-15 14:22:26 -08001269 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001270 synchronized (mLock) {
1271 switch (operation) {
1272 case MUTATION_OPERATION_INSERT: {
1273 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001274 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001275 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001276 }
1277
1278 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001279 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1280 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001281 }
1282
1283 case MUTATION_OPERATION_UPDATE: {
1284 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001285 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001286 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001287 }
Svetoslav683914b2015-01-15 14:22:26 -08001288 }
1289
Svetoslav7ec28e82015-05-20 17:01:10 -07001290 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001291 }
Svetoslav683914b2015-01-15 14:22:26 -08001292 }
1293
Billy Lau6ad2d662015-07-18 00:26:58 +01001294 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001295 // Write secure settings is a more protected permission. If caller has it we are good.
1296 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1297 == PackageManager.PERMISSION_GRANTED) {
1298 return true;
1299 }
1300
Svetoslavf41334b2015-06-23 12:06:03 -07001301 return false;
1302 }
1303
Svetoslav683914b2015-01-15 14:22:26 -08001304 private void validateSystemSettingValue(String name, String value) {
1305 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1306 if (validator != null && !validator.validate(value)) {
1307 throw new IllegalArgumentException("Invalid value: " + value
1308 + " for setting: " + name);
1309 }
1310 }
1311
1312 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1313 int owningUserId) {
1314 // Optimization - location providers are restricted only for managed profiles.
1315 if (callingUserId == owningUserId) {
1316 return false;
1317 }
1318 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1319 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1320 new UserHandle(callingUserId))) {
1321 return true;
1322 }
1323 return false;
1324 }
1325
Makoto Onuki28da2e32015-11-20 11:30:44 -08001326 /**
1327 * Checks whether changing a setting to a value is prohibited by the corresponding user
1328 * restriction.
1329 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001330 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1331 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001332 *
1333 * @return true if the change is prohibited, false if the change is allowed.
1334 */
1335 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001336 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001337 String restriction;
1338 switch (setting) {
1339 case Settings.Secure.LOCATION_MODE:
1340 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1341 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1342 // here normally, but we still protect it here from a direct provider write.
1343 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1344 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1345 break;
1346
1347 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1348 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1349 // a provider, which should be allowed even if the user restriction is set.
1350 if (value != null && value.startsWith("-")) return false;
1351 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1352 break;
1353
1354 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1355 if ("0".equals(value)) return false;
1356 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1357 break;
1358
1359 case Settings.Global.ADB_ENABLED:
1360 if ("0".equals(value)) return false;
1361 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1362 break;
1363
1364 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1365 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1366 if ("1".equals(value)) return false;
1367 restriction = UserManager.ENSURE_VERIFY_APPS;
1368 break;
1369
1370 case Settings.Global.PREFERRED_NETWORK_MODE:
1371 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1372 break;
1373
Victor Chang9c7b7062016-07-12 23:47:29 +01001374 case Settings.Secure.ALWAYS_ON_VPN_APP:
1375 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1376 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001377 final int appId = UserHandle.getAppId(callingUid);
1378 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001379 return false;
1380 }
1381 restriction = UserManager.DISALLOW_CONFIG_VPN;
1382 break;
1383
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001384 case Settings.Global.SAFE_BOOT_DISALLOWED:
1385 if ("1".equals(value)) return false;
1386 restriction = UserManager.DISALLOW_SAFE_BOOT;
1387 break;
1388
Makoto Onuki28da2e32015-11-20 11:30:44 -08001389 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001390 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001391 if ("0".equals(value)) return false;
1392 restriction = UserManager.DISALLOW_DATA_ROAMING;
1393 break;
1394 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001395 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001396 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001397
1398 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001399 }
1400
1401 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1402 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1403 }
1404
1405 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001406 final int parentId;
1407 // Resolves dependency if setting has a dependency and the calling user has a parent
1408 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1409 && (parentId = getGroupParentLocked(userId)) != userId) {
1410 // The setting has a dependency and the profile has a parent
1411 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001412 Setting settingObj = getSecureSetting(dependency, userId);
1413 if (settingObj != null && settingObj.getValue().equals("1")) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001414 return parentId;
1415 }
1416 }
Svetoslav683914b2015-01-15 14:22:26 -08001417 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1418 }
1419
1420 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1421 final int parentId = getGroupParentLocked(userId);
1422 if (parentId != userId && keys.contains(name)) {
1423 return parentId;
1424 }
1425 return userId;
1426 }
1427
Svetoslavf41334b2015-06-23 12:06:03 -07001428 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001429 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001430 // System/root/shell can mutate whatever secure settings they want.
1431 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001432 final int appId = UserHandle.getAppId(callingUid);
1433 if (appId == android.os.Process.SYSTEM_UID
1434 || appId == Process.SHELL_UID
1435 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001436 return;
1437 }
1438
1439 switch (operation) {
1440 case MUTATION_OPERATION_INSERT:
1441 // Insert updates.
1442 case MUTATION_OPERATION_UPDATE: {
1443 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1444 return;
1445 }
1446
1447 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001448 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001449
1450 // Privileged apps can do whatever they want.
1451 if ((packageInfo.applicationInfo.privateFlags
1452 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1453 return;
1454 }
1455
1456 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1457 packageInfo.applicationInfo.targetSdkVersion, name);
1458 } break;
1459
1460 case MUTATION_OPERATION_DELETE: {
1461 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1462 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1463 throw new IllegalArgumentException("You cannot delete system defined"
1464 + " secure settings.");
1465 }
1466
1467 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001468 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001469
1470 // Privileged apps can do whatever they want.
1471 if ((packageInfo.applicationInfo.privateFlags &
1472 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1473 return;
1474 }
1475
1476 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1477 packageInfo.applicationInfo.targetSdkVersion, name);
1478 } break;
1479 }
1480 }
1481
Xiaohui Chen43765b72015-08-31 10:57:33 -07001482 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001483 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001484 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1485 getCallingPackage(), 0, userId);
1486 if (packageInfo != null) {
1487 return packageInfo;
1488 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001489 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001490 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001491 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001492 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001493 }
1494
1495 private int getGroupParentLocked(int userId) {
1496 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001497 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001498 return userId;
1499 }
1500 // We are in the same process with the user manager and the returned
1501 // user info is a cached instance, so just look up instead of cache.
1502 final long identity = Binder.clearCallingIdentity();
1503 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001504 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001505 UserInfo userInfo = mUserManager.getProfileParent(userId);
1506 return (userInfo != null) ? userInfo.id : userId;
1507 } finally {
1508 Binder.restoreCallingIdentity(identity);
1509 }
1510 }
1511
Svetoslav683914b2015-01-15 14:22:26 -08001512 private void enforceWritePermission(String permission) {
1513 if (getContext().checkCallingOrSelfPermission(permission)
1514 != PackageManager.PERMISSION_GRANTED) {
1515 throw new SecurityException("Permission denial: writing to settings requires:"
1516 + permission);
1517 }
1518 }
1519
1520 /*
1521 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1522 * This setting contains a list of the currently enabled location providers.
1523 * But helper functions in android.providers.Settings can enable or disable
1524 * a single provider by using a "+" or "-" prefix before the provider name.
1525 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001526 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1527 * is set, the said method will only allow values with the "-" prefix.
1528 *
Svetoslav683914b2015-01-15 14:22:26 -08001529 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001530 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001531 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1532 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001533 if (TextUtils.isEmpty(value)) {
1534 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001535 }
1536
Svetoslav683914b2015-01-15 14:22:26 -08001537 final char prefix = value.charAt(0);
1538 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001539 if (forceNotify) {
1540 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1541 mSettingsRegistry.notifyForSettingsChange(key,
1542 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1543 }
Svetoslav683914b2015-01-15 14:22:26 -08001544 return false;
1545 }
1546
1547 // skip prefix
1548 value = value.substring(1);
1549
Svetoslav7ec28e82015-05-20 17:01:10 -07001550 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001551 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001552 if (settingValue == null) {
1553 return false;
1554 }
Svetoslav683914b2015-01-15 14:22:26 -08001555
1556 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1557
1558 int index = oldProviders.indexOf(value);
1559 int end = index + value.length();
1560
1561 // check for commas to avoid matching on partial string
1562 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1563 index = -1;
1564 }
1565
1566 // check for commas to avoid matching on partial string
1567 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1568 index = -1;
1569 }
1570
1571 String newProviders;
1572
1573 if (prefix == '+' && index < 0) {
1574 // append the provider to the list if not present
1575 if (oldProviders.length() == 0) {
1576 newProviders = value;
1577 } else {
1578 newProviders = oldProviders + ',' + value;
1579 }
1580 } else if (prefix == '-' && index >= 0) {
1581 // remove the provider from the list if present
1582 // remove leading or trailing comma
1583 if (index > 0) {
1584 index--;
1585 } else if (end < oldProviders.length()) {
1586 end++;
1587 }
1588
1589 newProviders = oldProviders.substring(0, index);
1590 if (end < oldProviders.length()) {
1591 newProviders += oldProviders.substring(end);
1592 }
1593 } else {
1594 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001595 if (forceNotify) {
1596 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1597 mSettingsRegistry.notifyForSettingsChange(key,
1598 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1599 }
Svetoslav683914b2015-01-15 14:22:26 -08001600 return false;
1601 }
1602
Svet Ganov53a441c2016-04-19 19:38:00 -07001603 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001604 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001605 tag, makeDefault, getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001606 }
1607
Svetoslav683914b2015-01-15 14:22:26 -08001608 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1609 int targetSdkVersion, String name) {
1610 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1611 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1612 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1613 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1614 + " This will soon become an error.");
1615 } else {
1616 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1617 + " This will soon become an error.");
1618 }
1619 } else {
1620 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1621 throw new IllegalArgumentException("You cannot change private secure settings.");
1622 } else {
1623 throw new IllegalArgumentException("You cannot keep your settings in"
1624 + " the secure settings.");
1625 }
1626 }
1627 }
1628
1629 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1630 if (requestingUserId == UserHandle.getCallingUserId()) {
1631 return requestingUserId;
1632 }
1633 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1634 Binder.getCallingUid(), requestingUserId, false, true,
1635 "get/set setting for user", null);
1636 }
1637
Svet Ganov53a441c2016-04-19 19:38:00 -07001638 private Bundle packageValueForCallResult(Setting setting,
1639 boolean trackingGeneration) {
1640 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001641 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001642 return NULL_SETTING_BUNDLE;
1643 }
1644 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001645 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001646 Bundle result = new Bundle();
1647 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001648 !setting.isNull() ? setting.getValue() : null);
1649 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001650 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001651 }
1652
1653 private static int getRequestingUserId(Bundle args) {
1654 final int callingUserId = UserHandle.getCallingUserId();
1655 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1656 : callingUserId;
1657 }
1658
Svet Ganov53a441c2016-04-19 19:38:00 -07001659 private boolean isTrackingGeneration(Bundle args) {
1660 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1661 }
1662
Svetoslav683914b2015-01-15 14:22:26 -08001663 private static String getSettingValue(Bundle args) {
1664 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1665 }
1666
Svetoslav Ganove080da92016-12-21 17:10:35 -08001667 private static String getSettingTag(Bundle args) {
1668 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1669 }
1670
1671 private static boolean getSettingMakeDefault(Bundle args) {
1672 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1673 }
1674
1675 private static int getResetModeEnforcingPermission(Bundle args) {
1676 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1677 switch (mode) {
1678 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1679 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1680 throw new SecurityException("Only system, shell/root on a "
1681 + "debuggable build can reset to untrusted defaults");
1682 }
1683 return mode;
1684 }
1685 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1686 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1687 throw new SecurityException("Only system, shell/root on a "
1688 + "debuggable build can reset untrusted changes");
1689 }
1690 return mode;
1691 }
1692 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1693 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1694 throw new SecurityException("Only system, shell/root on a "
1695 + "debuggable build can reset to trusted defaults");
1696 }
1697 return mode;
1698 }
1699 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1700 return mode;
1701 }
1702 }
1703 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1704 }
1705
1706 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1707 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1708 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1709 && (appId == SHELL_UID || appId == ROOT_UID));
1710 }
1711
Svetoslav683914b2015-01-15 14:22:26 -08001712 private static String getValidTableOrThrow(Uri uri) {
1713 if (uri.getPathSegments().size() > 0) {
1714 String table = uri.getPathSegments().get(0);
1715 if (DatabaseHelper.isValidTable(table)) {
1716 return table;
1717 }
1718 throw new IllegalArgumentException("Bad root path: " + table);
1719 }
1720 throw new IllegalArgumentException("Invalid URI:" + uri);
1721 }
1722
1723 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001724 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001725 return new MatrixCursor(projection, 0);
1726 }
1727 MatrixCursor cursor = new MatrixCursor(projection, 1);
1728 appendSettingToCursor(cursor, setting);
1729 return cursor;
1730 }
1731
1732 private static String[] normalizeProjection(String[] projection) {
1733 if (projection == null) {
1734 return ALL_COLUMNS;
1735 }
1736
1737 final int columnCount = projection.length;
1738 for (int i = 0; i < columnCount; i++) {
1739 String column = projection[i];
1740 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1741 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001742 }
1743 }
1744
Svetoslav683914b2015-01-15 14:22:26 -08001745 return projection;
1746 }
1747
1748 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001749 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001750 return;
1751 }
Svetoslav683914b2015-01-15 14:22:26 -08001752 final int columnCount = cursor.getColumnCount();
1753
1754 String[] values = new String[columnCount];
1755
1756 for (int i = 0; i < columnCount; i++) {
1757 String column = cursor.getColumnName(i);
1758
1759 switch (column) {
1760 case Settings.NameValueTable._ID: {
1761 values[i] = setting.getId();
1762 } break;
1763
1764 case Settings.NameValueTable.NAME: {
1765 values[i] = setting.getName();
1766 } break;
1767
1768 case Settings.NameValueTable.VALUE: {
1769 values[i] = setting.getValue();
1770 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001771 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001772 }
1773
Svetoslav683914b2015-01-15 14:22:26 -08001774 cursor.addRow(values);
1775 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001776
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001777 private static boolean isKeyValid(String key) {
1778 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1779 }
1780
Svetoslav683914b2015-01-15 14:22:26 -08001781 private static final class Arguments {
1782 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1783 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1784
1785 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1786 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1787
1788 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1789 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1790
1791 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1792 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1793
1794 public final String table;
1795 public final String name;
1796
1797 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1798 final int segmentSize = uri.getPathSegments().size();
1799 switch (segmentSize) {
1800 case 1: {
1801 if (where != null
1802 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1803 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1804 && whereArgs.length == 1) {
1805 name = whereArgs[0];
1806 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001807 return;
Svetoslav683914b2015-01-15 14:22:26 -08001808 } else if (where != null
1809 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1810 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1811 final int startIndex = Math.max(where.indexOf("'"),
1812 where.indexOf("\"")) + 1;
1813 final int endIndex = Math.max(where.lastIndexOf("'"),
1814 where.lastIndexOf("\""));
1815 name = where.substring(startIndex, endIndex);
1816 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001817 return;
Svetoslav683914b2015-01-15 14:22:26 -08001818 } else if (supportAll && where == null && whereArgs == null) {
1819 name = null;
1820 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001821 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001822 }
Svetoslav683914b2015-01-15 14:22:26 -08001823 } break;
1824
Svetoslav28494652015-02-12 14:11:42 -08001825 case 2: {
1826 if (where == null && whereArgs == null) {
1827 name = uri.getPathSegments().get(1);
1828 table = computeTableForSetting(uri, name);
1829 return;
1830 }
1831 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001832 }
Svetoslav28494652015-02-12 14:11:42 -08001833
1834 EventLogTags.writeUnsupportedSettingsQuery(
1835 uri.toSafeString(), where, Arrays.toString(whereArgs));
1836 String message = String.format( "Supported SQL:\n"
1837 + " uri content://some_table/some_property with null where and where args\n"
1838 + " uri content://some_table with query name=? and single name as arg\n"
1839 + " uri content://some_table with query name=some_name and null args\n"
1840 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1841 Arrays.toString(whereArgs));
1842 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001843 }
1844
Svetoslav28494652015-02-12 14:11:42 -08001845 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001846 String table = getValidTableOrThrow(uri);
1847
1848 if (name != null) {
1849 if (sSystemMovedToSecureSettings.contains(name)) {
1850 table = TABLE_SECURE;
1851 }
1852
1853 if (sSystemMovedToGlobalSettings.contains(name)) {
1854 table = TABLE_GLOBAL;
1855 }
1856
1857 if (sSecureMovedToGlobalSettings.contains(name)) {
1858 table = TABLE_GLOBAL;
1859 }
1860
1861 if (sGlobalMovedToSecureSettings.contains(name)) {
1862 table = TABLE_SECURE;
1863 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001864 }
Svetoslav683914b2015-01-15 14:22:26 -08001865
1866 return table;
1867 }
1868 }
1869
1870 final class SettingsRegistry {
1871 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1872
Svetoslav683914b2015-01-15 14:22:26 -08001873 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1874 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1875 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00001876 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
1877
1878 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08001879
1880 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1881
Svet Ganov53a441c2016-04-19 19:38:00 -07001882 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001883
Svetoslav7e0683b2015-08-03 16:02:52 -07001884 private final Handler mHandler;
1885
Svet Ganov53a441c2016-04-19 19:38:00 -07001886 private final BackupManager mBackupManager;
1887
Svetoslav683914b2015-01-15 14:22:26 -08001888 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001889 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001890 mGenerationRegistry = new GenerationRegistry(mLock);
1891 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001892 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00001893 syncSsaidTableOnStart();
1894 }
1895
1896 private void generateUserKeyLocked(int userId) {
1897 // Generate a random key for each user used for creating a new ssaid.
1898 final byte[] keyBytes = new byte[16];
1899 final SecureRandom rand = new SecureRandom();
1900 rand.nextBytes(keyBytes);
1901
1902 // Convert to string for storage in settings table.
1903 final String userKey = ByteStringUtils.toString(keyBytes);
1904
1905 // Store the key in the ssaid table.
1906 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1907 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
1908 true, SettingsState.SYSTEM_PACKAGE_NAME);
1909
1910 if (!success) {
1911 throw new IllegalStateException("Ssaid settings not accessible");
1912 }
1913 }
1914
1915 public Setting generateSsaidLocked(String packageName, int userId) {
1916 final PackageInfo packageInfo;
1917 try {
1918 packageInfo = mPackageManager.getPackageInfo(packageName,
1919 PackageManager.GET_SIGNATURES, userId);
1920 } catch (RemoteException e) {
1921 throw new IllegalStateException("Package info doesn't exist");
1922 }
1923
1924 // Read the user's key from the ssaid table.
1925 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
1926 if (userKeySetting.isNull() || userKeySetting.getValue() == null) {
1927 // Lazy initialize and store the user key.
1928 generateUserKeyLocked(userId);
1929 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
1930 if (userKeySetting.isNull() || userKeySetting.getValue() == null) {
1931 throw new IllegalStateException("User key not accessible");
1932 }
1933 }
1934 final String userKey = userKeySetting.getValue();
1935
1936 // Convert the user's key back to a byte array.
1937 final byte[] keyBytes = ByteStringUtils.toByteArray(userKey);
1938 if (keyBytes == null || keyBytes.length != 16) {
1939 throw new IllegalStateException("User key invalid");
1940 }
1941
1942 final MessageDigest md;
1943 try {
1944 // Hash package name and signature.
1945 md = MessageDigest.getInstance("SHA-256");
1946 } catch (NoSuchAlgorithmException e) {
1947 throw new IllegalStateException("HmacSHA256 is not available");
1948 }
1949 md.update(keyBytes);
1950 md.update(packageInfo.packageName.getBytes(StandardCharsets.UTF_8));
1951 md.update(packageInfo.signatures[0].toByteArray());
1952
1953 // Convert result to a string for storage in settings table. Only want first 64 bits.
1954 final String ssaid = ByteStringUtils.toString(md.digest()).substring(0, 16)
1955 .toLowerCase();
1956
1957 // Save the ssaid in the ssaid table.
1958 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
1959 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1960 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
1961 packageName);
1962
1963 if (!success) {
1964 throw new IllegalStateException("Ssaid settings not accessible");
1965 }
1966
1967 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
1968 }
1969
1970 public void syncSsaidTableOnStart() {
1971 synchronized (mLock) {
1972 // Verify that each user's packages and ssaid's are in sync.
1973 for (UserInfo user : mUserManager.getUsers(true)) {
1974 // Get all uids for the user's packages.
1975 final List<PackageInfo> packages;
1976 try {
1977 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
1978 } catch (RemoteException e) {
1979 throw new IllegalStateException("Package manager not available");
1980 }
1981 final Set<String> appUids = new HashSet<>();
1982 for (PackageInfo info : packages) {
1983 appUids.add(Integer.toString(info.applicationInfo.uid));
1984 }
1985
1986 // Get all uids currently stored in the user's ssaid table.
1987 final Set<String> ssaidUids = new HashSet<>(
1988 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
1989 ssaidUids.remove(SSAID_USER_KEY);
1990
1991 // Perform a set difference for the appUids and ssaidUids.
1992 ssaidUids.removeAll(appUids);
1993
1994 // If there are ssaidUids left over they need to be removed from the table.
1995 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
1996 user.id);
1997 for (String uid : ssaidUids) {
1998 ssaidSettings.deleteSettingLocked(uid);
1999 }
2000 }
2001 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002002 }
2003
Svetoslav683914b2015-01-15 14:22:26 -08002004 public List<String> getSettingsNamesLocked(int type, int userId) {
2005 final int key = makeKey(type, userId);
2006 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002007 if (settingsState == null) {
2008 return new ArrayList<String>();
2009 }
Svetoslav683914b2015-01-15 14:22:26 -08002010 return settingsState.getSettingNamesLocked();
2011 }
2012
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002013 public SparseBooleanArray getKnownUsersLocked() {
2014 SparseBooleanArray users = new SparseBooleanArray();
2015 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2016 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2017 }
2018 return users;
2019 }
2020
Svetoslav683914b2015-01-15 14:22:26 -08002021 public SettingsState getSettingsLocked(int type, int userId) {
2022 final int key = makeKey(type, userId);
2023 return peekSettingsStateLocked(key);
2024 }
2025
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002026 public boolean ensureSettingsForUserLocked(int userId) {
2027 // First make sure this user actually exists.
2028 if (mUserManager.getUserInfo(userId) == null) {
2029 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2030 return false;
2031 }
2032
Svetoslav683914b2015-01-15 14:22:26 -08002033 // Migrate the setting for this user if needed.
2034 migrateLegacySettingsForUserIfNeededLocked(userId);
2035
2036 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002037 if (userId == UserHandle.USER_SYSTEM) {
2038 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002039 ensureSettingsStateLocked(globalKey);
2040 }
2041
2042 // Ensure secure settings loaded.
2043 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2044 ensureSettingsStateLocked(secureKey);
2045
2046 // Make sure the secure settings have an Android id set.
2047 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2048 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2049
2050 // Ensure system settings loaded.
2051 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2052 ensureSettingsStateLocked(systemKey);
2053
Mark Rathjend891f012017-01-19 04:10:37 +00002054 // Ensure secure settings loaded.
2055 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2056 ensureSettingsStateLocked(ssaidKey);
2057
Svetoslav683914b2015-01-15 14:22:26 -08002058 // Upgrade the settings to the latest version.
2059 UpgradeController upgrader = new UpgradeController(userId);
2060 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002061 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002062 }
2063
2064 private void ensureSettingsStateLocked(int key) {
2065 if (mSettingsStates.get(key) == null) {
2066 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002067 SettingsState settingsState = new SettingsState(getContext(), mLock,
2068 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002069 mSettingsStates.put(key, settingsState);
2070 }
2071 }
2072
2073 public void removeUserStateLocked(int userId, boolean permanently) {
2074 // We always keep the global settings in memory.
2075
2076 // Nuke system settings.
2077 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2078 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2079 if (systemSettingsState != null) {
2080 if (permanently) {
2081 mSettingsStates.remove(systemKey);
2082 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002083 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002084 systemSettingsState.destroyLocked(new Runnable() {
2085 @Override
2086 public void run() {
2087 mSettingsStates.remove(systemKey);
2088 }
2089 });
2090 }
2091 }
2092
2093 // Nuke secure settings.
2094 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2095 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2096 if (secureSettingsState != null) {
2097 if (permanently) {
2098 mSettingsStates.remove(secureKey);
2099 secureSettingsState.destroyLocked(null);
2100 } else {
2101 secureSettingsState.destroyLocked(new Runnable() {
2102 @Override
2103 public void run() {
2104 mSettingsStates.remove(secureKey);
2105 }
2106 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002107 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002108 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002109
Mark Rathjend891f012017-01-19 04:10:37 +00002110 // Nuke ssaid settings.
2111 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2112 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2113 if (ssaidSettingsState != null) {
2114 if (permanently) {
2115 mSettingsStates.remove(ssaidKey);
2116 ssaidSettingsState.destroyLocked(null);
2117 } else {
2118 ssaidSettingsState.destroyLocked(new Runnable() {
2119 @Override
2120 public void run() {
2121 mSettingsStates.remove(ssaidKey);
2122 }
2123 });
2124 }
2125 }
2126
Svet Ganov53a441c2016-04-19 19:38:00 -07002127 // Nuke generation tracking data
2128 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002129 }
2130
Svetoslav683914b2015-01-15 14:22:26 -08002131 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002132 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002133 final int key = makeKey(type, userId);
2134
Svetoslav Ganove080da92016-12-21 17:10:35 -08002135 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002136 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002137 if (settingsState != null) {
2138 success = settingsState.insertSettingLocked(name, value,
2139 tag, makeDefault, packageName);
2140 }
Svetoslav683914b2015-01-15 14:22:26 -08002141
Svet Ganov53a441c2016-04-19 19:38:00 -07002142 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002143 notifyForSettingsChange(key, name);
2144 }
2145 return success;
2146 }
2147
Svet Ganov53a441c2016-04-19 19:38:00 -07002148 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002149 final int key = makeKey(type, userId);
2150
Svetoslav Ganove080da92016-12-21 17:10:35 -08002151 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002152 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002153 if (settingsState != null) {
2154 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002155 }
Svetoslav683914b2015-01-15 14:22:26 -08002156
Svet Ganov53a441c2016-04-19 19:38:00 -07002157 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002158 notifyForSettingsChange(key, name);
2159 }
2160 return success;
2161 }
2162
2163 public Setting getSettingLocked(int type, int userId, String name) {
2164 final int key = makeKey(type, userId);
2165
2166 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002167 if (settingsState == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002168 return settingsState.getNullSetting();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002169 }
Mark Rathjend891f012017-01-19 04:10:37 +00002170
2171 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002172 return settingsState.getSettingLocked(name);
2173 }
2174
2175 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002176 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002177 final int key = makeKey(type, userId);
2178
Svetoslav Ganove080da92016-12-21 17:10:35 -08002179 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002180 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002181 if (settingsState != null) {
2182 success = settingsState.updateSettingLocked(name, value, tag,
2183 makeDefault, packageName);
2184 }
Svetoslav683914b2015-01-15 14:22:26 -08002185
Svet Ganov53a441c2016-04-19 19:38:00 -07002186 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002187 notifyForSettingsChange(key, name);
2188 }
2189
2190 return success;
2191 }
2192
Svetoslav Ganove080da92016-12-21 17:10:35 -08002193 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2194 String tag) {
2195 final int key = makeKey(type, userId);
2196 SettingsState settingsState = peekSettingsStateLocked(key);
2197 if (settingsState == null) {
2198 return;
2199 }
2200
2201 switch (mode) {
2202 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2203 for (String name : settingsState.getSettingNamesLocked()) {
2204 Setting setting = settingsState.getSettingLocked(name);
2205 if (packageName.equals(setting.getPackageName())) {
2206 if (tag != null && !tag.equals(setting.getTag())) {
2207 continue;
2208 }
2209 if (settingsState.resetSettingLocked(name, packageName)) {
2210 notifyForSettingsChange(key, name);
2211 }
2212 }
2213 }
2214 } break;
2215
2216 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2217 for (String name : settingsState.getSettingNamesLocked()) {
2218 Setting setting = settingsState.getSettingLocked(name);
2219 if (!SettingsState.isSystemPackage(getContext(),
2220 setting.getPackageName())) {
2221 if (settingsState.resetSettingLocked(name, packageName)) {
2222 notifyForSettingsChange(key, name);
2223 }
2224 }
2225 }
2226 } break;
2227
2228 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2229 for (String name : settingsState.getSettingNamesLocked()) {
2230 Setting setting = settingsState.getSettingLocked(name);
2231 if (!SettingsState.isSystemPackage(getContext(),
2232 setting.getPackageName())) {
2233 if (setting.isDefaultSystemSet()) {
2234 if (settingsState.resetSettingLocked(name, packageName)) {
2235 notifyForSettingsChange(key, name);
2236 }
2237 } else if (settingsState.deleteSettingLocked(name)) {
2238 notifyForSettingsChange(key, name);
2239 }
2240 }
2241 }
2242 } break;
2243
2244 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2245 for (String name : settingsState.getSettingNamesLocked()) {
2246 Setting setting = settingsState.getSettingLocked(name);
2247 if (setting.isDefaultSystemSet()) {
2248 if (settingsState.resetSettingLocked(name, packageName)) {
2249 notifyForSettingsChange(key, name);
2250 }
2251 } else if (settingsState.deleteSettingLocked(name)) {
2252 notifyForSettingsChange(key, name);
2253 }
2254 }
2255 } break;
2256 }
2257 }
2258
Svetoslav683914b2015-01-15 14:22:26 -08002259 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002260 // Global and secure settings are signature protected. Apps signed
2261 // by the platform certificate are generally not uninstalled and
2262 // the main exception is tests. We trust components signed
2263 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002264
2265 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2266 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002267 if (systemSettings != null) {
2268 systemSettings.onPackageRemovedLocked(packageName);
2269 }
Svetoslav683914b2015-01-15 14:22:26 -08002270 }
2271
Mark Rathjend891f012017-01-19 04:10:37 +00002272 public void onUidRemovedLocked(int uid) {
2273 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2274 UserHandle.getUserId(uid));
2275 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2276 }
2277
Svetoslav683914b2015-01-15 14:22:26 -08002278 private SettingsState peekSettingsStateLocked(int key) {
2279 SettingsState settingsState = mSettingsStates.get(key);
2280 if (settingsState != null) {
2281 return settingsState;
2282 }
2283
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002284 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2285 return null;
2286 }
Svetoslav683914b2015-01-15 14:22:26 -08002287 return mSettingsStates.get(key);
2288 }
2289
2290 private void migrateAllLegacySettingsIfNeeded() {
2291 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002292 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002293 File globalFile = getSettingsFile(key);
2294 if (globalFile.exists()) {
2295 return;
2296 }
2297
2298 final long identity = Binder.clearCallingIdentity();
2299 try {
2300 List<UserInfo> users = mUserManager.getUsers(true);
2301
2302 final int userCount = users.size();
2303 for (int i = 0; i < userCount; i++) {
2304 final int userId = users.get(i).id;
2305
2306 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2307 SQLiteDatabase database = dbHelper.getWritableDatabase();
2308 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2309
2310 // Upgrade to the latest version.
2311 UpgradeController upgrader = new UpgradeController(userId);
2312 upgrader.upgradeIfNeededLocked();
2313
2314 // Drop from memory if not a running user.
2315 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2316 removeUserStateLocked(userId, false);
2317 }
2318 }
2319 } finally {
2320 Binder.restoreCallingIdentity(identity);
2321 }
2322 }
2323 }
2324
2325 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2326 // Every user has secure settings and if no file we need to migrate.
2327 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2328 File secureFile = getSettingsFile(secureKey);
2329 if (secureFile.exists()) {
2330 return;
2331 }
2332
2333 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2334 SQLiteDatabase database = dbHelper.getWritableDatabase();
2335
2336 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2337 }
2338
2339 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2340 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002341 // Move over the system settings.
2342 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2343 ensureSettingsStateLocked(systemKey);
2344 SettingsState systemSettings = mSettingsStates.get(systemKey);
2345 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2346 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002347
2348 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002349 // Do this after System settings, since this is the first thing we check when deciding
2350 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002351 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2352 ensureSettingsStateLocked(secureKey);
2353 SettingsState secureSettings = mSettingsStates.get(secureKey);
2354 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2355 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2356 secureSettings.persistSyncLocked();
2357
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002358 // Move over the global settings if owner.
2359 // Do this last, since this is the first thing we check when deciding
2360 // to skip over migration from db to xml for owner user.
2361 if (userId == UserHandle.USER_SYSTEM) {
2362 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2363 ensureSettingsStateLocked(globalKey);
2364 SettingsState globalSettings = mSettingsStates.get(globalKey);
2365 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2366 globalSettings.persistSyncLocked();
2367 }
Svetoslav683914b2015-01-15 14:22:26 -08002368
2369 // Drop the database as now all is moved and persisted.
2370 if (DROP_DATABASE_ON_MIGRATION) {
2371 dbHelper.dropDatabase();
2372 } else {
2373 dbHelper.backupDatabase();
2374 }
2375 }
2376
2377 private void migrateLegacySettingsLocked(SettingsState settingsState,
2378 SQLiteDatabase database, String table) {
2379 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2380 queryBuilder.setTables(table);
2381
2382 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2383 null, null, null, null, null);
2384
2385 if (cursor == null) {
2386 return;
2387 }
2388
2389 try {
2390 if (!cursor.moveToFirst()) {
2391 return;
2392 }
2393
2394 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2395 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2396
2397 settingsState.setVersionLocked(database.getVersion());
2398
2399 while (!cursor.isAfterLast()) {
2400 String name = cursor.getString(nameColumnIdx);
2401 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002402 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002403 SettingsState.SYSTEM_PACKAGE_NAME);
2404 cursor.moveToNext();
2405 }
2406 } finally {
2407 cursor.close();
2408 }
2409 }
2410
2411 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2412 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2413
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002414 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002415 return;
2416 }
2417
2418 final int userId = getUserIdFromKey(secureSettings.mKey);
2419
2420 final UserInfo user;
2421 final long identity = Binder.clearCallingIdentity();
2422 try {
2423 user = mUserManager.getUserInfo(userId);
2424 } finally {
2425 Binder.restoreCallingIdentity(identity);
2426 }
2427 if (user == null) {
2428 // Can happen due to races when deleting users - treat as benign.
2429 return;
2430 }
2431
2432 String androidId = Long.toHexString(new SecureRandom().nextLong());
2433 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002434 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002435
2436 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2437 + "] for user " + userId);
2438
2439 // Write a drop box entry if it's a restricted profile
2440 if (user.isRestricted()) {
2441 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2442 Context.DROPBOX_SERVICE);
2443 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2444 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2445 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2446 }
2447 }
2448 }
2449
2450 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002451 final int userId = getUserIdFromKey(key);
2452 Uri uri = getNotificationUriFor(key, name);
2453
Phil Weaver83fec002016-05-11 10:55:29 -07002454 mGenerationRegistry.incrementGeneration(key);
2455
Svetoslav7e0683b2015-08-03 16:02:52 -07002456 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2457 userId, 0, uri).sendToTarget();
2458
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002459 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002460 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2461 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002462 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002463 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2464 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002465 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002466
Svet Ganov53a441c2016-04-19 19:38:00 -07002467 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002468 }
2469
Svet Ganov53a441c2016-04-19 19:38:00 -07002470 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002471 Set<String> keysCloned) {
2472 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002473 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002474 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002475 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002476 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002477 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002478 final int key = makeKey(type, profileId);
2479 mGenerationRegistry.incrementGeneration(key);
2480
2481 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002482 }
2483 }
2484 }
Svetoslav683914b2015-01-15 14:22:26 -08002485 }
2486
Svetoslav683914b2015-01-15 14:22:26 -08002487 private boolean isGlobalSettingsKey(int key) {
2488 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2489 }
2490
2491 private boolean isSystemSettingsKey(int key) {
2492 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2493 }
2494
2495 private boolean isSecureSettingsKey(int key) {
2496 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2497 }
2498
Mark Rathjend891f012017-01-19 04:10:37 +00002499 private boolean isSsaidSettingsKey(int key) {
2500 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2501 }
2502
Svetoslav683914b2015-01-15 14:22:26 -08002503 private File getSettingsFile(int key) {
2504 if (isGlobalSettingsKey(key)) {
2505 final int userId = getUserIdFromKey(key);
2506 return new File(Environment.getUserSystemDirectory(userId),
2507 SETTINGS_FILE_GLOBAL);
2508 } else if (isSystemSettingsKey(key)) {
2509 final int userId = getUserIdFromKey(key);
2510 return new File(Environment.getUserSystemDirectory(userId),
2511 SETTINGS_FILE_SYSTEM);
2512 } else if (isSecureSettingsKey(key)) {
2513 final int userId = getUserIdFromKey(key);
2514 return new File(Environment.getUserSystemDirectory(userId),
2515 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002516 } else if (isSsaidSettingsKey(key)) {
2517 final int userId = getUserIdFromKey(key);
2518 return new File(Environment.getUserSystemDirectory(userId),
2519 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002520 } else {
2521 throw new IllegalArgumentException("Invalid settings key:" + key);
2522 }
2523 }
2524
2525 private Uri getNotificationUriFor(int key, String name) {
2526 if (isGlobalSettingsKey(key)) {
2527 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2528 : Settings.Global.CONTENT_URI;
2529 } else if (isSecureSettingsKey(key)) {
2530 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2531 : Settings.Secure.CONTENT_URI;
2532 } else if (isSystemSettingsKey(key)) {
2533 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2534 : Settings.System.CONTENT_URI;
2535 } else {
2536 throw new IllegalArgumentException("Invalid settings key:" + key);
2537 }
2538 }
2539
2540 private int getMaxBytesPerPackageForType(int type) {
2541 switch (type) {
2542 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002543 case SETTINGS_TYPE_SECURE:
2544 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002545 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2546 }
2547
2548 default: {
2549 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2550 }
2551 }
2552 }
2553
Svetoslav7e0683b2015-08-03 16:02:52 -07002554 private final class MyHandler extends Handler {
2555 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2556 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2557
2558 public MyHandler(Looper looper) {
2559 super(looper);
2560 }
2561
2562 @Override
2563 public void handleMessage(Message msg) {
2564 switch (msg.what) {
2565 case MSG_NOTIFY_URI_CHANGED: {
2566 final int userId = msg.arg1;
2567 Uri uri = (Uri) msg.obj;
2568 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2569 if (DEBUG) {
2570 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2571 }
2572 } break;
2573
2574 case MSG_NOTIFY_DATA_CHANGED: {
2575 mBackupManager.dataChanged();
2576 } break;
2577 }
2578 }
2579 }
2580
Svetoslav683914b2015-01-15 14:22:26 -08002581 private final class UpgradeController {
Mark Rathjend891f012017-01-19 04:10:37 +00002582 private static final int SETTINGS_VERSION = 137;
Svetoslav683914b2015-01-15 14:22:26 -08002583
2584 private final int mUserId;
2585
2586 public UpgradeController(int userId) {
2587 mUserId = userId;
2588 }
2589
2590 public void upgradeIfNeededLocked() {
2591 // The version of all settings for a user is the same (all users have secure).
2592 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002593 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002594
2595 // Try an update from the current state.
2596 final int oldVersion = secureSettings.getVersionLocked();
2597 final int newVersion = SETTINGS_VERSION;
2598
Svet Ganovc9755bc2015-03-28 13:21:22 -07002599 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002600 if (oldVersion == newVersion) {
2601 return;
2602 }
2603
2604 // Try to upgrade.
2605 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2606
2607 // If upgrade failed start from scratch and upgrade.
2608 if (curVersion != newVersion) {
2609 // Drop state we have for this user.
2610 removeUserStateLocked(mUserId, true);
2611
2612 // Recreate the database.
2613 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2614 SQLiteDatabase database = dbHelper.getWritableDatabase();
2615 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2616
2617 // Migrate the settings for this user.
2618 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2619
2620 // Now upgrade should work fine.
2621 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002622
2623 // Make a note what happened, so we don't wonder why data was lost
2624 String reason = "Settings rebuilt! Current version: "
2625 + curVersion + " while expected: " + newVersion;
2626 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002627 Settings.Global.DATABASE_DOWNGRADE_REASON,
2628 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002629 }
2630
2631 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002632 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002633 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002634 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002635 globalSettings.setVersionLocked(newVersion);
2636 }
2637
2638 // Set the secure settings version.
2639 secureSettings.setVersionLocked(newVersion);
2640
2641 // Set the system settings version.
2642 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002643 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002644 systemSettings.setVersionLocked(newVersion);
2645 }
2646
2647 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002648 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002649 }
2650
2651 private SettingsState getSecureSettingsLocked(int userId) {
2652 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2653 }
2654
Mark Rathjend891f012017-01-19 04:10:37 +00002655 private SettingsState getSsaidSettingsLocked(int userId) {
2656 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2657 }
2658
Svetoslav683914b2015-01-15 14:22:26 -08002659 private SettingsState getSystemSettingsLocked(int userId) {
2660 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2661 }
2662
Jeff Brown503cffc2015-03-26 18:08:51 -07002663 /**
2664 * You must perform all necessary mutations to bring the settings
2665 * for this user from the old to the new version. When you add a new
2666 * upgrade step you *must* update SETTINGS_VERSION.
2667 *
2668 * This is an example of moving a setting from secure to global.
2669 *
2670 * // v119: Example settings changes.
2671 * if (currentVersion == 118) {
2672 * if (userId == UserHandle.USER_OWNER) {
2673 * // Remove from the secure settings.
2674 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2675 * String name = "example_setting_to_move";
2676 * String value = secureSettings.getSetting(name);
2677 * secureSettings.deleteSetting(name);
2678 *
2679 * // Add to the global settings.
2680 * SettingsState globalSettings = getGlobalSettingsLocked();
2681 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2682 * }
2683 *
2684 * // Update the current version.
2685 * currentVersion = 119;
2686 * }
2687 */
Svetoslav683914b2015-01-15 14:22:26 -08002688 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2689 if (DEBUG) {
2690 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2691 + oldVersion + " to version: " + newVersion);
2692 }
2693
Jeff Brown503cffc2015-03-26 18:08:51 -07002694 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002695
John Spurlocke11ae112015-05-11 16:09:03 -04002696 // v119: Reset zen + ringer mode.
2697 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002698 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002699 final SettingsState globalSettings = getGlobalSettingsLocked();
2700 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002701 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2702 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002703 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002704 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2705 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002706 }
2707 currentVersion = 119;
2708 }
2709
Jason Monk27bbb2d2015-03-31 16:46:39 -04002710 // v120: Add double tap to wake setting.
2711 if (currentVersion == 119) {
2712 SettingsState secureSettings = getSecureSettingsLocked(userId);
2713 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2714 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002715 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002716 SettingsState.SYSTEM_PACKAGE_NAME);
2717
2718 currentVersion = 120;
2719 }
2720
Svetoslav7e0683b2015-08-03 16:02:52 -07002721 if (currentVersion == 120) {
2722 // Before 121, we used a different string encoding logic. We just bump the
2723 // version here; SettingsState knows how to handle pre-version 120 files.
2724 currentVersion = 121;
2725 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002726
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002727 if (currentVersion == 121) {
2728 // Version 122: allow OEMs to set a default payment component in resources.
2729 // Note that we only write the default if no default has been set;
2730 // if there is, we just leave the default at whatever it currently is.
2731 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2732 String defaultComponent = (getContext().getResources().getString(
2733 R.string.def_nfc_payment_component));
2734 Setting currentSetting = secureSettings.getSettingLocked(
2735 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2736 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002737 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002738 secureSettings.insertSettingLocked(
2739 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002740 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002741 }
2742 currentVersion = 122;
2743 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002744
2745 if (currentVersion == 122) {
2746 // Version 123: Adding a default value for the ability to add a user from
2747 // the lock screen.
2748 if (userId == UserHandle.USER_SYSTEM) {
2749 final SettingsState globalSettings = getGlobalSettingsLocked();
2750 Setting currentSetting = globalSettings.getSettingLocked(
2751 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002752 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002753 globalSettings.insertSettingLocked(
2754 Settings.Global.ADD_USERS_WHEN_LOCKED,
2755 getContext().getResources().getBoolean(
2756 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002757 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002758 }
2759 }
2760 currentVersion = 123;
2761 }
Bryce Leebd179282015-12-17 19:01:37 -08002762
2763 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002764 final SettingsState globalSettings = getGlobalSettingsLocked();
2765 String defaultDisabledProfiles = (getContext().getResources().getString(
2766 R.string.def_bluetooth_disabled_profiles));
2767 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002768 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002769 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002770 }
2771
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002772 if (currentVersion == 124) {
2773 // Version 124: allow OEMs to set a default value for whether IME should be
2774 // shown when a physical keyboard is connected.
2775 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2776 Setting currentSetting = secureSettings.getSettingLocked(
2777 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002778 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002779 secureSettings.insertSettingLocked(
2780 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2781 getContext().getResources().getBoolean(
2782 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002783 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002784 }
2785 currentVersion = 125;
2786 }
2787
Ruben Brunk98576cf2016-03-07 18:54:28 -08002788 if (currentVersion == 125) {
2789 // Version 125: Allow OEMs to set the default VR service.
2790 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2791
2792 Setting currentSetting = secureSettings.getSettingLocked(
2793 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002794 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002795 ArraySet<ComponentName> l =
2796 SystemConfig.getInstance().getDefaultVrComponents();
2797
2798 if (l != null && !l.isEmpty()) {
2799 StringBuilder b = new StringBuilder();
2800 boolean start = true;
2801 for (ComponentName c : l) {
2802 if (!start) {
2803 b.append(':');
2804 }
2805 b.append(c.flattenToString());
2806 start = false;
2807 }
2808 secureSettings.insertSettingLocked(
2809 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002810 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002811 }
2812
2813 }
2814 currentVersion = 126;
2815 }
2816
Daniel U02ba6122016-04-01 18:41:42 +01002817 if (currentVersion == 126) {
2818 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2819 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2820 if (mUserManager.isManagedProfile(userId)) {
2821 final SettingsState systemSecureSettings =
2822 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2823
2824 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2825 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002826 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002827 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2828 secureSettings.insertSettingLocked(
2829 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002830 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002831 SettingsState.SYSTEM_PACKAGE_NAME);
2832 }
2833
2834 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2835 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002836 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002837 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2838 secureSettings.insertSettingLocked(
2839 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002840 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002841 SettingsState.SYSTEM_PACKAGE_NAME);
2842 }
2843 }
2844 currentVersion = 127;
2845 }
2846
Steven Ngdc20ba62016-04-26 18:19:04 +01002847 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002848 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002849 currentVersion = 128;
2850 }
2851
Julia Reynolds1f721e12016-07-11 08:50:58 -04002852 if (currentVersion == 128) {
2853 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2854 // the new apps are appended to the list of already approved apps.
2855 final SettingsState systemSecureSettings =
2856 getSecureSettingsLocked(userId);
2857
2858 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2859 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2860 String defaultPolicyAccess = getContext().getResources().getString(
2861 com.android.internal.R.string.config_defaultDndAccessPackages);
2862 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2863 if (policyAccess.isNull()) {
2864 systemSecureSettings.insertSettingLocked(
2865 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002866 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002867 SettingsState.SYSTEM_PACKAGE_NAME);
2868 } else {
2869 StringBuilder currentSetting =
2870 new StringBuilder(policyAccess.getValue());
2871 currentSetting.append(":");
2872 currentSetting.append(defaultPolicyAccess);
2873 systemSecureSettings.updateSettingLocked(
2874 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002875 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002876 SettingsState.SYSTEM_PACKAGE_NAME);
2877 }
2878 }
2879
2880 currentVersion = 129;
2881 }
2882
Dan Sandler71f85e92016-07-20 13:46:05 -04002883 if (currentVersion == 129) {
2884 // default longpress timeout changed from 500 to 400. If unchanged from the old
2885 // default, update to the new default.
2886 final SettingsState systemSecureSettings =
2887 getSecureSettingsLocked(userId);
2888 final String oldValue = systemSecureSettings.getSettingLocked(
2889 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2890 if (TextUtils.equals("500", oldValue)) {
2891 systemSecureSettings.insertSettingLocked(
2892 Settings.Secure.LONG_PRESS_TIMEOUT,
2893 String.valueOf(getContext().getResources().getInteger(
2894 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002895 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04002896 }
2897 currentVersion = 130;
2898 }
2899
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002900 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07002901 // Split Ambient settings
2902 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2903 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
2904 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
2905
2906 if (dozeExplicitlyDisabled) {
2907 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002908 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002909 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002910 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002911 }
2912 currentVersion = 131;
2913 }
2914
2915 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002916 // Initialize new multi-press timeout to default value
2917 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2918 final String oldValue = systemSecureSettings.getSettingLocked(
2919 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2920 if (TextUtils.equals(null, oldValue)) {
2921 systemSecureSettings.insertSettingLocked(
2922 Settings.Secure.MULTI_PRESS_TIMEOUT,
2923 String.valueOf(getContext().getResources().getInteger(
2924 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002925 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002926 }
2927
Adrian Roos69741a22016-10-21 14:49:17 -07002928 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002929 }
2930
Adrian Roos69741a22016-10-21 14:49:17 -07002931 if (currentVersion == 132) {
2932 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01002933 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2934 String defaultSyncParentSounds = (getContext().getResources()
2935 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
2936 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002937 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
2938 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002939 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01002940 }
2941
Adrian Roos69741a22016-10-21 14:49:17 -07002942 if (currentVersion == 133) {
2943 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07002944 final SettingsState systemSettings = getSystemSettingsLocked(userId);
2945 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
2946 null) {
2947 String defaultEndButtonBehavior = Integer.toString(getContext()
2948 .getResources().getInteger(R.integer.def_end_button_behavior));
2949 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002950 defaultEndButtonBehavior, null, true,
2951 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07002952 }
Adrian Roos69741a22016-10-21 14:49:17 -07002953 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07002954 }
2955
Phil Weaver89e3ffc2016-09-19 13:51:10 -07002956 if (currentVersion == 134) {
2957 // Remove setting that specifies if magnification values should be preserved.
2958 // This setting defaulted to true and never has a UI.
2959 getSecureSettingsLocked(userId).deleteSettingLocked(
2960 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
2961 currentVersion = 135;
2962 }
2963
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002964 if (currentVersion == 135) {
2965 // Version 135: Migrating the NETWORK_SCORER_APP setting to the
2966 // NETWORK_RECOMMENDATIONS_ENABLED setting.
2967 if (userId == UserHandle.USER_SYSTEM) {
2968 final SettingsState globalSettings = getGlobalSettingsLocked();
2969 Setting currentSetting = globalSettings.getSettingLocked(
2970 Global.NETWORK_SCORER_APP);
2971 if (!currentSetting.isNull()) {
2972 // A scorer was set so enable recommendations.
2973 globalSettings.insertSettingLocked(
2974 Global.NETWORK_RECOMMENDATIONS_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002975 "1", null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002976 SettingsState.SYSTEM_PACKAGE_NAME);
2977
2978 // and clear the scorer setting since it's no longer needed.
2979 globalSettings.insertSettingLocked(
2980 Global.NETWORK_SCORER_APP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002981 null, null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002982 SettingsState.SYSTEM_PACKAGE_NAME);
2983 }
2984 }
2985 currentVersion = 136;
2986 }
2987
Mark Rathjend891f012017-01-19 04:10:37 +00002988 if (currentVersion == 136) {
2989 // Version 136: Store legacy SSAID for all apps currently installed on the
2990 // device as first step in migrating SSAID to be unique per application.
2991
2992 final boolean isUpgrade;
2993 try {
2994 isUpgrade = mPackageManager.isUpgrade();
2995 } catch (RemoteException e) {
2996 throw new IllegalStateException("Package manager not available");
2997 }
2998 // Only retain legacy ssaid if the device is performing an OTA. After wiping
2999 // user data or first boot on a new device should use new ssaid generation.
3000 if (isUpgrade) {
3001 // Retrieve the legacy ssaid from the secure settings table.
3002 final String legacySsaid = getSettingLocked(SETTINGS_TYPE_SECURE, userId,
3003 Settings.Secure.ANDROID_ID).getValue();
3004
3005 // Fill each uid with the legacy ssaid to be backwards compatible.
3006 final List<PackageInfo> packages;
3007 try {
3008 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3009 } catch (RemoteException e) {
3010 throw new IllegalStateException("Package manager not available");
3011 }
3012
3013 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3014 for (PackageInfo info : packages) {
3015 // Check if the UID already has an entry in the table.
3016 final String uid = Integer.toString(info.applicationInfo.uid);
3017 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3018
3019 if (ssaid.isNull() || ssaid.getValue() == null) {
3020 // Android Id doesn't exist for this package so create it.
3021 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3022 info.packageName);
3023 }
3024 }
3025 }
3026
3027 currentVersion = 137;
3028 }
3029
Dan Sandler71f85e92016-07-20 13:46:05 -04003030 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003031 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003032 + newVersion + " left it at "
3033 + currentVersion + " instead; this is probably a bug", new Throwable());
3034 if (DEBUG) {
3035 throw new RuntimeException("db upgrade error");
3036 }
3037 }
3038
Jeff Brown503cffc2015-03-26 18:08:51 -07003039 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003040
Jeff Brown503cffc2015-03-26 18:08:51 -07003041 // Return the current version.
3042 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003043 }
3044 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003045 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003046}