blob: a33ab162debf8c3a2d978be5beb30bdca971e3fe [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.
Mark Rathjenea617592017-01-18 23:03:41 -08001042 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001043 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);
Mark Rathjenea617592017-01-18 23:03:41 -08001926 if (userKeySetting == null || userKeySetting.isNull()
1927 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001928 // Lazy initialize and store the user key.
1929 generateUserKeyLocked(userId);
1930 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08001931 if (userKeySetting == null || userKeySetting.isNull()
1932 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001933 throw new IllegalStateException("User key not accessible");
1934 }
1935 }
1936 final String userKey = userKeySetting.getValue();
1937
1938 // Convert the user's key back to a byte array.
1939 final byte[] keyBytes = ByteStringUtils.toByteArray(userKey);
1940 if (keyBytes == null || keyBytes.length != 16) {
1941 throw new IllegalStateException("User key invalid");
1942 }
1943
1944 final MessageDigest md;
1945 try {
1946 // Hash package name and signature.
1947 md = MessageDigest.getInstance("SHA-256");
1948 } catch (NoSuchAlgorithmException e) {
1949 throw new IllegalStateException("HmacSHA256 is not available");
1950 }
1951 md.update(keyBytes);
1952 md.update(packageInfo.packageName.getBytes(StandardCharsets.UTF_8));
1953 md.update(packageInfo.signatures[0].toByteArray());
1954
1955 // Convert result to a string for storage in settings table. Only want first 64 bits.
1956 final String ssaid = ByteStringUtils.toString(md.digest()).substring(0, 16)
1957 .toLowerCase();
1958
1959 // Save the ssaid in the ssaid table.
1960 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
1961 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1962 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
1963 packageName);
1964
1965 if (!success) {
1966 throw new IllegalStateException("Ssaid settings not accessible");
1967 }
1968
1969 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
1970 }
1971
1972 public void syncSsaidTableOnStart() {
1973 synchronized (mLock) {
1974 // Verify that each user's packages and ssaid's are in sync.
1975 for (UserInfo user : mUserManager.getUsers(true)) {
1976 // Get all uids for the user's packages.
1977 final List<PackageInfo> packages;
1978 try {
1979 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
1980 } catch (RemoteException e) {
1981 throw new IllegalStateException("Package manager not available");
1982 }
1983 final Set<String> appUids = new HashSet<>();
1984 for (PackageInfo info : packages) {
1985 appUids.add(Integer.toString(info.applicationInfo.uid));
1986 }
1987
1988 // Get all uids currently stored in the user's ssaid table.
1989 final Set<String> ssaidUids = new HashSet<>(
1990 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
1991 ssaidUids.remove(SSAID_USER_KEY);
1992
1993 // Perform a set difference for the appUids and ssaidUids.
1994 ssaidUids.removeAll(appUids);
1995
1996 // If there are ssaidUids left over they need to be removed from the table.
1997 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
1998 user.id);
1999 for (String uid : ssaidUids) {
2000 ssaidSettings.deleteSettingLocked(uid);
2001 }
2002 }
2003 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002004 }
2005
Svetoslav683914b2015-01-15 14:22:26 -08002006 public List<String> getSettingsNamesLocked(int type, int userId) {
2007 final int key = makeKey(type, userId);
2008 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002009 if (settingsState == null) {
2010 return new ArrayList<String>();
2011 }
Svetoslav683914b2015-01-15 14:22:26 -08002012 return settingsState.getSettingNamesLocked();
2013 }
2014
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002015 public SparseBooleanArray getKnownUsersLocked() {
2016 SparseBooleanArray users = new SparseBooleanArray();
2017 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2018 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2019 }
2020 return users;
2021 }
2022
Svetoslav683914b2015-01-15 14:22:26 -08002023 public SettingsState getSettingsLocked(int type, int userId) {
2024 final int key = makeKey(type, userId);
2025 return peekSettingsStateLocked(key);
2026 }
2027
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002028 public boolean ensureSettingsForUserLocked(int userId) {
2029 // First make sure this user actually exists.
2030 if (mUserManager.getUserInfo(userId) == null) {
2031 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2032 return false;
2033 }
2034
Svetoslav683914b2015-01-15 14:22:26 -08002035 // Migrate the setting for this user if needed.
2036 migrateLegacySettingsForUserIfNeededLocked(userId);
2037
2038 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002039 if (userId == UserHandle.USER_SYSTEM) {
2040 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002041 ensureSettingsStateLocked(globalKey);
2042 }
2043
2044 // Ensure secure settings loaded.
2045 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2046 ensureSettingsStateLocked(secureKey);
2047
2048 // Make sure the secure settings have an Android id set.
2049 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2050 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2051
2052 // Ensure system settings loaded.
2053 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2054 ensureSettingsStateLocked(systemKey);
2055
Mark Rathjend891f012017-01-19 04:10:37 +00002056 // Ensure secure settings loaded.
2057 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2058 ensureSettingsStateLocked(ssaidKey);
2059
Svetoslav683914b2015-01-15 14:22:26 -08002060 // Upgrade the settings to the latest version.
2061 UpgradeController upgrader = new UpgradeController(userId);
2062 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002063 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002064 }
2065
2066 private void ensureSettingsStateLocked(int key) {
2067 if (mSettingsStates.get(key) == null) {
2068 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002069 SettingsState settingsState = new SettingsState(getContext(), mLock,
2070 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002071 mSettingsStates.put(key, settingsState);
2072 }
2073 }
2074
2075 public void removeUserStateLocked(int userId, boolean permanently) {
2076 // We always keep the global settings in memory.
2077
2078 // Nuke system settings.
2079 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2080 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2081 if (systemSettingsState != null) {
2082 if (permanently) {
2083 mSettingsStates.remove(systemKey);
2084 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002085 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002086 systemSettingsState.destroyLocked(new Runnable() {
2087 @Override
2088 public void run() {
2089 mSettingsStates.remove(systemKey);
2090 }
2091 });
2092 }
2093 }
2094
2095 // Nuke secure settings.
2096 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2097 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2098 if (secureSettingsState != null) {
2099 if (permanently) {
2100 mSettingsStates.remove(secureKey);
2101 secureSettingsState.destroyLocked(null);
2102 } else {
2103 secureSettingsState.destroyLocked(new Runnable() {
2104 @Override
2105 public void run() {
2106 mSettingsStates.remove(secureKey);
2107 }
2108 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002109 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002110 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002111
Mark Rathjend891f012017-01-19 04:10:37 +00002112 // Nuke ssaid settings.
2113 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2114 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2115 if (ssaidSettingsState != null) {
2116 if (permanently) {
2117 mSettingsStates.remove(ssaidKey);
2118 ssaidSettingsState.destroyLocked(null);
2119 } else {
2120 ssaidSettingsState.destroyLocked(new Runnable() {
2121 @Override
2122 public void run() {
2123 mSettingsStates.remove(ssaidKey);
2124 }
2125 });
2126 }
2127 }
2128
Svet Ganov53a441c2016-04-19 19:38:00 -07002129 // Nuke generation tracking data
2130 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002131 }
2132
Svetoslav683914b2015-01-15 14:22:26 -08002133 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002134 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002135 final int key = makeKey(type, userId);
2136
Svetoslav Ganove080da92016-12-21 17:10:35 -08002137 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002138 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002139 if (settingsState != null) {
2140 success = settingsState.insertSettingLocked(name, value,
2141 tag, makeDefault, packageName);
2142 }
Svetoslav683914b2015-01-15 14:22:26 -08002143
Svet Ganov53a441c2016-04-19 19:38:00 -07002144 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002145 notifyForSettingsChange(key, name);
2146 }
2147 return success;
2148 }
2149
Svet Ganov53a441c2016-04-19 19:38:00 -07002150 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002151 final int key = makeKey(type, userId);
2152
Svetoslav Ganove080da92016-12-21 17:10:35 -08002153 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002154 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002155 if (settingsState != null) {
2156 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002157 }
Svetoslav683914b2015-01-15 14:22:26 -08002158
Svet Ganov53a441c2016-04-19 19:38:00 -07002159 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002160 notifyForSettingsChange(key, name);
2161 }
2162 return success;
2163 }
2164
2165 public Setting getSettingLocked(int type, int userId, String name) {
2166 final int key = makeKey(type, userId);
2167
2168 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002169 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002170 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002171 }
Mark Rathjend891f012017-01-19 04:10:37 +00002172
2173 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002174 return settingsState.getSettingLocked(name);
2175 }
2176
2177 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002178 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002179 final int key = makeKey(type, userId);
2180
Svetoslav Ganove080da92016-12-21 17:10:35 -08002181 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002182 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002183 if (settingsState != null) {
2184 success = settingsState.updateSettingLocked(name, value, tag,
2185 makeDefault, packageName);
2186 }
Svetoslav683914b2015-01-15 14:22:26 -08002187
Svet Ganov53a441c2016-04-19 19:38:00 -07002188 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002189 notifyForSettingsChange(key, name);
2190 }
2191
2192 return success;
2193 }
2194
Svetoslav Ganove080da92016-12-21 17:10:35 -08002195 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2196 String tag) {
2197 final int key = makeKey(type, userId);
2198 SettingsState settingsState = peekSettingsStateLocked(key);
2199 if (settingsState == null) {
2200 return;
2201 }
2202
2203 switch (mode) {
2204 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2205 for (String name : settingsState.getSettingNamesLocked()) {
2206 Setting setting = settingsState.getSettingLocked(name);
2207 if (packageName.equals(setting.getPackageName())) {
2208 if (tag != null && !tag.equals(setting.getTag())) {
2209 continue;
2210 }
2211 if (settingsState.resetSettingLocked(name, packageName)) {
2212 notifyForSettingsChange(key, name);
2213 }
2214 }
2215 }
2216 } break;
2217
2218 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2219 for (String name : settingsState.getSettingNamesLocked()) {
2220 Setting setting = settingsState.getSettingLocked(name);
2221 if (!SettingsState.isSystemPackage(getContext(),
2222 setting.getPackageName())) {
2223 if (settingsState.resetSettingLocked(name, packageName)) {
2224 notifyForSettingsChange(key, name);
2225 }
2226 }
2227 }
2228 } break;
2229
2230 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2231 for (String name : settingsState.getSettingNamesLocked()) {
2232 Setting setting = settingsState.getSettingLocked(name);
2233 if (!SettingsState.isSystemPackage(getContext(),
2234 setting.getPackageName())) {
2235 if (setting.isDefaultSystemSet()) {
2236 if (settingsState.resetSettingLocked(name, packageName)) {
2237 notifyForSettingsChange(key, name);
2238 }
2239 } else if (settingsState.deleteSettingLocked(name)) {
2240 notifyForSettingsChange(key, name);
2241 }
2242 }
2243 }
2244 } break;
2245
2246 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2247 for (String name : settingsState.getSettingNamesLocked()) {
2248 Setting setting = settingsState.getSettingLocked(name);
2249 if (setting.isDefaultSystemSet()) {
2250 if (settingsState.resetSettingLocked(name, packageName)) {
2251 notifyForSettingsChange(key, name);
2252 }
2253 } else if (settingsState.deleteSettingLocked(name)) {
2254 notifyForSettingsChange(key, name);
2255 }
2256 }
2257 } break;
2258 }
2259 }
2260
Svetoslav683914b2015-01-15 14:22:26 -08002261 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002262 // Global and secure settings are signature protected. Apps signed
2263 // by the platform certificate are generally not uninstalled and
2264 // the main exception is tests. We trust components signed
2265 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002266
2267 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2268 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002269 if (systemSettings != null) {
2270 systemSettings.onPackageRemovedLocked(packageName);
2271 }
Svetoslav683914b2015-01-15 14:22:26 -08002272 }
2273
Mark Rathjend891f012017-01-19 04:10:37 +00002274 public void onUidRemovedLocked(int uid) {
2275 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2276 UserHandle.getUserId(uid));
2277 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2278 }
2279
Svetoslav683914b2015-01-15 14:22:26 -08002280 private SettingsState peekSettingsStateLocked(int key) {
2281 SettingsState settingsState = mSettingsStates.get(key);
2282 if (settingsState != null) {
2283 return settingsState;
2284 }
2285
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002286 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2287 return null;
2288 }
Svetoslav683914b2015-01-15 14:22:26 -08002289 return mSettingsStates.get(key);
2290 }
2291
2292 private void migrateAllLegacySettingsIfNeeded() {
2293 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002294 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002295 File globalFile = getSettingsFile(key);
2296 if (globalFile.exists()) {
2297 return;
2298 }
2299
2300 final long identity = Binder.clearCallingIdentity();
2301 try {
2302 List<UserInfo> users = mUserManager.getUsers(true);
2303
2304 final int userCount = users.size();
2305 for (int i = 0; i < userCount; i++) {
2306 final int userId = users.get(i).id;
2307
2308 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2309 SQLiteDatabase database = dbHelper.getWritableDatabase();
2310 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2311
2312 // Upgrade to the latest version.
2313 UpgradeController upgrader = new UpgradeController(userId);
2314 upgrader.upgradeIfNeededLocked();
2315
2316 // Drop from memory if not a running user.
2317 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2318 removeUserStateLocked(userId, false);
2319 }
2320 }
2321 } finally {
2322 Binder.restoreCallingIdentity(identity);
2323 }
2324 }
2325 }
2326
2327 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2328 // Every user has secure settings and if no file we need to migrate.
2329 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2330 File secureFile = getSettingsFile(secureKey);
2331 if (secureFile.exists()) {
2332 return;
2333 }
2334
2335 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2336 SQLiteDatabase database = dbHelper.getWritableDatabase();
2337
2338 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2339 }
2340
2341 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2342 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002343 // Move over the system settings.
2344 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2345 ensureSettingsStateLocked(systemKey);
2346 SettingsState systemSettings = mSettingsStates.get(systemKey);
2347 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2348 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002349
2350 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002351 // Do this after System settings, since this is the first thing we check when deciding
2352 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002353 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2354 ensureSettingsStateLocked(secureKey);
2355 SettingsState secureSettings = mSettingsStates.get(secureKey);
2356 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2357 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2358 secureSettings.persistSyncLocked();
2359
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002360 // Move over the global settings if owner.
2361 // Do this last, since this is the first thing we check when deciding
2362 // to skip over migration from db to xml for owner user.
2363 if (userId == UserHandle.USER_SYSTEM) {
2364 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2365 ensureSettingsStateLocked(globalKey);
2366 SettingsState globalSettings = mSettingsStates.get(globalKey);
2367 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2368 globalSettings.persistSyncLocked();
2369 }
Svetoslav683914b2015-01-15 14:22:26 -08002370
2371 // Drop the database as now all is moved and persisted.
2372 if (DROP_DATABASE_ON_MIGRATION) {
2373 dbHelper.dropDatabase();
2374 } else {
2375 dbHelper.backupDatabase();
2376 }
2377 }
2378
2379 private void migrateLegacySettingsLocked(SettingsState settingsState,
2380 SQLiteDatabase database, String table) {
2381 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2382 queryBuilder.setTables(table);
2383
2384 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2385 null, null, null, null, null);
2386
2387 if (cursor == null) {
2388 return;
2389 }
2390
2391 try {
2392 if (!cursor.moveToFirst()) {
2393 return;
2394 }
2395
2396 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2397 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2398
2399 settingsState.setVersionLocked(database.getVersion());
2400
2401 while (!cursor.isAfterLast()) {
2402 String name = cursor.getString(nameColumnIdx);
2403 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002404 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002405 SettingsState.SYSTEM_PACKAGE_NAME);
2406 cursor.moveToNext();
2407 }
2408 } finally {
2409 cursor.close();
2410 }
2411 }
2412
2413 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2414 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2415
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002416 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002417 return;
2418 }
2419
2420 final int userId = getUserIdFromKey(secureSettings.mKey);
2421
2422 final UserInfo user;
2423 final long identity = Binder.clearCallingIdentity();
2424 try {
2425 user = mUserManager.getUserInfo(userId);
2426 } finally {
2427 Binder.restoreCallingIdentity(identity);
2428 }
2429 if (user == null) {
2430 // Can happen due to races when deleting users - treat as benign.
2431 return;
2432 }
2433
2434 String androidId = Long.toHexString(new SecureRandom().nextLong());
2435 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002436 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002437
2438 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2439 + "] for user " + userId);
2440
2441 // Write a drop box entry if it's a restricted profile
2442 if (user.isRestricted()) {
2443 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2444 Context.DROPBOX_SERVICE);
2445 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2446 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2447 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2448 }
2449 }
2450 }
2451
2452 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002453 final int userId = getUserIdFromKey(key);
2454 Uri uri = getNotificationUriFor(key, name);
2455
Phil Weaver83fec002016-05-11 10:55:29 -07002456 mGenerationRegistry.incrementGeneration(key);
2457
Svetoslav7e0683b2015-08-03 16:02:52 -07002458 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2459 userId, 0, uri).sendToTarget();
2460
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002461 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002462 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2463 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002464 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002465 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2466 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002467 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002468
Svet Ganov53a441c2016-04-19 19:38:00 -07002469 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002470 }
2471
Svet Ganov53a441c2016-04-19 19:38:00 -07002472 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002473 Set<String> keysCloned) {
2474 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002475 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002476 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002477 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002478 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002479 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002480 final int key = makeKey(type, profileId);
2481 mGenerationRegistry.incrementGeneration(key);
2482
2483 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002484 }
2485 }
2486 }
Svetoslav683914b2015-01-15 14:22:26 -08002487 }
2488
Svetoslav683914b2015-01-15 14:22:26 -08002489 private boolean isGlobalSettingsKey(int key) {
2490 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2491 }
2492
2493 private boolean isSystemSettingsKey(int key) {
2494 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2495 }
2496
2497 private boolean isSecureSettingsKey(int key) {
2498 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2499 }
2500
Mark Rathjend891f012017-01-19 04:10:37 +00002501 private boolean isSsaidSettingsKey(int key) {
2502 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2503 }
2504
Svetoslav683914b2015-01-15 14:22:26 -08002505 private File getSettingsFile(int key) {
2506 if (isGlobalSettingsKey(key)) {
2507 final int userId = getUserIdFromKey(key);
2508 return new File(Environment.getUserSystemDirectory(userId),
2509 SETTINGS_FILE_GLOBAL);
2510 } else if (isSystemSettingsKey(key)) {
2511 final int userId = getUserIdFromKey(key);
2512 return new File(Environment.getUserSystemDirectory(userId),
2513 SETTINGS_FILE_SYSTEM);
2514 } else if (isSecureSettingsKey(key)) {
2515 final int userId = getUserIdFromKey(key);
2516 return new File(Environment.getUserSystemDirectory(userId),
2517 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002518 } else if (isSsaidSettingsKey(key)) {
2519 final int userId = getUserIdFromKey(key);
2520 return new File(Environment.getUserSystemDirectory(userId),
2521 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002522 } else {
2523 throw new IllegalArgumentException("Invalid settings key:" + key);
2524 }
2525 }
2526
2527 private Uri getNotificationUriFor(int key, String name) {
2528 if (isGlobalSettingsKey(key)) {
2529 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2530 : Settings.Global.CONTENT_URI;
2531 } else if (isSecureSettingsKey(key)) {
2532 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2533 : Settings.Secure.CONTENT_URI;
2534 } else if (isSystemSettingsKey(key)) {
2535 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2536 : Settings.System.CONTENT_URI;
2537 } else {
2538 throw new IllegalArgumentException("Invalid settings key:" + key);
2539 }
2540 }
2541
2542 private int getMaxBytesPerPackageForType(int type) {
2543 switch (type) {
2544 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002545 case SETTINGS_TYPE_SECURE:
2546 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002547 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2548 }
2549
2550 default: {
2551 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2552 }
2553 }
2554 }
2555
Svetoslav7e0683b2015-08-03 16:02:52 -07002556 private final class MyHandler extends Handler {
2557 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2558 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2559
2560 public MyHandler(Looper looper) {
2561 super(looper);
2562 }
2563
2564 @Override
2565 public void handleMessage(Message msg) {
2566 switch (msg.what) {
2567 case MSG_NOTIFY_URI_CHANGED: {
2568 final int userId = msg.arg1;
2569 Uri uri = (Uri) msg.obj;
2570 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2571 if (DEBUG) {
2572 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2573 }
2574 } break;
2575
2576 case MSG_NOTIFY_DATA_CHANGED: {
2577 mBackupManager.dataChanged();
2578 } break;
2579 }
2580 }
2581 }
2582
Svetoslav683914b2015-01-15 14:22:26 -08002583 private final class UpgradeController {
Mark Rathjend891f012017-01-19 04:10:37 +00002584 private static final int SETTINGS_VERSION = 137;
Svetoslav683914b2015-01-15 14:22:26 -08002585
2586 private final int mUserId;
2587
2588 public UpgradeController(int userId) {
2589 mUserId = userId;
2590 }
2591
2592 public void upgradeIfNeededLocked() {
2593 // The version of all settings for a user is the same (all users have secure).
2594 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002595 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002596
2597 // Try an update from the current state.
2598 final int oldVersion = secureSettings.getVersionLocked();
2599 final int newVersion = SETTINGS_VERSION;
2600
Svet Ganovc9755bc2015-03-28 13:21:22 -07002601 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002602 if (oldVersion == newVersion) {
2603 return;
2604 }
2605
2606 // Try to upgrade.
2607 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2608
2609 // If upgrade failed start from scratch and upgrade.
2610 if (curVersion != newVersion) {
2611 // Drop state we have for this user.
2612 removeUserStateLocked(mUserId, true);
2613
2614 // Recreate the database.
2615 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2616 SQLiteDatabase database = dbHelper.getWritableDatabase();
2617 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2618
2619 // Migrate the settings for this user.
2620 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2621
2622 // Now upgrade should work fine.
2623 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002624
2625 // Make a note what happened, so we don't wonder why data was lost
2626 String reason = "Settings rebuilt! Current version: "
2627 + curVersion + " while expected: " + newVersion;
2628 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002629 Settings.Global.DATABASE_DOWNGRADE_REASON,
2630 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002631 }
2632
2633 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002634 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002635 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002636 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002637 globalSettings.setVersionLocked(newVersion);
2638 }
2639
2640 // Set the secure settings version.
2641 secureSettings.setVersionLocked(newVersion);
2642
2643 // Set the system settings version.
2644 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002645 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002646 systemSettings.setVersionLocked(newVersion);
2647 }
2648
2649 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002650 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002651 }
2652
2653 private SettingsState getSecureSettingsLocked(int userId) {
2654 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2655 }
2656
Mark Rathjend891f012017-01-19 04:10:37 +00002657 private SettingsState getSsaidSettingsLocked(int userId) {
2658 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2659 }
2660
Svetoslav683914b2015-01-15 14:22:26 -08002661 private SettingsState getSystemSettingsLocked(int userId) {
2662 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2663 }
2664
Jeff Brown503cffc2015-03-26 18:08:51 -07002665 /**
2666 * You must perform all necessary mutations to bring the settings
2667 * for this user from the old to the new version. When you add a new
2668 * upgrade step you *must* update SETTINGS_VERSION.
2669 *
2670 * This is an example of moving a setting from secure to global.
2671 *
2672 * // v119: Example settings changes.
2673 * if (currentVersion == 118) {
2674 * if (userId == UserHandle.USER_OWNER) {
2675 * // Remove from the secure settings.
2676 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2677 * String name = "example_setting_to_move";
2678 * String value = secureSettings.getSetting(name);
2679 * secureSettings.deleteSetting(name);
2680 *
2681 * // Add to the global settings.
2682 * SettingsState globalSettings = getGlobalSettingsLocked();
2683 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2684 * }
2685 *
2686 * // Update the current version.
2687 * currentVersion = 119;
2688 * }
2689 */
Svetoslav683914b2015-01-15 14:22:26 -08002690 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2691 if (DEBUG) {
2692 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2693 + oldVersion + " to version: " + newVersion);
2694 }
2695
Jeff Brown503cffc2015-03-26 18:08:51 -07002696 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002697
John Spurlocke11ae112015-05-11 16:09:03 -04002698 // v119: Reset zen + ringer mode.
2699 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002700 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002701 final SettingsState globalSettings = getGlobalSettingsLocked();
2702 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002703 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2704 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002705 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002706 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2707 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002708 }
2709 currentVersion = 119;
2710 }
2711
Jason Monk27bbb2d2015-03-31 16:46:39 -04002712 // v120: Add double tap to wake setting.
2713 if (currentVersion == 119) {
2714 SettingsState secureSettings = getSecureSettingsLocked(userId);
2715 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2716 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002717 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002718 SettingsState.SYSTEM_PACKAGE_NAME);
2719
2720 currentVersion = 120;
2721 }
2722
Svetoslav7e0683b2015-08-03 16:02:52 -07002723 if (currentVersion == 120) {
2724 // Before 121, we used a different string encoding logic. We just bump the
2725 // version here; SettingsState knows how to handle pre-version 120 files.
2726 currentVersion = 121;
2727 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002728
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002729 if (currentVersion == 121) {
2730 // Version 122: allow OEMs to set a default payment component in resources.
2731 // Note that we only write the default if no default has been set;
2732 // if there is, we just leave the default at whatever it currently is.
2733 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2734 String defaultComponent = (getContext().getResources().getString(
2735 R.string.def_nfc_payment_component));
2736 Setting currentSetting = secureSettings.getSettingLocked(
2737 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2738 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002739 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002740 secureSettings.insertSettingLocked(
2741 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002742 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002743 }
2744 currentVersion = 122;
2745 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002746
2747 if (currentVersion == 122) {
2748 // Version 123: Adding a default value for the ability to add a user from
2749 // the lock screen.
2750 if (userId == UserHandle.USER_SYSTEM) {
2751 final SettingsState globalSettings = getGlobalSettingsLocked();
2752 Setting currentSetting = globalSettings.getSettingLocked(
2753 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002754 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002755 globalSettings.insertSettingLocked(
2756 Settings.Global.ADD_USERS_WHEN_LOCKED,
2757 getContext().getResources().getBoolean(
2758 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002759 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002760 }
2761 }
2762 currentVersion = 123;
2763 }
Bryce Leebd179282015-12-17 19:01:37 -08002764
2765 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002766 final SettingsState globalSettings = getGlobalSettingsLocked();
2767 String defaultDisabledProfiles = (getContext().getResources().getString(
2768 R.string.def_bluetooth_disabled_profiles));
2769 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002770 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002771 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002772 }
2773
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002774 if (currentVersion == 124) {
2775 // Version 124: allow OEMs to set a default value for whether IME should be
2776 // shown when a physical keyboard is connected.
2777 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2778 Setting currentSetting = secureSettings.getSettingLocked(
2779 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002780 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002781 secureSettings.insertSettingLocked(
2782 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2783 getContext().getResources().getBoolean(
2784 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002785 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002786 }
2787 currentVersion = 125;
2788 }
2789
Ruben Brunk98576cf2016-03-07 18:54:28 -08002790 if (currentVersion == 125) {
2791 // Version 125: Allow OEMs to set the default VR service.
2792 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2793
2794 Setting currentSetting = secureSettings.getSettingLocked(
2795 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002796 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002797 ArraySet<ComponentName> l =
2798 SystemConfig.getInstance().getDefaultVrComponents();
2799
2800 if (l != null && !l.isEmpty()) {
2801 StringBuilder b = new StringBuilder();
2802 boolean start = true;
2803 for (ComponentName c : l) {
2804 if (!start) {
2805 b.append(':');
2806 }
2807 b.append(c.flattenToString());
2808 start = false;
2809 }
2810 secureSettings.insertSettingLocked(
2811 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002812 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002813 }
2814
2815 }
2816 currentVersion = 126;
2817 }
2818
Daniel U02ba6122016-04-01 18:41:42 +01002819 if (currentVersion == 126) {
2820 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2821 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2822 if (mUserManager.isManagedProfile(userId)) {
2823 final SettingsState systemSecureSettings =
2824 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2825
2826 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2827 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002828 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002829 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2830 secureSettings.insertSettingLocked(
2831 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002832 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002833 SettingsState.SYSTEM_PACKAGE_NAME);
2834 }
2835
2836 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2837 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002838 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002839 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2840 secureSettings.insertSettingLocked(
2841 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002842 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002843 SettingsState.SYSTEM_PACKAGE_NAME);
2844 }
2845 }
2846 currentVersion = 127;
2847 }
2848
Steven Ngdc20ba62016-04-26 18:19:04 +01002849 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002850 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002851 currentVersion = 128;
2852 }
2853
Julia Reynolds1f721e12016-07-11 08:50:58 -04002854 if (currentVersion == 128) {
2855 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2856 // the new apps are appended to the list of already approved apps.
2857 final SettingsState systemSecureSettings =
2858 getSecureSettingsLocked(userId);
2859
2860 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2861 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2862 String defaultPolicyAccess = getContext().getResources().getString(
2863 com.android.internal.R.string.config_defaultDndAccessPackages);
2864 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2865 if (policyAccess.isNull()) {
2866 systemSecureSettings.insertSettingLocked(
2867 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002868 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002869 SettingsState.SYSTEM_PACKAGE_NAME);
2870 } else {
2871 StringBuilder currentSetting =
2872 new StringBuilder(policyAccess.getValue());
2873 currentSetting.append(":");
2874 currentSetting.append(defaultPolicyAccess);
2875 systemSecureSettings.updateSettingLocked(
2876 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002877 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002878 SettingsState.SYSTEM_PACKAGE_NAME);
2879 }
2880 }
2881
2882 currentVersion = 129;
2883 }
2884
Dan Sandler71f85e92016-07-20 13:46:05 -04002885 if (currentVersion == 129) {
2886 // default longpress timeout changed from 500 to 400. If unchanged from the old
2887 // default, update to the new default.
2888 final SettingsState systemSecureSettings =
2889 getSecureSettingsLocked(userId);
2890 final String oldValue = systemSecureSettings.getSettingLocked(
2891 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2892 if (TextUtils.equals("500", oldValue)) {
2893 systemSecureSettings.insertSettingLocked(
2894 Settings.Secure.LONG_PRESS_TIMEOUT,
2895 String.valueOf(getContext().getResources().getInteger(
2896 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002897 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04002898 }
2899 currentVersion = 130;
2900 }
2901
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002902 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07002903 // Split Ambient settings
2904 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2905 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
2906 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
2907
2908 if (dozeExplicitlyDisabled) {
2909 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002910 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002911 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002912 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002913 }
2914 currentVersion = 131;
2915 }
2916
2917 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002918 // Initialize new multi-press timeout to default value
2919 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2920 final String oldValue = systemSecureSettings.getSettingLocked(
2921 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2922 if (TextUtils.equals(null, oldValue)) {
2923 systemSecureSettings.insertSettingLocked(
2924 Settings.Secure.MULTI_PRESS_TIMEOUT,
2925 String.valueOf(getContext().getResources().getInteger(
2926 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002927 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002928 }
2929
Adrian Roos69741a22016-10-21 14:49:17 -07002930 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002931 }
2932
Adrian Roos69741a22016-10-21 14:49:17 -07002933 if (currentVersion == 132) {
2934 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01002935 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2936 String defaultSyncParentSounds = (getContext().getResources()
2937 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
2938 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002939 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
2940 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002941 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01002942 }
2943
Adrian Roos69741a22016-10-21 14:49:17 -07002944 if (currentVersion == 133) {
2945 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07002946 final SettingsState systemSettings = getSystemSettingsLocked(userId);
2947 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
2948 null) {
2949 String defaultEndButtonBehavior = Integer.toString(getContext()
2950 .getResources().getInteger(R.integer.def_end_button_behavior));
2951 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002952 defaultEndButtonBehavior, null, true,
2953 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07002954 }
Adrian Roos69741a22016-10-21 14:49:17 -07002955 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07002956 }
2957
Phil Weaver89e3ffc2016-09-19 13:51:10 -07002958 if (currentVersion == 134) {
2959 // Remove setting that specifies if magnification values should be preserved.
2960 // This setting defaulted to true and never has a UI.
2961 getSecureSettingsLocked(userId).deleteSettingLocked(
2962 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
2963 currentVersion = 135;
2964 }
2965
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002966 if (currentVersion == 135) {
2967 // Version 135: Migrating the NETWORK_SCORER_APP setting to the
2968 // NETWORK_RECOMMENDATIONS_ENABLED setting.
2969 if (userId == UserHandle.USER_SYSTEM) {
2970 final SettingsState globalSettings = getGlobalSettingsLocked();
2971 Setting currentSetting = globalSettings.getSettingLocked(
2972 Global.NETWORK_SCORER_APP);
2973 if (!currentSetting.isNull()) {
2974 // A scorer was set so enable recommendations.
2975 globalSettings.insertSettingLocked(
2976 Global.NETWORK_RECOMMENDATIONS_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002977 "1", null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002978 SettingsState.SYSTEM_PACKAGE_NAME);
2979
2980 // and clear the scorer setting since it's no longer needed.
2981 globalSettings.insertSettingLocked(
2982 Global.NETWORK_SCORER_APP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002983 null, null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08002984 SettingsState.SYSTEM_PACKAGE_NAME);
2985 }
2986 }
2987 currentVersion = 136;
2988 }
2989
Mark Rathjend891f012017-01-19 04:10:37 +00002990 if (currentVersion == 136) {
2991 // Version 136: Store legacy SSAID for all apps currently installed on the
2992 // device as first step in migrating SSAID to be unique per application.
2993
2994 final boolean isUpgrade;
2995 try {
2996 isUpgrade = mPackageManager.isUpgrade();
2997 } catch (RemoteException e) {
2998 throw new IllegalStateException("Package manager not available");
2999 }
3000 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3001 // user data or first boot on a new device should use new ssaid generation.
3002 if (isUpgrade) {
3003 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003004 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3005 userId, Settings.Secure.ANDROID_ID);
3006 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3007 || legacySsaidSetting.getValue() == null) {
3008 throw new IllegalStateException("Legacy ssaid not accessible");
3009 }
3010 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003011
3012 // Fill each uid with the legacy ssaid to be backwards compatible.
3013 final List<PackageInfo> packages;
3014 try {
3015 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3016 } catch (RemoteException e) {
3017 throw new IllegalStateException("Package manager not available");
3018 }
3019
3020 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3021 for (PackageInfo info : packages) {
3022 // Check if the UID already has an entry in the table.
3023 final String uid = Integer.toString(info.applicationInfo.uid);
3024 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3025
3026 if (ssaid.isNull() || ssaid.getValue() == null) {
3027 // Android Id doesn't exist for this package so create it.
3028 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3029 info.packageName);
3030 }
3031 }
3032 }
3033
3034 currentVersion = 137;
3035 }
3036
Dan Sandler71f85e92016-07-20 13:46:05 -04003037 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003038 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003039 + newVersion + " left it at "
3040 + currentVersion + " instead; this is probably a bug", new Throwable());
3041 if (DEBUG) {
3042 throw new RuntimeException("db upgrade error");
3043 }
3044 }
3045
Jeff Brown503cffc2015-03-26 18:08:51 -07003046 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003047
Jeff Brown503cffc2015-03-26 18:08:51 -07003048 // Return the current version.
3049 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003050 }
3051 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003052 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003053}