blob: 527631e0fb7c2b6d5d39021c51d740e81cc3649c [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() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800274 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800275 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700276 mUserManager = UserManager.get(getContext());
277 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700278 mHandlerThread = new HandlerThread(LOG_TAG,
279 Process.THREAD_PRIORITY_BACKGROUND);
280 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800281 mSettingsRegistry = new SettingsRegistry();
282 }
283 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700284 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700285 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700286 return true;
287 }
288
Svetoslav683914b2015-01-15 14:22:26 -0800289 @Override
290 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700291 final int requestingUserId = getRequestingUserId(args);
292 switch (method) {
293 case Settings.CALL_METHOD_GET_GLOBAL: {
294 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700295 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800296 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700297
298 case Settings.CALL_METHOD_GET_SECURE: {
299 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700300 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700301 }
302
303 case Settings.CALL_METHOD_GET_SYSTEM: {
304 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700305 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700306 }
307
308 case Settings.CALL_METHOD_PUT_GLOBAL: {
309 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800310 String tag = getSettingTag(args);
311 final boolean makeDefault = getSettingMakeDefault(args);
312 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700313 break;
314 }
315
316 case Settings.CALL_METHOD_PUT_SECURE: {
317 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800318 String tag = getSettingTag(args);
319 final boolean makeDefault = getSettingMakeDefault(args);
320 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700321 break;
322 }
323
324 case Settings.CALL_METHOD_PUT_SYSTEM: {
325 String value = getSettingValue(args);
326 insertSystemSetting(name, value, requestingUserId);
327 break;
328 }
329
Svetoslav Ganove080da92016-12-21 17:10:35 -0800330 case Settings.CALL_METHOD_RESET_GLOBAL: {
331 final int mode = getResetModeEnforcingPermission(args);
332 String tag = getSettingTag(args);
333 resetGlobalSetting(requestingUserId, mode, tag);
334 break;
335 }
336
337 case Settings.CALL_METHOD_RESET_SECURE: {
338 final int mode = getResetModeEnforcingPermission(args);
339 String tag = getSettingTag(args);
340 resetSecureSetting(requestingUserId, mode, tag);
341 break;
342 }
343
Svetoslav7ec28e82015-05-20 17:01:10 -0700344 default: {
345 Slog.w(LOG_TAG, "call() with invalid method: " + method);
346 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700347 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700348
Christopher Tate06efb532012-08-24 15:29:27 -0700349 return null;
350 }
351
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800352 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800353 public String getType(Uri uri) {
354 Arguments args = new Arguments(uri, null, null, true);
355 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700356 return "vnd.android.cursor.dir/" + args.table;
357 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700358 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 }
360 }
361
362 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800363 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
364 String order) {
365 if (DEBUG) {
366 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367 }
368
Svetoslav683914b2015-01-15 14:22:26 -0800369 Arguments args = new Arguments(uri, where, whereArgs, true);
370 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371
Svetoslav683914b2015-01-15 14:22:26 -0800372 // If a legacy table that is gone, done.
373 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
374 return new MatrixCursor(normalizedProjection, 0);
375 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700376
Svetoslav7ec28e82015-05-20 17:01:10 -0700377 switch (args.table) {
378 case TABLE_GLOBAL: {
379 if (args.name != null) {
380 Setting setting = getGlobalSetting(args.name);
381 return packageSettingForQuery(setting, normalizedProjection);
382 } else {
383 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700384 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700385 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700386
Svetoslav7ec28e82015-05-20 17:01:10 -0700387 case TABLE_SECURE: {
388 final int userId = UserHandle.getCallingUserId();
389 if (args.name != null) {
390 Setting setting = getSecureSetting(args.name, userId);
391 return packageSettingForQuery(setting, normalizedProjection);
392 } else {
393 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800394 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700395 }
Svetoslav683914b2015-01-15 14:22:26 -0800396
Svetoslav7ec28e82015-05-20 17:01:10 -0700397 case TABLE_SYSTEM: {
398 final int userId = UserHandle.getCallingUserId();
399 if (args.name != null) {
400 Setting setting = getSystemSetting(args.name, userId);
401 return packageSettingForQuery(setting, normalizedProjection);
402 } else {
403 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800404 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 }
Svetoslav683914b2015-01-15 14:22:26 -0800406
Svetoslav7ec28e82015-05-20 17:01:10 -0700407 default: {
408 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700409 }
410 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700411 }
412
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700413 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800414 public Uri insert(Uri uri, ContentValues values) {
415 if (DEBUG) {
416 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700417 }
418
Svetoslav683914b2015-01-15 14:22:26 -0800419 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700420
Svetoslav683914b2015-01-15 14:22:26 -0800421 // If a legacy table that is gone, done.
422 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 return null;
424 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425
Svetoslav683914b2015-01-15 14:22:26 -0800426 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700427 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800428 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700429 }
430
Svetoslav683914b2015-01-15 14:22:26 -0800431 String value = values.getAsString(Settings.Secure.VALUE);
432
Svetoslav7ec28e82015-05-20 17:01:10 -0700433 switch (table) {
434 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800435 if (insertGlobalSetting(name, value, null, false,
436 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700437 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700438 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700439 } break;
440
441 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800442 if (insertSecureSetting(name, value, null, false,
443 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700444 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
445 }
446 } break;
447
448 case TABLE_SYSTEM: {
449 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
450 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
451 }
452 } break;
453
454 default: {
455 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700456 }
457 }
458
Svetoslav683914b2015-01-15 14:22:26 -0800459 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460 }
461
462 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800463 public int bulkInsert(Uri uri, ContentValues[] allValues) {
464 if (DEBUG) {
465 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700467
Svetoslav683914b2015-01-15 14:22:26 -0800468 int insertionCount = 0;
469 final int valuesCount = allValues.length;
470 for (int i = 0; i < valuesCount; i++) {
471 ContentValues values = allValues[i];
472 if (insert(uri, values) != null) {
473 insertionCount++;
474 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700475 }
Svetoslav683914b2015-01-15 14:22:26 -0800476
477 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 }
479
480 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800481 public int delete(Uri uri, String where, String[] whereArgs) {
482 if (DEBUG) {
483 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700485
Svetoslav683914b2015-01-15 14:22:26 -0800486 Arguments args = new Arguments(uri, where, whereArgs, false);
487
488 // If a legacy table that is gone, done.
489 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
490 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700491 }
Svetoslav683914b2015-01-15 14:22:26 -0800492
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700493 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800494 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700495 }
Svetoslav683914b2015-01-15 14:22:26 -0800496
Svetoslav7ec28e82015-05-20 17:01:10 -0700497 switch (args.table) {
498 case TABLE_GLOBAL: {
499 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700500 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700501 }
Svetoslav683914b2015-01-15 14:22:26 -0800502
Svetoslav7ec28e82015-05-20 17:01:10 -0700503 case TABLE_SECURE: {
504 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700505 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 }
Svetoslav683914b2015-01-15 14:22:26 -0800507
Svetoslav7ec28e82015-05-20 17:01:10 -0700508 case TABLE_SYSTEM: {
509 final int userId = UserHandle.getCallingUserId();
510 return deleteSystemSetting(args.name, userId) ? 1 : 0;
511 }
512
513 default: {
514 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800515 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700516 }
Svetoslav683914b2015-01-15 14:22:26 -0800517 }
518
519 @Override
520 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
521 if (DEBUG) {
522 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700523 }
Svetoslav683914b2015-01-15 14:22:26 -0800524
525 Arguments args = new Arguments(uri, where, whereArgs, false);
526
527 // If a legacy table that is gone, done.
528 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
529 return 0;
530 }
531
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700532 String name = values.getAsString(Settings.Secure.NAME);
533 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800534 return 0;
535 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700536 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800537
Svetoslav7ec28e82015-05-20 17:01:10 -0700538 switch (args.table) {
539 case TABLE_GLOBAL: {
540 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800541 return updateGlobalSetting(args.name, value, null, false,
542 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700543 }
Svetoslav683914b2015-01-15 14:22:26 -0800544
Svetoslav7ec28e82015-05-20 17:01:10 -0700545 case TABLE_SECURE: {
546 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800547 return updateSecureSetting(args.name, value, null, false,
548 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700549 }
Svetoslav683914b2015-01-15 14:22:26 -0800550
Svetoslav7ec28e82015-05-20 17:01:10 -0700551 case TABLE_SYSTEM: {
552 final int userId = UserHandle.getCallingUserId();
553 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
554 }
Svetoslav683914b2015-01-15 14:22:26 -0800555
Svetoslav7ec28e82015-05-20 17:01:10 -0700556 default: {
557 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800558 }
559 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700560 }
561
562 @Override
563 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100564 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
565 if (userId != UserHandle.getCallingUserId()) {
566 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
567 "Access files from the settings of another user");
568 }
569 uri = ContentProvider.getUriWithoutUserId(uri);
570
Andre Lago3fa139c2016-08-04 13:53:44 +0100571 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700572 final String cacheName;
573 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100574 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700575 cacheName = Settings.System.RINGTONE_CACHE;
576 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100577 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700578 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
579 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100580 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700581 cacheName = Settings.System.ALARM_ALERT_CACHE;
582 } else {
583 throw new FileNotFoundException("Direct file access no longer supported; "
584 + "ringtone playback is available through android.media.Ringtone");
585 }
586
Andre Lago3fa139c2016-08-04 13:53:44 +0100587 int actualCacheOwner;
588 // Redirect cache to parent if ringtone setting is owned by profile parent
589 synchronized (mLock) {
590 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
591 cacheRingtoneSetting);
592 }
593 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700594 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
595 }
596
597 private File getRingtoneCacheDir(int userId) {
598 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
599 cacheDir.mkdir();
600 SELinux.restorecon(cacheDir);
601 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700602 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800603
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700604 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800605 synchronized (mLock) {
606 final long identity = Binder.clearCallingIdentity();
607 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700608 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800609 final int userCount = users.size();
610 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700611 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800612 }
613 } finally {
614 Binder.restoreCallingIdentity(identity);
615 }
616 }
617 }
618
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700619 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700620 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800621 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700622 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
623 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700624 if (globalSettings != null) {
625 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800626 pw.println();
627 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700628 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800629 }
630
631 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700632 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
633 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700634 if (secureSettings != null) {
635 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800636 pw.println();
637 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700638 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700639
Svetoslavb505ccc2015-02-17 12:41:04 -0800640 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700641 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
642 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700643 if (systemSettings != null) {
644 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800645 pw.println();
646 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700647 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800648 }
649
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700650 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
651 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800652
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700653 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800654
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700655 for (int i = 0; i < nameCount; i++) {
656 String name = names.get(i);
657 Setting setting = settingsState.getSettingLocked(name);
658 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
659 pw.print(" name:"); pw.print(toDumpString(name));
660 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800661 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700662 }
663 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800664 if (setting.getDefaultValue() != null) {
665 pw.print(" default:"); pw.print(setting.getDefaultValue());
666 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultSystemSet());
667 }
668 if (setting.getTag() != null) {
669 pw.print(" tag:"); pw.print(setting.getTag());
670 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800671 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700672 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800673 }
674
Svetoslav7e0683b2015-08-03 16:02:52 -0700675 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700676 if (s != null) {
677 return s;
678 }
679 return "{null}";
680 }
681
Svetoslav683914b2015-01-15 14:22:26 -0800682 private void registerBroadcastReceivers() {
683 IntentFilter userFilter = new IntentFilter();
684 userFilter.addAction(Intent.ACTION_USER_REMOVED);
685 userFilter.addAction(Intent.ACTION_USER_STOPPED);
686
687 getContext().registerReceiver(new BroadcastReceiver() {
688 @Override
689 public void onReceive(Context context, Intent intent) {
690 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700691 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800692
693 switch (intent.getAction()) {
694 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700695 synchronized (mLock) {
696 mSettingsRegistry.removeUserStateLocked(userId, true);
697 }
Svetoslav683914b2015-01-15 14:22:26 -0800698 } break;
699
700 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700701 synchronized (mLock) {
702 mSettingsRegistry.removeUserStateLocked(userId, false);
703 }
Svetoslav683914b2015-01-15 14:22:26 -0800704 } break;
705 }
706 }
707 }, userFilter);
708
709 PackageMonitor monitor = new PackageMonitor() {
710 @Override
711 public void onPackageRemoved(String packageName, int uid) {
712 synchronized (mLock) {
713 mSettingsRegistry.onPackageRemovedLocked(packageName,
714 UserHandle.getUserId(uid));
715 }
716 }
Mark Rathjend891f012017-01-19 04:10:37 +0000717
718 @Override
719 public void onUidRemoved(int uid) {
720 synchronized (mLock) {
721 mSettingsRegistry.onUidRemovedLocked(uid);
722 }
723 }
Svetoslav683914b2015-01-15 14:22:26 -0800724 };
725
726 // package changes
727 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
728 UserHandle.ALL, true);
729 }
730
Svet Ganov53a441c2016-04-19 19:38:00 -0700731 private void startWatchingUserRestrictionChanges() {
732 // TODO: The current design of settings looking different based on user restrictions
733 // should be reworked to keep them separate and system code should check the setting
734 // first followed by checking the user restriction before performing an operation.
735 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
736 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
737 Bundle prevRestrictions) -> {
738 // We are changing the settings affected by restrictions to their current
739 // value with a forced update to ensure that all cross profile dependencies
740 // are taken into account. Also make sure the settings update to.. the same
741 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800742 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
743 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700744 final long identity = Binder.clearCallingIdentity();
745 try {
746 synchronized (mLock) {
747 Setting setting = getSecureSetting(
748 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
749 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800750 setting != null ? setting.getValue() : null, null,
751 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700752 }
753 } finally {
754 Binder.restoreCallingIdentity(identity);
755 }
756 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800757 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
758 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700759 final long identity = Binder.clearCallingIdentity();
760 try {
761 synchronized (mLock) {
762 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800763 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700764 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800765 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700766 }
767 } finally {
768 Binder.restoreCallingIdentity(identity);
769 }
770 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800771 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
772 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700773 final long identity = Binder.clearCallingIdentity();
774 try {
775 synchronized (mLock) {
776 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800777 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700778 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800779 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700780 }
781 } finally {
782 Binder.restoreCallingIdentity(identity);
783 }
784 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800785 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
786 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700787 final long identity = Binder.clearCallingIdentity();
788 try {
789 synchronized (mLock) {
790 Setting enable = getGlobalSetting(
791 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800792 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700793 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800794 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700795 Setting include = getGlobalSetting(
796 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800797 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700798 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800799 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700800 }
801 } finally {
802 Binder.restoreCallingIdentity(identity);
803 }
804 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800805 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
806 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700807 final long identity = Binder.clearCallingIdentity();
808 try {
809 synchronized (mLock) {
810 Setting setting = getGlobalSetting(
811 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800812 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700813 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800814 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700815 }
816 } finally {
817 Binder.restoreCallingIdentity(identity);
818 }
819 }
820 });
821 }
822
Svetoslav7ec28e82015-05-20 17:01:10 -0700823 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800824 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700825 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800826 }
827
Svetoslav7ec28e82015-05-20 17:01:10 -0700828 synchronized (mLock) {
829 // Get the settings.
830 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800832
Chad Brubaker97bccee2017-01-05 15:51:41 -0800833 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
834 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800835
Svetoslav7ec28e82015-05-20 17:01:10 -0700836 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800837
Svetoslav7ec28e82015-05-20 17:01:10 -0700838 String[] normalizedProjection = normalizeProjection(projection);
839 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800840
Svetoslav7ec28e82015-05-20 17:01:10 -0700841 // Anyone can get the global settings, so no security checks.
842 for (int i = 0; i < nameCount; i++) {
843 String name = names.get(i);
844 Setting setting = settingsState.getSettingLocked(name);
845 appendSettingToCursor(result, setting);
846 }
847
848 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800849 }
Svetoslav683914b2015-01-15 14:22:26 -0800850 }
851
Svetoslav7ec28e82015-05-20 17:01:10 -0700852 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800853 if (DEBUG) {
854 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
855 }
856
Chad Brubaker97bccee2017-01-05 15:51:41 -0800857 // Ensure the caller can access the setting.
858 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
859
Svetoslav683914b2015-01-15 14:22:26 -0800860 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700861 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700862 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700863 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800864 }
Svetoslav683914b2015-01-15 14:22:26 -0800865 }
866
Svetoslav Ganove080da92016-12-21 17:10:35 -0800867 private boolean updateGlobalSetting(String name, String value, String tag,
868 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800869 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800870 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
871 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
872 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800873 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800874 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
875 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800876 }
877
Svetoslav Ganove080da92016-12-21 17:10:35 -0800878 private boolean insertGlobalSetting(String name, String value, String tag,
879 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800881 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
882 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
883 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700884 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800885 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
886 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 }
888
Svet Ganov53a441c2016-04-19 19:38:00 -0700889 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800890 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800891 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
892 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800893 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800894 return mutateGlobalSetting(name, null, null, false, requestingUserId,
895 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800896 }
897
Svetoslav Ganove080da92016-12-21 17:10:35 -0800898 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
899 if (DEBUG) {
900 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
901 + mode + ", " + tag + ")");
902 }
903 mutateGlobalSetting(null, null, tag, false, requestingUserId,
904 MUTATION_OPERATION_RESET, false, mode);
905 }
906
907 private boolean mutateGlobalSetting(String name, String value, String tag,
908 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
909 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800910 // Make sure the caller can change the settings - treated as secure.
911 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
912
Svetoslav683914b2015-01-15 14:22:26 -0800913 // Resolve the userId on whose behalf the call is made.
914 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
915
Makoto Onuki28da2e32015-11-20 11:30:44 -0800916 // If this is a setting that is currently restricted for this user, do not allow
917 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100919 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800920 return false;
921 }
922
923 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 synchronized (mLock) {
925 switch (operation) {
926 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800927 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
928 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
929 getCallingPackage(), 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_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700933 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
934 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700935 }
Svetoslav683914b2015-01-15 14:22:26 -0800936
Svetoslav7ec28e82015-05-20 17:01:10 -0700937 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800938 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
939 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
940 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700941 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800942
943 case MUTATION_OPERATION_RESET: {
944 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
945 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
946 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800947 }
948 }
949
950 return false;
951 }
952
Svetoslav7ec28e82015-05-20 17:01:10 -0700953 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800954 if (DEBUG) {
955 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
956 }
957
958 // Resolve the userId on whose behalf the call is made.
959 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
960
Svetoslav7ec28e82015-05-20 17:01:10 -0700961 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800962 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800963
Svetoslav7ec28e82015-05-20 17:01:10 -0700964 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800965
Svetoslav7ec28e82015-05-20 17:01:10 -0700966 String[] normalizedProjection = normalizeProjection(projection);
967 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800968
Svetoslav7ec28e82015-05-20 17:01:10 -0700969 for (int i = 0; i < nameCount; i++) {
970 String name = names.get(i);
971 // Determine the owning user as some profile settings are cloned from the parent.
972 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
973 name);
Svetoslav683914b2015-01-15 14:22:26 -0800974
Svetoslav7ec28e82015-05-20 17:01:10 -0700975 // Special case for location (sigh).
976 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700977 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700978 }
Svetoslav683914b2015-01-15 14:22:26 -0800979
Mark Rathjend891f012017-01-19 04:10:37 +0000980 // As of Android O (API 24), the SSAID is read from an app-specific entry in table
981 // SETTINGS_FILE_SSAID, unless accessed by a system process.
982 final Setting setting;
983 if (isNewSsaidSetting(name)) {
984 setting = getSsaidSettingLocked(owningUserId);
985 } else {
986 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
987 name);
988 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800990 }
991
Svetoslav7ec28e82015-05-20 17:01:10 -0700992 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800993 }
Svetoslav683914b2015-01-15 14:22:26 -0800994 }
995
Svetoslav7ec28e82015-05-20 17:01:10 -0700996 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800997 if (DEBUG) {
998 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
999 }
1000
1001 // Resolve the userId on whose behalf the call is made.
1002 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1003
Chad Brubaker97bccee2017-01-05 15:51:41 -08001004 // Ensure the caller can access the setting.
1005 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, callingUserId);
1006
Svetoslav683914b2015-01-15 14:22:26 -08001007 // Determine the owning user as some profile settings are cloned from the parent.
1008 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1009
1010 // Special case for location (sigh).
1011 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001012 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1013 owningUserId);
1014 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001015 }
1016
1017 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001018 synchronized (mLock) {
Mark Rathjend891f012017-01-19 04:10:37 +00001019 // As of Android O (API 24), the SSAID is read from an app-specific entry in table
1020 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1021 if (isNewSsaidSetting(name)) {
1022 return getSsaidSettingLocked(owningUserId);
1023 }
1024
Svet Ganov53a441c2016-04-19 19:38:00 -07001025 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 owningUserId, name);
1027 }
Svetoslav683914b2015-01-15 14:22:26 -08001028 }
1029
Mark Rathjend891f012017-01-19 04:10:37 +00001030 private boolean isNewSsaidSetting(String name) {
1031 return Settings.Secure.ANDROID_ID.equals(name)
1032 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1033 }
1034
1035 private Setting getSsaidSettingLocked(int owningUserId) {
1036 // Get uid of caller (key) used to store ssaid value
1037 String name = Integer.toString(
1038 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1039
1040 if (DEBUG) {
1041 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1042 }
1043
1044 // Retrieve the ssaid from the table if present.
1045 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1046 name);
1047
1048 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001049 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001050 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1051 }
1052
1053 return ssaid;
1054 }
1055
Svetoslav Ganove080da92016-12-21 17:10:35 -08001056 private boolean insertSecureSetting(String name, String value, String tag,
1057 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001058 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001059 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001060 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1061 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001062 }
1063
Svetoslav Ganove080da92016-12-21 17:10:35 -08001064 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1065 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001066 }
1067
Svet Ganov53a441c2016-04-19 19:38:00 -07001068 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001069 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001070 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1071 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001072 }
1073
Svetoslav Ganove080da92016-12-21 17:10:35 -08001074 return mutateSecureSetting(name, null, null, false, requestingUserId,
1075 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001076 }
1077
Svetoslav Ganove080da92016-12-21 17:10:35 -08001078 private boolean updateSecureSetting(String name, String value, String tag,
1079 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001080 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001081 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001082 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1083 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001084 }
1085
Svetoslav Ganove080da92016-12-21 17:10:35 -08001086 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1087 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001088 }
1089
Svetoslav Ganove080da92016-12-21 17:10:35 -08001090 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1091 if (DEBUG) {
1092 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1093 + mode + ", " + tag + ")");
1094 }
1095
1096 mutateSecureSetting(null, null, tag, false, requestingUserId,
1097 MUTATION_OPERATION_RESET, false, mode);
1098 }
1099
1100 private boolean mutateSecureSetting(String name, String value, String tag,
1101 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1102 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001103 // Make sure the caller can change the settings.
1104 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1105
Svetoslav683914b2015-01-15 14:22:26 -08001106 // Resolve the userId on whose behalf the call is made.
1107 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1108
Makoto Onuki28da2e32015-11-20 11:30:44 -08001109 // If this is a setting that is currently restricted for this user, do not allow
1110 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001111 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001112 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001113 return false;
1114 }
1115
1116 // Determine the owning user as some profile settings are cloned from the parent.
1117 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1118
1119 // Only the owning user can change the setting.
1120 if (owningUserId != callingUserId) {
1121 return false;
1122 }
1123
1124 // Special cases for location providers (sigh).
1125 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001126 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1127 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001128 }
1129
1130 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001131 synchronized (mLock) {
1132 switch (operation) {
1133 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001134 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001135 owningUserId, name, value, tag, makeDefault,
1136 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001137 }
Svetoslav683914b2015-01-15 14:22:26 -08001138
Svetoslav7ec28e82015-05-20 17:01:10 -07001139 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001140 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
1141 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001142 }
Svetoslav683914b2015-01-15 14:22:26 -08001143
Svetoslav7ec28e82015-05-20 17:01:10 -07001144 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001145 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001146 owningUserId, name, value, tag, makeDefault,
1147 getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -07001148 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001149
1150 case MUTATION_OPERATION_RESET: {
1151 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1152 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1153 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001154 }
1155 }
1156
1157 return false;
1158 }
1159
Svetoslav7ec28e82015-05-20 17:01:10 -07001160 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001161 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001162 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001163 }
1164
1165 // Resolve the userId on whose behalf the call is made.
1166 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1167
Svetoslav7ec28e82015-05-20 17:01:10 -07001168 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001169 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001170
Svetoslav7ec28e82015-05-20 17:01:10 -07001171 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001172
Svetoslav7ec28e82015-05-20 17:01:10 -07001173 String[] normalizedProjection = normalizeProjection(projection);
1174 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001175
Svetoslav7ec28e82015-05-20 17:01:10 -07001176 for (int i = 0; i < nameCount; i++) {
1177 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001178
Svetoslav7ec28e82015-05-20 17:01:10 -07001179 // Determine the owning user as some profile settings are cloned from the parent.
1180 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1181 name);
Svetoslav683914b2015-01-15 14:22:26 -08001182
Svetoslav7ec28e82015-05-20 17:01:10 -07001183 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001184 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001185 appendSettingToCursor(result, setting);
1186 }
1187
1188 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001189 }
Svetoslav683914b2015-01-15 14:22:26 -08001190 }
1191
Svetoslav7ec28e82015-05-20 17:01:10 -07001192 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001193 if (DEBUG) {
1194 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1195 }
1196
1197 // Resolve the userId on whose behalf the call is made.
1198 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1199
Chad Brubaker97bccee2017-01-05 15:51:41 -08001200 // Ensure the caller can access the setting.
1201 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, callingUserId);
1202
Svetoslav683914b2015-01-15 14:22:26 -08001203 // Determine the owning user as some profile settings are cloned from the parent.
1204 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1205
1206 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001208 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001209 }
Svetoslav683914b2015-01-15 14:22:26 -08001210 }
1211
Svetoslav7ec28e82015-05-20 17:01:10 -07001212 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001213 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001214 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001215 + requestingUserId + ")");
1216 }
1217
Svetoslav7ec28e82015-05-20 17:01:10 -07001218 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001219 }
1220
Svetoslav7ec28e82015-05-20 17:01:10 -07001221 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001222 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001223 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001224 }
1225
Svetoslav7ec28e82015-05-20 17:01:10 -07001226 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001227 }
1228
Svetoslav7ec28e82015-05-20 17:01:10 -07001229 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001230 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001231 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001232 + requestingUserId + ")");
1233 }
1234
Svetoslav7ec28e82015-05-20 17:01:10 -07001235 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001236 }
1237
Svetoslav7ec28e82015-05-20 17:01:10 -07001238 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001239 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001240 if (!hasWriteSecureSettingsPermission()) {
1241 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1242 // operation is allowed for the calling package through appops.
1243 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1244 Binder.getCallingUid(), getCallingPackage(), true)) {
1245 return false;
1246 }
Svetoslav683914b2015-01-15 14:22:26 -08001247 }
1248
Svetoslav683914b2015-01-15 14:22:26 -08001249 // Resolve the userId on whose behalf the call is made.
1250 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1251
Svetoslavd8d25e02015-11-20 13:09:26 -08001252 // Enforce what the calling package can mutate the system settings.
1253 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1254
Svetoslav683914b2015-01-15 14:22:26 -08001255 // Determine the owning user as some profile settings are cloned from the parent.
1256 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1257
1258 // Only the owning user id can change the setting.
1259 if (owningUserId != callingUserId) {
1260 return false;
1261 }
1262
Jeff Sharkey413573a2016-02-22 17:52:45 -07001263 // Invalidate any relevant cache files
1264 String cacheName = null;
1265 if (Settings.System.RINGTONE.equals(name)) {
1266 cacheName = Settings.System.RINGTONE_CACHE;
1267 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1268 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1269 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1270 cacheName = Settings.System.ALARM_ALERT_CACHE;
1271 }
1272 if (cacheName != null) {
1273 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001274 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001275 cacheFile.delete();
1276 }
1277
Svetoslav683914b2015-01-15 14:22:26 -08001278 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001279 synchronized (mLock) {
1280 switch (operation) {
1281 case MUTATION_OPERATION_INSERT: {
1282 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001283 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001284 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001285 }
1286
1287 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001288 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1289 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001290 }
1291
1292 case MUTATION_OPERATION_UPDATE: {
1293 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001294 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001295 owningUserId, name, value, null, false, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 }
Svetoslav683914b2015-01-15 14:22:26 -08001297 }
1298
Svetoslav7ec28e82015-05-20 17:01:10 -07001299 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001300 }
Svetoslav683914b2015-01-15 14:22:26 -08001301 }
1302
Billy Lau6ad2d662015-07-18 00:26:58 +01001303 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001304 // Write secure settings is a more protected permission. If caller has it we are good.
1305 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1306 == PackageManager.PERMISSION_GRANTED) {
1307 return true;
1308 }
1309
Svetoslavf41334b2015-06-23 12:06:03 -07001310 return false;
1311 }
1312
Svetoslav683914b2015-01-15 14:22:26 -08001313 private void validateSystemSettingValue(String name, String value) {
1314 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1315 if (validator != null && !validator.validate(value)) {
1316 throw new IllegalArgumentException("Invalid value: " + value
1317 + " for setting: " + name);
1318 }
1319 }
1320
1321 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1322 int owningUserId) {
1323 // Optimization - location providers are restricted only for managed profiles.
1324 if (callingUserId == owningUserId) {
1325 return false;
1326 }
1327 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1328 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1329 new UserHandle(callingUserId))) {
1330 return true;
1331 }
1332 return false;
1333 }
1334
Makoto Onuki28da2e32015-11-20 11:30:44 -08001335 /**
1336 * Checks whether changing a setting to a value is prohibited by the corresponding user
1337 * restriction.
1338 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001339 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1340 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001341 *
1342 * @return true if the change is prohibited, false if the change is allowed.
1343 */
1344 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001345 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001346 String restriction;
1347 switch (setting) {
1348 case Settings.Secure.LOCATION_MODE:
1349 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1350 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1351 // here normally, but we still protect it here from a direct provider write.
1352 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1353 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1354 break;
1355
1356 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1357 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1358 // a provider, which should be allowed even if the user restriction is set.
1359 if (value != null && value.startsWith("-")) return false;
1360 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1361 break;
1362
1363 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1364 if ("0".equals(value)) return false;
1365 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1366 break;
1367
1368 case Settings.Global.ADB_ENABLED:
1369 if ("0".equals(value)) return false;
1370 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1371 break;
1372
1373 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1374 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1375 if ("1".equals(value)) return false;
1376 restriction = UserManager.ENSURE_VERIFY_APPS;
1377 break;
1378
1379 case Settings.Global.PREFERRED_NETWORK_MODE:
1380 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1381 break;
1382
Victor Chang9c7b7062016-07-12 23:47:29 +01001383 case Settings.Secure.ALWAYS_ON_VPN_APP:
1384 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1385 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001386 final int appId = UserHandle.getAppId(callingUid);
1387 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001388 return false;
1389 }
1390 restriction = UserManager.DISALLOW_CONFIG_VPN;
1391 break;
1392
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001393 case Settings.Global.SAFE_BOOT_DISALLOWED:
1394 if ("1".equals(value)) return false;
1395 restriction = UserManager.DISALLOW_SAFE_BOOT;
1396 break;
1397
Makoto Onuki28da2e32015-11-20 11:30:44 -08001398 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001399 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001400 if ("0".equals(value)) return false;
1401 restriction = UserManager.DISALLOW_DATA_ROAMING;
1402 break;
1403 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001404 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001405 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001406
1407 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001408 }
1409
1410 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1411 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1412 }
1413
1414 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001415 final int parentId;
1416 // Resolves dependency if setting has a dependency and the calling user has a parent
1417 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1418 && (parentId = getGroupParentLocked(userId)) != userId) {
1419 // The setting has a dependency and the profile has a parent
1420 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001421 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1422 final long token = Binder.clearCallingIdentity();
1423 try {
1424 Setting settingObj = getSecureSetting(dependency, userId);
1425 if (settingObj != null && settingObj.getValue().equals("1")) {
1426 return parentId;
1427 }
1428 } finally {
1429 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001430 }
1431 }
Svetoslav683914b2015-01-15 14:22:26 -08001432 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1433 }
1434
1435 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1436 final int parentId = getGroupParentLocked(userId);
1437 if (parentId != userId && keys.contains(name)) {
1438 return parentId;
1439 }
1440 return userId;
1441 }
1442
Svetoslavf41334b2015-06-23 12:06:03 -07001443 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001444 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001445 // System/root/shell can mutate whatever secure settings they want.
1446 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001447 final int appId = UserHandle.getAppId(callingUid);
1448 if (appId == android.os.Process.SYSTEM_UID
1449 || appId == Process.SHELL_UID
1450 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001451 return;
1452 }
1453
1454 switch (operation) {
1455 case MUTATION_OPERATION_INSERT:
1456 // Insert updates.
1457 case MUTATION_OPERATION_UPDATE: {
1458 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1459 return;
1460 }
1461
1462 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001463 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001464
1465 // Privileged apps can do whatever they want.
1466 if ((packageInfo.applicationInfo.privateFlags
1467 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1468 return;
1469 }
1470
1471 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1472 packageInfo.applicationInfo.targetSdkVersion, name);
1473 } break;
1474
1475 case MUTATION_OPERATION_DELETE: {
1476 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1477 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1478 throw new IllegalArgumentException("You cannot delete system defined"
1479 + " secure settings.");
1480 }
1481
1482 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001483 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001484
1485 // Privileged apps can do whatever they want.
1486 if ((packageInfo.applicationInfo.privateFlags &
1487 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1488 return;
1489 }
1490
1491 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1492 packageInfo.applicationInfo.targetSdkVersion, name);
1493 } break;
1494 }
1495 }
1496
Chad Brubaker97bccee2017-01-05 15:51:41 -08001497 private Set<String> getEphemeralAccessibleSettings(int settingsType) {
1498 switch (settingsType) {
1499 case SETTINGS_TYPE_GLOBAL:
1500 return Settings.Global.EPHEMERAL_SETTINGS;
1501 case SETTINGS_TYPE_SECURE:
1502 return Settings.Secure.EPHEMERAL_SETTINGS;
1503 case SETTINGS_TYPE_SYSTEM:
1504 return Settings.System.EPHEMERAL_SETTINGS;
1505 default:
1506 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1507 }
1508 }
1509
1510 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
1511 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
1512 if (ai.isEphemeralApp()) {
1513 return new ArrayList<String>(getEphemeralAccessibleSettings(settingsType));
1514 } else {
1515 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1516 }
1517 }
1518
1519 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1520 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1521 return;
1522 }
1523 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
1524 if (!ai.isEphemeralApp()) {
1525 return;
1526 }
1527 if (!getEphemeralAccessibleSettings(settingsType).contains(settingName)) {
1528 throw new SecurityException("Setting " + settingName + " is not accessible from"
1529 + " ephemeral package " + getCallingPackage());
1530 }
1531 }
1532
1533 private ApplicationInfo getCallingApplicationInfoOrThrow(int userId) {
1534 ApplicationInfo ai = null;
1535 try {
1536 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0 , userId);
1537 } catch (RemoteException ignored) {
1538 }
1539 if (ai == null) {
1540 throw new IllegalStateException("Failed to lookup info for package "
1541 + getCallingPackage());
1542 }
1543 return ai;
1544 }
1545
Xiaohui Chen43765b72015-08-31 10:57:33 -07001546 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001547 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001548 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1549 getCallingPackage(), 0, userId);
1550 if (packageInfo != null) {
1551 return packageInfo;
1552 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001553 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001554 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001555 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001556 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001557 }
1558
1559 private int getGroupParentLocked(int userId) {
1560 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001561 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001562 return userId;
1563 }
1564 // We are in the same process with the user manager and the returned
1565 // user info is a cached instance, so just look up instead of cache.
1566 final long identity = Binder.clearCallingIdentity();
1567 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001568 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001569 UserInfo userInfo = mUserManager.getProfileParent(userId);
1570 return (userInfo != null) ? userInfo.id : userId;
1571 } finally {
1572 Binder.restoreCallingIdentity(identity);
1573 }
1574 }
1575
Svetoslav683914b2015-01-15 14:22:26 -08001576 private void enforceWritePermission(String permission) {
1577 if (getContext().checkCallingOrSelfPermission(permission)
1578 != PackageManager.PERMISSION_GRANTED) {
1579 throw new SecurityException("Permission denial: writing to settings requires:"
1580 + permission);
1581 }
1582 }
1583
1584 /*
1585 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1586 * This setting contains a list of the currently enabled location providers.
1587 * But helper functions in android.providers.Settings can enable or disable
1588 * a single provider by using a "+" or "-" prefix before the provider name.
1589 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001590 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1591 * is set, the said method will only allow values with the "-" prefix.
1592 *
Svetoslav683914b2015-01-15 14:22:26 -08001593 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001594 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001595 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1596 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001597 if (TextUtils.isEmpty(value)) {
1598 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001599 }
1600
Svetoslav683914b2015-01-15 14:22:26 -08001601 final char prefix = value.charAt(0);
1602 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001603 if (forceNotify) {
1604 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1605 mSettingsRegistry.notifyForSettingsChange(key,
1606 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1607 }
Svetoslav683914b2015-01-15 14:22:26 -08001608 return false;
1609 }
1610
1611 // skip prefix
1612 value = value.substring(1);
1613
Svetoslav7ec28e82015-05-20 17:01:10 -07001614 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001615 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001616 if (settingValue == null) {
1617 return false;
1618 }
Svetoslav683914b2015-01-15 14:22:26 -08001619
1620 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1621
1622 int index = oldProviders.indexOf(value);
1623 int end = index + value.length();
1624
1625 // check for commas to avoid matching on partial string
1626 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1627 index = -1;
1628 }
1629
1630 // check for commas to avoid matching on partial string
1631 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1632 index = -1;
1633 }
1634
1635 String newProviders;
1636
1637 if (prefix == '+' && index < 0) {
1638 // append the provider to the list if not present
1639 if (oldProviders.length() == 0) {
1640 newProviders = value;
1641 } else {
1642 newProviders = oldProviders + ',' + value;
1643 }
1644 } else if (prefix == '-' && index >= 0) {
1645 // remove the provider from the list if present
1646 // remove leading or trailing comma
1647 if (index > 0) {
1648 index--;
1649 } else if (end < oldProviders.length()) {
1650 end++;
1651 }
1652
1653 newProviders = oldProviders.substring(0, index);
1654 if (end < oldProviders.length()) {
1655 newProviders += oldProviders.substring(end);
1656 }
1657 } else {
1658 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001659 if (forceNotify) {
1660 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1661 mSettingsRegistry.notifyForSettingsChange(key,
1662 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1663 }
Svetoslav683914b2015-01-15 14:22:26 -08001664 return false;
1665 }
1666
Svet Ganov53a441c2016-04-19 19:38:00 -07001667 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001668 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001669 tag, makeDefault, getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001670 }
1671
Svetoslav683914b2015-01-15 14:22:26 -08001672 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1673 int targetSdkVersion, String name) {
1674 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1675 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1676 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1677 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1678 + " This will soon become an error.");
1679 } else {
1680 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1681 + " This will soon become an error.");
1682 }
1683 } else {
1684 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1685 throw new IllegalArgumentException("You cannot change private secure settings.");
1686 } else {
1687 throw new IllegalArgumentException("You cannot keep your settings in"
1688 + " the secure settings.");
1689 }
1690 }
1691 }
1692
1693 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1694 if (requestingUserId == UserHandle.getCallingUserId()) {
1695 return requestingUserId;
1696 }
1697 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1698 Binder.getCallingUid(), requestingUserId, false, true,
1699 "get/set setting for user", null);
1700 }
1701
Svet Ganov53a441c2016-04-19 19:38:00 -07001702 private Bundle packageValueForCallResult(Setting setting,
1703 boolean trackingGeneration) {
1704 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001705 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001706 return NULL_SETTING_BUNDLE;
1707 }
1708 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001709 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001710 Bundle result = new Bundle();
1711 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001712 !setting.isNull() ? setting.getValue() : null);
1713 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001714 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001715 }
1716
1717 private static int getRequestingUserId(Bundle args) {
1718 final int callingUserId = UserHandle.getCallingUserId();
1719 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1720 : callingUserId;
1721 }
1722
Svet Ganov53a441c2016-04-19 19:38:00 -07001723 private boolean isTrackingGeneration(Bundle args) {
1724 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1725 }
1726
Svetoslav683914b2015-01-15 14:22:26 -08001727 private static String getSettingValue(Bundle args) {
1728 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1729 }
1730
Svetoslav Ganove080da92016-12-21 17:10:35 -08001731 private static String getSettingTag(Bundle args) {
1732 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1733 }
1734
1735 private static boolean getSettingMakeDefault(Bundle args) {
1736 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1737 }
1738
1739 private static int getResetModeEnforcingPermission(Bundle args) {
1740 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1741 switch (mode) {
1742 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1743 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1744 throw new SecurityException("Only system, shell/root on a "
1745 + "debuggable build can reset to untrusted defaults");
1746 }
1747 return mode;
1748 }
1749 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1750 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1751 throw new SecurityException("Only system, shell/root on a "
1752 + "debuggable build can reset untrusted changes");
1753 }
1754 return mode;
1755 }
1756 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1757 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1758 throw new SecurityException("Only system, shell/root on a "
1759 + "debuggable build can reset to trusted defaults");
1760 }
1761 return mode;
1762 }
1763 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1764 return mode;
1765 }
1766 }
1767 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1768 }
1769
1770 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1771 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1772 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1773 && (appId == SHELL_UID || appId == ROOT_UID));
1774 }
1775
Svetoslav683914b2015-01-15 14:22:26 -08001776 private static String getValidTableOrThrow(Uri uri) {
1777 if (uri.getPathSegments().size() > 0) {
1778 String table = uri.getPathSegments().get(0);
1779 if (DatabaseHelper.isValidTable(table)) {
1780 return table;
1781 }
1782 throw new IllegalArgumentException("Bad root path: " + table);
1783 }
1784 throw new IllegalArgumentException("Invalid URI:" + uri);
1785 }
1786
1787 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001788 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001789 return new MatrixCursor(projection, 0);
1790 }
1791 MatrixCursor cursor = new MatrixCursor(projection, 1);
1792 appendSettingToCursor(cursor, setting);
1793 return cursor;
1794 }
1795
1796 private static String[] normalizeProjection(String[] projection) {
1797 if (projection == null) {
1798 return ALL_COLUMNS;
1799 }
1800
1801 final int columnCount = projection.length;
1802 for (int i = 0; i < columnCount; i++) {
1803 String column = projection[i];
1804 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1805 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001806 }
1807 }
1808
Svetoslav683914b2015-01-15 14:22:26 -08001809 return projection;
1810 }
1811
1812 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001813 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001814 return;
1815 }
Svetoslav683914b2015-01-15 14:22:26 -08001816 final int columnCount = cursor.getColumnCount();
1817
1818 String[] values = new String[columnCount];
1819
1820 for (int i = 0; i < columnCount; i++) {
1821 String column = cursor.getColumnName(i);
1822
1823 switch (column) {
1824 case Settings.NameValueTable._ID: {
1825 values[i] = setting.getId();
1826 } break;
1827
1828 case Settings.NameValueTable.NAME: {
1829 values[i] = setting.getName();
1830 } break;
1831
1832 case Settings.NameValueTable.VALUE: {
1833 values[i] = setting.getValue();
1834 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001835 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001836 }
1837
Svetoslav683914b2015-01-15 14:22:26 -08001838 cursor.addRow(values);
1839 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001840
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001841 private static boolean isKeyValid(String key) {
1842 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1843 }
1844
Svetoslav683914b2015-01-15 14:22:26 -08001845 private static final class Arguments {
1846 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1847 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1848
1849 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1850 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1851
1852 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1853 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1854
1855 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1856 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1857
1858 public final String table;
1859 public final String name;
1860
1861 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1862 final int segmentSize = uri.getPathSegments().size();
1863 switch (segmentSize) {
1864 case 1: {
1865 if (where != null
1866 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1867 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1868 && whereArgs.length == 1) {
1869 name = whereArgs[0];
1870 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001871 return;
Svetoslav683914b2015-01-15 14:22:26 -08001872 } else if (where != null
1873 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1874 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1875 final int startIndex = Math.max(where.indexOf("'"),
1876 where.indexOf("\"")) + 1;
1877 final int endIndex = Math.max(where.lastIndexOf("'"),
1878 where.lastIndexOf("\""));
1879 name = where.substring(startIndex, endIndex);
1880 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001881 return;
Svetoslav683914b2015-01-15 14:22:26 -08001882 } else if (supportAll && where == null && whereArgs == null) {
1883 name = null;
1884 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001885 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001886 }
Svetoslav683914b2015-01-15 14:22:26 -08001887 } break;
1888
Svetoslav28494652015-02-12 14:11:42 -08001889 case 2: {
1890 if (where == null && whereArgs == null) {
1891 name = uri.getPathSegments().get(1);
1892 table = computeTableForSetting(uri, name);
1893 return;
1894 }
1895 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001896 }
Svetoslav28494652015-02-12 14:11:42 -08001897
1898 EventLogTags.writeUnsupportedSettingsQuery(
1899 uri.toSafeString(), where, Arrays.toString(whereArgs));
1900 String message = String.format( "Supported SQL:\n"
1901 + " uri content://some_table/some_property with null where and where args\n"
1902 + " uri content://some_table with query name=? and single name as arg\n"
1903 + " uri content://some_table with query name=some_name and null args\n"
1904 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1905 Arrays.toString(whereArgs));
1906 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001907 }
1908
Svetoslav28494652015-02-12 14:11:42 -08001909 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001910 String table = getValidTableOrThrow(uri);
1911
1912 if (name != null) {
1913 if (sSystemMovedToSecureSettings.contains(name)) {
1914 table = TABLE_SECURE;
1915 }
1916
1917 if (sSystemMovedToGlobalSettings.contains(name)) {
1918 table = TABLE_GLOBAL;
1919 }
1920
1921 if (sSecureMovedToGlobalSettings.contains(name)) {
1922 table = TABLE_GLOBAL;
1923 }
1924
1925 if (sGlobalMovedToSecureSettings.contains(name)) {
1926 table = TABLE_SECURE;
1927 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001928 }
Svetoslav683914b2015-01-15 14:22:26 -08001929
1930 return table;
1931 }
1932 }
1933
1934 final class SettingsRegistry {
1935 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1936
Svetoslav683914b2015-01-15 14:22:26 -08001937 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1938 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1939 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00001940 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
1941
1942 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08001943
1944 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1945
Svet Ganov53a441c2016-04-19 19:38:00 -07001946 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001947
Svetoslav7e0683b2015-08-03 16:02:52 -07001948 private final Handler mHandler;
1949
Svet Ganov53a441c2016-04-19 19:38:00 -07001950 private final BackupManager mBackupManager;
1951
Svetoslav683914b2015-01-15 14:22:26 -08001952 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001953 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001954 mGenerationRegistry = new GenerationRegistry(mLock);
1955 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001956 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00001957 syncSsaidTableOnStart();
1958 }
1959
1960 private void generateUserKeyLocked(int userId) {
1961 // Generate a random key for each user used for creating a new ssaid.
1962 final byte[] keyBytes = new byte[16];
1963 final SecureRandom rand = new SecureRandom();
1964 rand.nextBytes(keyBytes);
1965
1966 // Convert to string for storage in settings table.
1967 final String userKey = ByteStringUtils.toString(keyBytes);
1968
1969 // Store the key in the ssaid table.
1970 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
1971 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
1972 true, SettingsState.SYSTEM_PACKAGE_NAME);
1973
1974 if (!success) {
1975 throw new IllegalStateException("Ssaid settings not accessible");
1976 }
1977 }
1978
1979 public Setting generateSsaidLocked(String packageName, int userId) {
1980 final PackageInfo packageInfo;
1981 try {
1982 packageInfo = mPackageManager.getPackageInfo(packageName,
1983 PackageManager.GET_SIGNATURES, userId);
1984 } catch (RemoteException e) {
1985 throw new IllegalStateException("Package info doesn't exist");
1986 }
1987
1988 // Read the user's key from the ssaid table.
1989 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08001990 if (userKeySetting == null || userKeySetting.isNull()
1991 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001992 // Lazy initialize and store the user key.
1993 generateUserKeyLocked(userId);
1994 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08001995 if (userKeySetting == null || userKeySetting.isNull()
1996 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001997 throw new IllegalStateException("User key not accessible");
1998 }
1999 }
2000 final String userKey = userKeySetting.getValue();
2001
2002 // Convert the user's key back to a byte array.
2003 final byte[] keyBytes = ByteStringUtils.toByteArray(userKey);
2004 if (keyBytes == null || keyBytes.length != 16) {
2005 throw new IllegalStateException("User key invalid");
2006 }
2007
2008 final MessageDigest md;
2009 try {
2010 // Hash package name and signature.
2011 md = MessageDigest.getInstance("SHA-256");
2012 } catch (NoSuchAlgorithmException e) {
2013 throw new IllegalStateException("HmacSHA256 is not available");
2014 }
2015 md.update(keyBytes);
2016 md.update(packageInfo.packageName.getBytes(StandardCharsets.UTF_8));
2017 md.update(packageInfo.signatures[0].toByteArray());
2018
2019 // Convert result to a string for storage in settings table. Only want first 64 bits.
2020 final String ssaid = ByteStringUtils.toString(md.digest()).substring(0, 16)
2021 .toLowerCase();
2022
2023 // Save the ssaid in the ssaid table.
2024 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2025 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2026 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2027 packageName);
2028
2029 if (!success) {
2030 throw new IllegalStateException("Ssaid settings not accessible");
2031 }
2032
2033 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2034 }
2035
2036 public void syncSsaidTableOnStart() {
2037 synchronized (mLock) {
2038 // Verify that each user's packages and ssaid's are in sync.
2039 for (UserInfo user : mUserManager.getUsers(true)) {
2040 // Get all uids for the user's packages.
2041 final List<PackageInfo> packages;
2042 try {
2043 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2044 } catch (RemoteException e) {
2045 throw new IllegalStateException("Package manager not available");
2046 }
2047 final Set<String> appUids = new HashSet<>();
2048 for (PackageInfo info : packages) {
2049 appUids.add(Integer.toString(info.applicationInfo.uid));
2050 }
2051
2052 // Get all uids currently stored in the user's ssaid table.
2053 final Set<String> ssaidUids = new HashSet<>(
2054 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2055 ssaidUids.remove(SSAID_USER_KEY);
2056
2057 // Perform a set difference for the appUids and ssaidUids.
2058 ssaidUids.removeAll(appUids);
2059
2060 // If there are ssaidUids left over they need to be removed from the table.
2061 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2062 user.id);
2063 for (String uid : ssaidUids) {
2064 ssaidSettings.deleteSettingLocked(uid);
2065 }
2066 }
2067 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002068 }
2069
Svetoslav683914b2015-01-15 14:22:26 -08002070 public List<String> getSettingsNamesLocked(int type, int userId) {
2071 final int key = makeKey(type, userId);
2072 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002073 if (settingsState == null) {
2074 return new ArrayList<String>();
2075 }
Svetoslav683914b2015-01-15 14:22:26 -08002076 return settingsState.getSettingNamesLocked();
2077 }
2078
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002079 public SparseBooleanArray getKnownUsersLocked() {
2080 SparseBooleanArray users = new SparseBooleanArray();
2081 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2082 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2083 }
2084 return users;
2085 }
2086
Svetoslav683914b2015-01-15 14:22:26 -08002087 public SettingsState getSettingsLocked(int type, int userId) {
2088 final int key = makeKey(type, userId);
2089 return peekSettingsStateLocked(key);
2090 }
2091
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002092 public boolean ensureSettingsForUserLocked(int userId) {
2093 // First make sure this user actually exists.
2094 if (mUserManager.getUserInfo(userId) == null) {
2095 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2096 return false;
2097 }
2098
Svetoslav683914b2015-01-15 14:22:26 -08002099 // Migrate the setting for this user if needed.
2100 migrateLegacySettingsForUserIfNeededLocked(userId);
2101
2102 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002103 if (userId == UserHandle.USER_SYSTEM) {
2104 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002105 ensureSettingsStateLocked(globalKey);
2106 }
2107
2108 // Ensure secure settings loaded.
2109 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2110 ensureSettingsStateLocked(secureKey);
2111
2112 // Make sure the secure settings have an Android id set.
2113 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2114 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2115
2116 // Ensure system settings loaded.
2117 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2118 ensureSettingsStateLocked(systemKey);
2119
Mark Rathjend891f012017-01-19 04:10:37 +00002120 // Ensure secure settings loaded.
2121 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2122 ensureSettingsStateLocked(ssaidKey);
2123
Svetoslav683914b2015-01-15 14:22:26 -08002124 // Upgrade the settings to the latest version.
2125 UpgradeController upgrader = new UpgradeController(userId);
2126 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002127 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002128 }
2129
2130 private void ensureSettingsStateLocked(int key) {
2131 if (mSettingsStates.get(key) == null) {
2132 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002133 SettingsState settingsState = new SettingsState(getContext(), mLock,
2134 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002135 mSettingsStates.put(key, settingsState);
2136 }
2137 }
2138
2139 public void removeUserStateLocked(int userId, boolean permanently) {
2140 // We always keep the global settings in memory.
2141
2142 // Nuke system settings.
2143 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2144 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2145 if (systemSettingsState != null) {
2146 if (permanently) {
2147 mSettingsStates.remove(systemKey);
2148 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002149 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002150 systemSettingsState.destroyLocked(new Runnable() {
2151 @Override
2152 public void run() {
2153 mSettingsStates.remove(systemKey);
2154 }
2155 });
2156 }
2157 }
2158
2159 // Nuke secure settings.
2160 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2161 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2162 if (secureSettingsState != null) {
2163 if (permanently) {
2164 mSettingsStates.remove(secureKey);
2165 secureSettingsState.destroyLocked(null);
2166 } else {
2167 secureSettingsState.destroyLocked(new Runnable() {
2168 @Override
2169 public void run() {
2170 mSettingsStates.remove(secureKey);
2171 }
2172 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002173 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002174 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002175
Mark Rathjend891f012017-01-19 04:10:37 +00002176 // Nuke ssaid settings.
2177 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2178 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2179 if (ssaidSettingsState != null) {
2180 if (permanently) {
2181 mSettingsStates.remove(ssaidKey);
2182 ssaidSettingsState.destroyLocked(null);
2183 } else {
2184 ssaidSettingsState.destroyLocked(new Runnable() {
2185 @Override
2186 public void run() {
2187 mSettingsStates.remove(ssaidKey);
2188 }
2189 });
2190 }
2191 }
2192
Svet Ganov53a441c2016-04-19 19:38:00 -07002193 // Nuke generation tracking data
2194 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002195 }
2196
Svetoslav683914b2015-01-15 14:22:26 -08002197 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002198 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002199 final int key = makeKey(type, userId);
2200
Svetoslav Ganove080da92016-12-21 17:10:35 -08002201 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002202 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002203 if (settingsState != null) {
2204 success = settingsState.insertSettingLocked(name, value,
2205 tag, makeDefault, packageName);
2206 }
Svetoslav683914b2015-01-15 14:22:26 -08002207
Svet Ganov53a441c2016-04-19 19:38:00 -07002208 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002209 notifyForSettingsChange(key, name);
2210 }
2211 return success;
2212 }
2213
Svet Ganov53a441c2016-04-19 19:38:00 -07002214 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002215 final int key = makeKey(type, userId);
2216
Svetoslav Ganove080da92016-12-21 17:10:35 -08002217 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002218 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002219 if (settingsState != null) {
2220 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002221 }
Svetoslav683914b2015-01-15 14:22:26 -08002222
Svet Ganov53a441c2016-04-19 19:38:00 -07002223 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002224 notifyForSettingsChange(key, name);
2225 }
2226 return success;
2227 }
2228
2229 public Setting getSettingLocked(int type, int userId, String name) {
2230 final int key = makeKey(type, userId);
2231
2232 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002233 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002234 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002235 }
Mark Rathjend891f012017-01-19 04:10:37 +00002236
2237 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002238 return settingsState.getSettingLocked(name);
2239 }
2240
2241 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002242 String tag, boolean makeDefault, String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002243 final int key = makeKey(type, userId);
2244
Svetoslav Ganove080da92016-12-21 17:10:35 -08002245 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002246 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002247 if (settingsState != null) {
2248 success = settingsState.updateSettingLocked(name, value, tag,
2249 makeDefault, packageName);
2250 }
Svetoslav683914b2015-01-15 14:22:26 -08002251
Svet Ganov53a441c2016-04-19 19:38:00 -07002252 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002253 notifyForSettingsChange(key, name);
2254 }
2255
2256 return success;
2257 }
2258
Svetoslav Ganove080da92016-12-21 17:10:35 -08002259 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2260 String tag) {
2261 final int key = makeKey(type, userId);
2262 SettingsState settingsState = peekSettingsStateLocked(key);
2263 if (settingsState == null) {
2264 return;
2265 }
2266
2267 switch (mode) {
2268 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2269 for (String name : settingsState.getSettingNamesLocked()) {
2270 Setting setting = settingsState.getSettingLocked(name);
2271 if (packageName.equals(setting.getPackageName())) {
2272 if (tag != null && !tag.equals(setting.getTag())) {
2273 continue;
2274 }
2275 if (settingsState.resetSettingLocked(name, packageName)) {
2276 notifyForSettingsChange(key, name);
2277 }
2278 }
2279 }
2280 } break;
2281
2282 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2283 for (String name : settingsState.getSettingNamesLocked()) {
2284 Setting setting = settingsState.getSettingLocked(name);
2285 if (!SettingsState.isSystemPackage(getContext(),
2286 setting.getPackageName())) {
2287 if (settingsState.resetSettingLocked(name, packageName)) {
2288 notifyForSettingsChange(key, name);
2289 }
2290 }
2291 }
2292 } break;
2293
2294 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2295 for (String name : settingsState.getSettingNamesLocked()) {
2296 Setting setting = settingsState.getSettingLocked(name);
2297 if (!SettingsState.isSystemPackage(getContext(),
2298 setting.getPackageName())) {
2299 if (setting.isDefaultSystemSet()) {
2300 if (settingsState.resetSettingLocked(name, packageName)) {
2301 notifyForSettingsChange(key, name);
2302 }
2303 } else if (settingsState.deleteSettingLocked(name)) {
2304 notifyForSettingsChange(key, name);
2305 }
2306 }
2307 }
2308 } break;
2309
2310 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2311 for (String name : settingsState.getSettingNamesLocked()) {
2312 Setting setting = settingsState.getSettingLocked(name);
2313 if (setting.isDefaultSystemSet()) {
2314 if (settingsState.resetSettingLocked(name, packageName)) {
2315 notifyForSettingsChange(key, name);
2316 }
2317 } else if (settingsState.deleteSettingLocked(name)) {
2318 notifyForSettingsChange(key, name);
2319 }
2320 }
2321 } break;
2322 }
2323 }
2324
Svetoslav683914b2015-01-15 14:22:26 -08002325 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002326 // Global and secure settings are signature protected. Apps signed
2327 // by the platform certificate are generally not uninstalled and
2328 // the main exception is tests. We trust components signed
2329 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002330
2331 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2332 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002333 if (systemSettings != null) {
2334 systemSettings.onPackageRemovedLocked(packageName);
2335 }
Svetoslav683914b2015-01-15 14:22:26 -08002336 }
2337
Mark Rathjend891f012017-01-19 04:10:37 +00002338 public void onUidRemovedLocked(int uid) {
2339 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2340 UserHandle.getUserId(uid));
2341 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2342 }
2343
Svetoslav683914b2015-01-15 14:22:26 -08002344 private SettingsState peekSettingsStateLocked(int key) {
2345 SettingsState settingsState = mSettingsStates.get(key);
2346 if (settingsState != null) {
2347 return settingsState;
2348 }
2349
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002350 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2351 return null;
2352 }
Svetoslav683914b2015-01-15 14:22:26 -08002353 return mSettingsStates.get(key);
2354 }
2355
2356 private void migrateAllLegacySettingsIfNeeded() {
2357 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002358 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002359 File globalFile = getSettingsFile(key);
2360 if (globalFile.exists()) {
2361 return;
2362 }
2363
2364 final long identity = Binder.clearCallingIdentity();
2365 try {
2366 List<UserInfo> users = mUserManager.getUsers(true);
2367
2368 final int userCount = users.size();
2369 for (int i = 0; i < userCount; i++) {
2370 final int userId = users.get(i).id;
2371
2372 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2373 SQLiteDatabase database = dbHelper.getWritableDatabase();
2374 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2375
2376 // Upgrade to the latest version.
2377 UpgradeController upgrader = new UpgradeController(userId);
2378 upgrader.upgradeIfNeededLocked();
2379
2380 // Drop from memory if not a running user.
2381 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2382 removeUserStateLocked(userId, false);
2383 }
2384 }
2385 } finally {
2386 Binder.restoreCallingIdentity(identity);
2387 }
2388 }
2389 }
2390
2391 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2392 // Every user has secure settings and if no file we need to migrate.
2393 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2394 File secureFile = getSettingsFile(secureKey);
2395 if (secureFile.exists()) {
2396 return;
2397 }
2398
2399 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2400 SQLiteDatabase database = dbHelper.getWritableDatabase();
2401
2402 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2403 }
2404
2405 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2406 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002407 // Move over the system settings.
2408 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2409 ensureSettingsStateLocked(systemKey);
2410 SettingsState systemSettings = mSettingsStates.get(systemKey);
2411 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2412 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002413
2414 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002415 // Do this after System settings, since this is the first thing we check when deciding
2416 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002417 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2418 ensureSettingsStateLocked(secureKey);
2419 SettingsState secureSettings = mSettingsStates.get(secureKey);
2420 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2421 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2422 secureSettings.persistSyncLocked();
2423
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002424 // Move over the global settings if owner.
2425 // Do this last, since this is the first thing we check when deciding
2426 // to skip over migration from db to xml for owner user.
2427 if (userId == UserHandle.USER_SYSTEM) {
2428 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2429 ensureSettingsStateLocked(globalKey);
2430 SettingsState globalSettings = mSettingsStates.get(globalKey);
2431 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2432 globalSettings.persistSyncLocked();
2433 }
Svetoslav683914b2015-01-15 14:22:26 -08002434
2435 // Drop the database as now all is moved and persisted.
2436 if (DROP_DATABASE_ON_MIGRATION) {
2437 dbHelper.dropDatabase();
2438 } else {
2439 dbHelper.backupDatabase();
2440 }
2441 }
2442
2443 private void migrateLegacySettingsLocked(SettingsState settingsState,
2444 SQLiteDatabase database, String table) {
2445 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2446 queryBuilder.setTables(table);
2447
2448 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2449 null, null, null, null, null);
2450
2451 if (cursor == null) {
2452 return;
2453 }
2454
2455 try {
2456 if (!cursor.moveToFirst()) {
2457 return;
2458 }
2459
2460 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2461 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2462
2463 settingsState.setVersionLocked(database.getVersion());
2464
2465 while (!cursor.isAfterLast()) {
2466 String name = cursor.getString(nameColumnIdx);
2467 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002468 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002469 SettingsState.SYSTEM_PACKAGE_NAME);
2470 cursor.moveToNext();
2471 }
2472 } finally {
2473 cursor.close();
2474 }
2475 }
2476
2477 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2478 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2479
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002480 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002481 return;
2482 }
2483
2484 final int userId = getUserIdFromKey(secureSettings.mKey);
2485
2486 final UserInfo user;
2487 final long identity = Binder.clearCallingIdentity();
2488 try {
2489 user = mUserManager.getUserInfo(userId);
2490 } finally {
2491 Binder.restoreCallingIdentity(identity);
2492 }
2493 if (user == null) {
2494 // Can happen due to races when deleting users - treat as benign.
2495 return;
2496 }
2497
2498 String androidId = Long.toHexString(new SecureRandom().nextLong());
2499 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002500 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002501
2502 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2503 + "] for user " + userId);
2504
2505 // Write a drop box entry if it's a restricted profile
2506 if (user.isRestricted()) {
2507 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2508 Context.DROPBOX_SERVICE);
2509 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2510 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2511 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2512 }
2513 }
2514 }
2515
2516 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002517 final int userId = getUserIdFromKey(key);
2518 Uri uri = getNotificationUriFor(key, name);
2519
Phil Weaver83fec002016-05-11 10:55:29 -07002520 mGenerationRegistry.incrementGeneration(key);
2521
Svetoslav7e0683b2015-08-03 16:02:52 -07002522 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2523 userId, 0, uri).sendToTarget();
2524
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002525 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002526 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2527 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002528 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002529 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2530 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002531 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002532
Svet Ganov53a441c2016-04-19 19:38:00 -07002533 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002534 }
2535
Svet Ganov53a441c2016-04-19 19:38:00 -07002536 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002537 Set<String> keysCloned) {
2538 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002539 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002540 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002541 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002542 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002543 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002544 final int key = makeKey(type, profileId);
2545 mGenerationRegistry.incrementGeneration(key);
2546
2547 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002548 }
2549 }
2550 }
Svetoslav683914b2015-01-15 14:22:26 -08002551 }
2552
Svetoslav683914b2015-01-15 14:22:26 -08002553 private boolean isGlobalSettingsKey(int key) {
2554 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2555 }
2556
2557 private boolean isSystemSettingsKey(int key) {
2558 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2559 }
2560
2561 private boolean isSecureSettingsKey(int key) {
2562 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2563 }
2564
Mark Rathjend891f012017-01-19 04:10:37 +00002565 private boolean isSsaidSettingsKey(int key) {
2566 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2567 }
2568
Svetoslav683914b2015-01-15 14:22:26 -08002569 private File getSettingsFile(int key) {
2570 if (isGlobalSettingsKey(key)) {
2571 final int userId = getUserIdFromKey(key);
2572 return new File(Environment.getUserSystemDirectory(userId),
2573 SETTINGS_FILE_GLOBAL);
2574 } else if (isSystemSettingsKey(key)) {
2575 final int userId = getUserIdFromKey(key);
2576 return new File(Environment.getUserSystemDirectory(userId),
2577 SETTINGS_FILE_SYSTEM);
2578 } else if (isSecureSettingsKey(key)) {
2579 final int userId = getUserIdFromKey(key);
2580 return new File(Environment.getUserSystemDirectory(userId),
2581 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002582 } else if (isSsaidSettingsKey(key)) {
2583 final int userId = getUserIdFromKey(key);
2584 return new File(Environment.getUserSystemDirectory(userId),
2585 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002586 } else {
2587 throw new IllegalArgumentException("Invalid settings key:" + key);
2588 }
2589 }
2590
2591 private Uri getNotificationUriFor(int key, String name) {
2592 if (isGlobalSettingsKey(key)) {
2593 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2594 : Settings.Global.CONTENT_URI;
2595 } else if (isSecureSettingsKey(key)) {
2596 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2597 : Settings.Secure.CONTENT_URI;
2598 } else if (isSystemSettingsKey(key)) {
2599 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2600 : Settings.System.CONTENT_URI;
2601 } else {
2602 throw new IllegalArgumentException("Invalid settings key:" + key);
2603 }
2604 }
2605
2606 private int getMaxBytesPerPackageForType(int type) {
2607 switch (type) {
2608 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002609 case SETTINGS_TYPE_SECURE:
2610 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002611 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2612 }
2613
2614 default: {
2615 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2616 }
2617 }
2618 }
2619
Svetoslav7e0683b2015-08-03 16:02:52 -07002620 private final class MyHandler extends Handler {
2621 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2622 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2623
2624 public MyHandler(Looper looper) {
2625 super(looper);
2626 }
2627
2628 @Override
2629 public void handleMessage(Message msg) {
2630 switch (msg.what) {
2631 case MSG_NOTIFY_URI_CHANGED: {
2632 final int userId = msg.arg1;
2633 Uri uri = (Uri) msg.obj;
2634 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2635 if (DEBUG) {
2636 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2637 }
2638 } break;
2639
2640 case MSG_NOTIFY_DATA_CHANGED: {
2641 mBackupManager.dataChanged();
2642 } break;
2643 }
2644 }
2645 }
2646
Svetoslav683914b2015-01-15 14:22:26 -08002647 private final class UpgradeController {
Mark Rathjend891f012017-01-19 04:10:37 +00002648 private static final int SETTINGS_VERSION = 137;
Svetoslav683914b2015-01-15 14:22:26 -08002649
2650 private final int mUserId;
2651
2652 public UpgradeController(int userId) {
2653 mUserId = userId;
2654 }
2655
2656 public void upgradeIfNeededLocked() {
2657 // The version of all settings for a user is the same (all users have secure).
2658 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002659 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002660
2661 // Try an update from the current state.
2662 final int oldVersion = secureSettings.getVersionLocked();
2663 final int newVersion = SETTINGS_VERSION;
2664
Svet Ganovc9755bc2015-03-28 13:21:22 -07002665 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002666 if (oldVersion == newVersion) {
2667 return;
2668 }
2669
2670 // Try to upgrade.
2671 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2672
2673 // If upgrade failed start from scratch and upgrade.
2674 if (curVersion != newVersion) {
2675 // Drop state we have for this user.
2676 removeUserStateLocked(mUserId, true);
2677
2678 // Recreate the database.
2679 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2680 SQLiteDatabase database = dbHelper.getWritableDatabase();
2681 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2682
2683 // Migrate the settings for this user.
2684 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2685
2686 // Now upgrade should work fine.
2687 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002688
2689 // Make a note what happened, so we don't wonder why data was lost
2690 String reason = "Settings rebuilt! Current version: "
2691 + curVersion + " while expected: " + newVersion;
2692 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002693 Settings.Global.DATABASE_DOWNGRADE_REASON,
2694 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002695 }
2696
2697 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002698 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002699 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002700 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002701 globalSettings.setVersionLocked(newVersion);
2702 }
2703
2704 // Set the secure settings version.
2705 secureSettings.setVersionLocked(newVersion);
2706
2707 // Set the system settings version.
2708 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002709 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002710 systemSettings.setVersionLocked(newVersion);
2711 }
2712
2713 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002714 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002715 }
2716
2717 private SettingsState getSecureSettingsLocked(int userId) {
2718 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2719 }
2720
Mark Rathjend891f012017-01-19 04:10:37 +00002721 private SettingsState getSsaidSettingsLocked(int userId) {
2722 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2723 }
2724
Svetoslav683914b2015-01-15 14:22:26 -08002725 private SettingsState getSystemSettingsLocked(int userId) {
2726 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2727 }
2728
Jeff Brown503cffc2015-03-26 18:08:51 -07002729 /**
2730 * You must perform all necessary mutations to bring the settings
2731 * for this user from the old to the new version. When you add a new
2732 * upgrade step you *must* update SETTINGS_VERSION.
2733 *
2734 * This is an example of moving a setting from secure to global.
2735 *
2736 * // v119: Example settings changes.
2737 * if (currentVersion == 118) {
2738 * if (userId == UserHandle.USER_OWNER) {
2739 * // Remove from the secure settings.
2740 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2741 * String name = "example_setting_to_move";
2742 * String value = secureSettings.getSetting(name);
2743 * secureSettings.deleteSetting(name);
2744 *
2745 * // Add to the global settings.
2746 * SettingsState globalSettings = getGlobalSettingsLocked();
2747 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2748 * }
2749 *
2750 * // Update the current version.
2751 * currentVersion = 119;
2752 * }
2753 */
Svetoslav683914b2015-01-15 14:22:26 -08002754 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2755 if (DEBUG) {
2756 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2757 + oldVersion + " to version: " + newVersion);
2758 }
2759
Jeff Brown503cffc2015-03-26 18:08:51 -07002760 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002761
John Spurlocke11ae112015-05-11 16:09:03 -04002762 // v119: Reset zen + ringer mode.
2763 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002764 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002765 final SettingsState globalSettings = getGlobalSettingsLocked();
2766 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002767 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2768 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002769 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002770 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2771 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002772 }
2773 currentVersion = 119;
2774 }
2775
Jason Monk27bbb2d2015-03-31 16:46:39 -04002776 // v120: Add double tap to wake setting.
2777 if (currentVersion == 119) {
2778 SettingsState secureSettings = getSecureSettingsLocked(userId);
2779 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2780 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002781 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002782 SettingsState.SYSTEM_PACKAGE_NAME);
2783
2784 currentVersion = 120;
2785 }
2786
Svetoslav7e0683b2015-08-03 16:02:52 -07002787 if (currentVersion == 120) {
2788 // Before 121, we used a different string encoding logic. We just bump the
2789 // version here; SettingsState knows how to handle pre-version 120 files.
2790 currentVersion = 121;
2791 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002792
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002793 if (currentVersion == 121) {
2794 // Version 122: allow OEMs to set a default payment component in resources.
2795 // Note that we only write the default if no default has been set;
2796 // if there is, we just leave the default at whatever it currently is.
2797 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2798 String defaultComponent = (getContext().getResources().getString(
2799 R.string.def_nfc_payment_component));
2800 Setting currentSetting = secureSettings.getSettingLocked(
2801 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2802 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002803 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002804 secureSettings.insertSettingLocked(
2805 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002806 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002807 }
2808 currentVersion = 122;
2809 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002810
2811 if (currentVersion == 122) {
2812 // Version 123: Adding a default value for the ability to add a user from
2813 // the lock screen.
2814 if (userId == UserHandle.USER_SYSTEM) {
2815 final SettingsState globalSettings = getGlobalSettingsLocked();
2816 Setting currentSetting = globalSettings.getSettingLocked(
2817 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002818 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002819 globalSettings.insertSettingLocked(
2820 Settings.Global.ADD_USERS_WHEN_LOCKED,
2821 getContext().getResources().getBoolean(
2822 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002823 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002824 }
2825 }
2826 currentVersion = 123;
2827 }
Bryce Leebd179282015-12-17 19:01:37 -08002828
2829 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002830 final SettingsState globalSettings = getGlobalSettingsLocked();
2831 String defaultDisabledProfiles = (getContext().getResources().getString(
2832 R.string.def_bluetooth_disabled_profiles));
2833 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002834 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002835 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002836 }
2837
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002838 if (currentVersion == 124) {
2839 // Version 124: allow OEMs to set a default value for whether IME should be
2840 // shown when a physical keyboard is connected.
2841 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2842 Setting currentSetting = secureSettings.getSettingLocked(
2843 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002844 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002845 secureSettings.insertSettingLocked(
2846 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2847 getContext().getResources().getBoolean(
2848 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002849 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002850 }
2851 currentVersion = 125;
2852 }
2853
Ruben Brunk98576cf2016-03-07 18:54:28 -08002854 if (currentVersion == 125) {
2855 // Version 125: Allow OEMs to set the default VR service.
2856 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2857
2858 Setting currentSetting = secureSettings.getSettingLocked(
2859 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002860 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002861 ArraySet<ComponentName> l =
2862 SystemConfig.getInstance().getDefaultVrComponents();
2863
2864 if (l != null && !l.isEmpty()) {
2865 StringBuilder b = new StringBuilder();
2866 boolean start = true;
2867 for (ComponentName c : l) {
2868 if (!start) {
2869 b.append(':');
2870 }
2871 b.append(c.flattenToString());
2872 start = false;
2873 }
2874 secureSettings.insertSettingLocked(
2875 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002876 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002877 }
2878
2879 }
2880 currentVersion = 126;
2881 }
2882
Daniel U02ba6122016-04-01 18:41:42 +01002883 if (currentVersion == 126) {
2884 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2885 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2886 if (mUserManager.isManagedProfile(userId)) {
2887 final SettingsState systemSecureSettings =
2888 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2889
2890 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2891 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002892 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002893 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2894 secureSettings.insertSettingLocked(
2895 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002896 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002897 SettingsState.SYSTEM_PACKAGE_NAME);
2898 }
2899
2900 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2901 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002902 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002903 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2904 secureSettings.insertSettingLocked(
2905 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002906 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002907 SettingsState.SYSTEM_PACKAGE_NAME);
2908 }
2909 }
2910 currentVersion = 127;
2911 }
2912
Steven Ngdc20ba62016-04-26 18:19:04 +01002913 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002914 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01002915 currentVersion = 128;
2916 }
2917
Julia Reynolds1f721e12016-07-11 08:50:58 -04002918 if (currentVersion == 128) {
2919 // Version 128: Allow OEMs to grant DND access to default apps. Note that
2920 // the new apps are appended to the list of already approved apps.
2921 final SettingsState systemSecureSettings =
2922 getSecureSettingsLocked(userId);
2923
2924 final Setting policyAccess = systemSecureSettings.getSettingLocked(
2925 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
2926 String defaultPolicyAccess = getContext().getResources().getString(
2927 com.android.internal.R.string.config_defaultDndAccessPackages);
2928 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
2929 if (policyAccess.isNull()) {
2930 systemSecureSettings.insertSettingLocked(
2931 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002932 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002933 SettingsState.SYSTEM_PACKAGE_NAME);
2934 } else {
2935 StringBuilder currentSetting =
2936 new StringBuilder(policyAccess.getValue());
2937 currentSetting.append(":");
2938 currentSetting.append(defaultPolicyAccess);
2939 systemSecureSettings.updateSettingLocked(
2940 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002941 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04002942 SettingsState.SYSTEM_PACKAGE_NAME);
2943 }
2944 }
2945
2946 currentVersion = 129;
2947 }
2948
Dan Sandler71f85e92016-07-20 13:46:05 -04002949 if (currentVersion == 129) {
2950 // default longpress timeout changed from 500 to 400. If unchanged from the old
2951 // default, update to the new default.
2952 final SettingsState systemSecureSettings =
2953 getSecureSettingsLocked(userId);
2954 final String oldValue = systemSecureSettings.getSettingLocked(
2955 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
2956 if (TextUtils.equals("500", oldValue)) {
2957 systemSecureSettings.insertSettingLocked(
2958 Settings.Secure.LONG_PRESS_TIMEOUT,
2959 String.valueOf(getContext().getResources().getInteger(
2960 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002961 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04002962 }
2963 currentVersion = 130;
2964 }
2965
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002966 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07002967 // Split Ambient settings
2968 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2969 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
2970 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
2971
2972 if (dozeExplicitlyDisabled) {
2973 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002974 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002975 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002976 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07002977 }
2978 currentVersion = 131;
2979 }
2980
2981 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002982 // Initialize new multi-press timeout to default value
2983 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
2984 final String oldValue = systemSecureSettings.getSettingLocked(
2985 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
2986 if (TextUtils.equals(null, oldValue)) {
2987 systemSecureSettings.insertSettingLocked(
2988 Settings.Secure.MULTI_PRESS_TIMEOUT,
2989 String.valueOf(getContext().getResources().getInteger(
2990 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002991 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002992 }
2993
Adrian Roos69741a22016-10-21 14:49:17 -07002994 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07002995 }
2996
Adrian Roos69741a22016-10-21 14:49:17 -07002997 if (currentVersion == 132) {
2998 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01002999 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3000 String defaultSyncParentSounds = (getContext().getResources()
3001 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3002 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003003 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3004 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003005 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003006 }
3007
Adrian Roos69741a22016-10-21 14:49:17 -07003008 if (currentVersion == 133) {
3009 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003010 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3011 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3012 null) {
3013 String defaultEndButtonBehavior = Integer.toString(getContext()
3014 .getResources().getInteger(R.integer.def_end_button_behavior));
3015 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003016 defaultEndButtonBehavior, null, true,
3017 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003018 }
Adrian Roos69741a22016-10-21 14:49:17 -07003019 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003020 }
3021
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003022 if (currentVersion == 134) {
3023 // Remove setting that specifies if magnification values should be preserved.
3024 // This setting defaulted to true and never has a UI.
3025 getSecureSettingsLocked(userId).deleteSettingLocked(
3026 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3027 currentVersion = 135;
3028 }
3029
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003030 if (currentVersion == 135) {
3031 // Version 135: Migrating the NETWORK_SCORER_APP setting to the
3032 // NETWORK_RECOMMENDATIONS_ENABLED setting.
3033 if (userId == UserHandle.USER_SYSTEM) {
3034 final SettingsState globalSettings = getGlobalSettingsLocked();
3035 Setting currentSetting = globalSettings.getSettingLocked(
3036 Global.NETWORK_SCORER_APP);
3037 if (!currentSetting.isNull()) {
3038 // A scorer was set so enable recommendations.
3039 globalSettings.insertSettingLocked(
3040 Global.NETWORK_RECOMMENDATIONS_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003041 "1", null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003042 SettingsState.SYSTEM_PACKAGE_NAME);
3043
3044 // and clear the scorer setting since it's no longer needed.
3045 globalSettings.insertSettingLocked(
3046 Global.NETWORK_SCORER_APP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003047 null, null, true,
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003048 SettingsState.SYSTEM_PACKAGE_NAME);
3049 }
3050 }
3051 currentVersion = 136;
3052 }
3053
Mark Rathjend891f012017-01-19 04:10:37 +00003054 if (currentVersion == 136) {
3055 // Version 136: Store legacy SSAID for all apps currently installed on the
3056 // device as first step in migrating SSAID to be unique per application.
3057
3058 final boolean isUpgrade;
3059 try {
3060 isUpgrade = mPackageManager.isUpgrade();
3061 } catch (RemoteException e) {
3062 throw new IllegalStateException("Package manager not available");
3063 }
3064 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3065 // user data or first boot on a new device should use new ssaid generation.
3066 if (isUpgrade) {
3067 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003068 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3069 userId, Settings.Secure.ANDROID_ID);
3070 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3071 || legacySsaidSetting.getValue() == null) {
3072 throw new IllegalStateException("Legacy ssaid not accessible");
3073 }
3074 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003075
3076 // Fill each uid with the legacy ssaid to be backwards compatible.
3077 final List<PackageInfo> packages;
3078 try {
3079 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3080 } catch (RemoteException e) {
3081 throw new IllegalStateException("Package manager not available");
3082 }
3083
3084 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3085 for (PackageInfo info : packages) {
3086 // Check if the UID already has an entry in the table.
3087 final String uid = Integer.toString(info.applicationInfo.uid);
3088 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3089
3090 if (ssaid.isNull() || ssaid.getValue() == null) {
3091 // Android Id doesn't exist for this package so create it.
3092 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3093 info.packageName);
3094 }
3095 }
3096 }
3097
3098 currentVersion = 137;
3099 }
3100
Dan Sandler71f85e92016-07-20 13:46:05 -04003101 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003102 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003103 + newVersion + " left it at "
3104 + currentVersion + " instead; this is probably a bug", new Throwable());
3105 if (DEBUG) {
3106 throw new RuntimeException("db upgrade error");
3107 }
3108 }
3109
Jeff Brown503cffc2015-03-26 18:08:51 -07003110 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003111
Jeff Brown503cffc2015-03-26 18:08:51 -07003112 // Return the current version.
3113 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003114 }
3115 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003116 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003117}