blob: 7de54db4ffebc9f077fc441a997db241aa75c940 [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
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010067import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080068import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000069import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010071import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080072import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000073import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070076import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080077import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import com.android.internal.annotations.GuardedBy;
80import com.android.internal.content.PackageMonitor;
81import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080082import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070083import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080084import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040085
Svetoslav683914b2015-01-15 14:22:26 -080086import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080087import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080089import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080090import java.nio.ByteBuffer;
91import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070094import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000096import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000097import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080098import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100100import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800101import java.util.Set;
102import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000103
Mark Rathjen7599f132017-01-23 14:15:54 -0800104import javax.crypto.Mac;
105import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
Svetoslav Ganove080da92016-12-21 17:10:35 -0800107
Svetoslav683914b2015-01-15 14:22:26 -0800108/**
109 * <p>
110 * This class is a content provider that publishes the system settings.
111 * It can be accessed via the content provider APIs or via custom call
112 * commands. The latter is a bit faster and is the preferred way to access
113 * the platform settings.
114 * </p>
115 * <p>
116 * There are three settings types, global (with signature level protection
117 * and shared across users), secure (with signature permission level
118 * protection and per user), and system (with dangerous permission level
119 * protection and per user). Global settings are stored under the device owner.
120 * Each of these settings is represented by a {@link
121 * com.android.providers.settings.SettingsState} object mapped to an integer
122 * key derived from the setting type in the most significant bits and user
123 * id in the least significant bits. Settings are synchronously loaded on
124 * instantiation of a SettingsState and asynchronously persisted on mutation.
125 * Settings are stored in the user specific system directory.
126 * </p>
127 * <p>
128 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
129 * and get a warning. Targeting higher API version prohibits this as the
130 * system settings are not a place for apps to save their state. When a package
131 * is removed the settings it added are deleted. Apps cannot delete system
132 * settings added by the platform. System settings values are validated to
133 * ensure the clients do not put bad values. Global and secure settings are
134 * changed only by trusted parties, therefore no validation is performed. Also
135 * there is a limit on the amount of app specific settings that can be added
136 * to prevent unlimited growth of the system process memory footprint.
137 * </p>
138 */
139@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700141 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700143 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800144
145 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700146
Christopher Tate06efb532012-08-24 15:29:27 -0700147 private static final String TABLE_SYSTEM = "system";
148 private static final String TABLE_SECURE = "secure";
149 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800150
151 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final String TABLE_FAVORITES = "favorites";
153 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800154 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
155 private static final String TABLE_BOOKMARKS = "bookmarks";
156 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Svetoslav683914b2015-01-15 14:22:26 -0800158 // The set of removed legacy tables.
159 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700160 static {
Svetoslav683914b2015-01-15 14:22:26 -0800161 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
162 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
163 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
164 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
165 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
166 }
Christopher Tate06efb532012-08-24 15:29:27 -0700167
Svetoslav683914b2015-01-15 14:22:26 -0800168 private static final int MUTATION_OPERATION_INSERT = 1;
169 private static final int MUTATION_OPERATION_DELETE = 2;
170 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800171 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400172
Svetoslav683914b2015-01-15 14:22:26 -0800173 private static final String[] ALL_COLUMNS = new String[] {
174 Settings.NameValueTable._ID,
175 Settings.NameValueTable.NAME,
176 Settings.NameValueTable.VALUE
177 };
178
Makoto Onuki53f0e022017-11-29 13:51:01 -0800179 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
180 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
181 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
182 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Svet Ganov53a441c2016-04-19 19:38:00 -0700183
184 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
185 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700186
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700187 // Overlay specified settings whitelisted for Instant Apps
188 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
189 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
190 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
191
192 static {
193 for (String name : Resources.getSystem().getStringArray(
194 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
195 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
196 }
197 for (String name : Resources.getSystem().getStringArray(
198 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
199 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
200 }
201 for (String name : Resources.getSystem().getStringArray(
202 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
203 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
204 }
205 }
206
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800207 // Changes to these global settings are synchronously persisted
208 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
209 static {
210 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
211 }
212
213 // Changes to these secure settings are synchronously persisted
214 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
215 static {
216 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
217 }
218
Svetoslav683914b2015-01-15 14:22:26 -0800219 // Per user secure settings that moved to the for all users global settings.
220 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
221 static {
222 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700223 }
224
Svetoslav683914b2015-01-15 14:22:26 -0800225 // Per user system settings that moved to the for all users global settings.
226 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
227 static {
228 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229 }
230
Svetoslav683914b2015-01-15 14:22:26 -0800231 // Per user system settings that moved to the per user secure settings.
232 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
233 static {
234 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700235 }
236
Svetoslav683914b2015-01-15 14:22:26 -0800237 // Per all users global settings that moved to the per user secure settings.
238 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
239 static {
240 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700241 }
242
Svetoslav683914b2015-01-15 14:22:26 -0800243 // Per user secure settings that are cloned for the managed profiles of the user.
244 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
245 static {
246 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247 }
248
Svetoslav683914b2015-01-15 14:22:26 -0800249 // Per user system settings that are cloned for the managed profiles of the user.
250 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
251 static {
252 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400253 }
254
Andre Lago3fa139c2016-08-04 13:53:44 +0100255 // Per user system settings that are cloned from the profile's parent when a dependency
256 // in {@link Settings.Secure} is set to "1".
257 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
258 static {
259 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
260 }
261
Svetoslav683914b2015-01-15 14:22:26 -0800262 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700263
Svetoslav683914b2015-01-15 14:22:26 -0800264 @GuardedBy("mLock")
265 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700266
Svet Ganova8f90262016-05-10 08:44:48 -0700267 @GuardedBy("mLock")
268 private HandlerThread mHandlerThread;
269
Makoto Onuki73360ab2017-03-17 11:50:13 -0700270 @GuardedBy("mLock")
271 private Handler mHandler;
272
Svetoslav7ec28e82015-05-20 17:01:10 -0700273 // We have to call in the user manager with no lock held,
274 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800275
yuemingw1d13eae2018-01-30 17:27:54 +0000276 private UserManagerInternal mUserManagerInternal;
277
Svetoslav7ec28e82015-05-20 17:01:10 -0700278 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700279 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700280
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800282 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700283 }
284
285 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800286 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700287 }
288
289 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800290 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 }
292
293 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800294 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700295 }
296
297 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800298 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700299 }
300
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700301 @Override
302 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800303 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000304
305 // fail to boot if there're any backed up settings that don't have a non-null validator
306 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000307 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000308 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000309
Svetoslav683914b2015-01-15 14:22:26 -0800310 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700311 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000312 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700313 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700314 mHandlerThread = new HandlerThread(LOG_TAG,
315 Process.THREAD_PRIORITY_BACKGROUND);
316 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700317 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800318 mSettingsRegistry = new SettingsRegistry();
319 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700320 mHandler.post(() -> {
321 registerBroadcastReceivers();
322 startWatchingUserRestrictionChanges();
323 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700324 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325 return true;
326 }
327
Michal Karpinski2c37b082018-01-18 16:14:27 +0000328 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000329 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
330 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000331
332 failToBootIfOffendersPresent(offenders, "Settings.System");
333 }
334
335 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000336 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
337 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000338
339 failToBootIfOffendersPresent(offenders, "Settings.Global");
340 }
341
Michal Karpinski964943a2018-01-19 16:28:26 +0000342 private void ensureAllBackedUpSecureSettingsHaveValidators() {
343 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
344 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
345
346 failToBootIfOffendersPresent(offenders, "Settings.Secure");
347 }
348
Michal Karpinski5db1e432018-01-18 20:10:24 +0000349 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
350 if (offenders.length() > 0) {
351 throw new RuntimeException("All " + settingsType + " settings that are backed up"
352 + " have to have a non-null validator, but those don't: " + offenders);
353 }
354 }
355
356 private String getOffenders(String[] settingsToBackup, Map<String,
357 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000358 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000359 for (String setting : settingsToBackup) {
360 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000361 offenders.append(setting).append(" ");
362 }
363 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000364 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000365 }
366
Michal Karpinski964943a2018-01-19 16:28:26 +0000367 private final String[] concat(String[] first, String[] second) {
368 if (second == null || second.length == 0) {
369 return first;
370 }
371 final int firstLen = first.length;
372 final int secondLen = second.length;
373 String[] both = new String[firstLen + secondLen];
374 System.arraycopy(first, 0, both, 0, firstLen);
375 System.arraycopy(second, 0, both, firstLen, secondLen);
376 return both;
377 }
378
Svetoslav683914b2015-01-15 14:22:26 -0800379 @Override
380 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700381 final int requestingUserId = getRequestingUserId(args);
382 switch (method) {
383 case Settings.CALL_METHOD_GET_GLOBAL: {
384 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700385 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800386 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700387
388 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800389 Setting setting = getSecureSetting(name, requestingUserId,
390 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700391 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700392 }
393
394 case Settings.CALL_METHOD_GET_SYSTEM: {
395 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700396 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700397 }
398
399 case Settings.CALL_METHOD_PUT_GLOBAL: {
400 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800401 String tag = getSettingTag(args);
402 final boolean makeDefault = getSettingMakeDefault(args);
403 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700404 break;
405 }
406
407 case Settings.CALL_METHOD_PUT_SECURE: {
408 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800409 String tag = getSettingTag(args);
410 final boolean makeDefault = getSettingMakeDefault(args);
411 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700412 break;
413 }
414
415 case Settings.CALL_METHOD_PUT_SYSTEM: {
416 String value = getSettingValue(args);
417 insertSystemSetting(name, value, requestingUserId);
418 break;
419 }
420
Svetoslav Ganove080da92016-12-21 17:10:35 -0800421 case Settings.CALL_METHOD_RESET_GLOBAL: {
422 final int mode = getResetModeEnforcingPermission(args);
423 String tag = getSettingTag(args);
424 resetGlobalSetting(requestingUserId, mode, tag);
425 break;
426 }
427
428 case Settings.CALL_METHOD_RESET_SECURE: {
429 final int mode = getResetModeEnforcingPermission(args);
430 String tag = getSettingTag(args);
431 resetSecureSetting(requestingUserId, mode, tag);
432 break;
433 }
434
Svetoslav7ec28e82015-05-20 17:01:10 -0700435 default: {
436 Slog.w(LOG_TAG, "call() with invalid method: " + method);
437 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700438 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700439
Christopher Tate06efb532012-08-24 15:29:27 -0700440 return null;
441 }
442
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800443 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800444 public String getType(Uri uri) {
445 Arguments args = new Arguments(uri, null, null, true);
446 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700447 return "vnd.android.cursor.dir/" + args.table;
448 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700449 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700450 }
451 }
452
453 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800454 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
455 String order) {
456 if (DEBUG) {
457 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700458 }
459
Svetoslav683914b2015-01-15 14:22:26 -0800460 Arguments args = new Arguments(uri, where, whereArgs, true);
461 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700462
Svetoslav683914b2015-01-15 14:22:26 -0800463 // If a legacy table that is gone, done.
464 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
465 return new MatrixCursor(normalizedProjection, 0);
466 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700467
Svetoslav7ec28e82015-05-20 17:01:10 -0700468 switch (args.table) {
469 case TABLE_GLOBAL: {
470 if (args.name != null) {
471 Setting setting = getGlobalSetting(args.name);
472 return packageSettingForQuery(setting, normalizedProjection);
473 } else {
474 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700475 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700476 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700477
Svetoslav7ec28e82015-05-20 17:01:10 -0700478 case TABLE_SECURE: {
479 final int userId = UserHandle.getCallingUserId();
480 if (args.name != null) {
481 Setting setting = getSecureSetting(args.name, userId);
482 return packageSettingForQuery(setting, normalizedProjection);
483 } else {
484 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800485 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700486 }
Svetoslav683914b2015-01-15 14:22:26 -0800487
Svetoslav7ec28e82015-05-20 17:01:10 -0700488 case TABLE_SYSTEM: {
489 final int userId = UserHandle.getCallingUserId();
490 if (args.name != null) {
491 Setting setting = getSystemSetting(args.name, userId);
492 return packageSettingForQuery(setting, normalizedProjection);
493 } else {
494 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800495 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 }
Svetoslav683914b2015-01-15 14:22:26 -0800497
Svetoslav7ec28e82015-05-20 17:01:10 -0700498 default: {
499 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700500 }
501 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700502 }
503
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700504 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800505 public Uri insert(Uri uri, ContentValues values) {
506 if (DEBUG) {
507 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700508 }
509
Svetoslav683914b2015-01-15 14:22:26 -0800510 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700511
Svetoslav683914b2015-01-15 14:22:26 -0800512 // If a legacy table that is gone, done.
513 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 return null;
515 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516
Svetoslav683914b2015-01-15 14:22:26 -0800517 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700518 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800519 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700520 }
521
Svetoslav683914b2015-01-15 14:22:26 -0800522 String value = values.getAsString(Settings.Secure.VALUE);
523
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 switch (table) {
525 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800526 if (insertGlobalSetting(name, value, null, false,
527 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700528 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700529 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700530 } break;
531
532 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800533 if (insertSecureSetting(name, value, null, false,
534 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700535 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
536 }
537 } break;
538
539 case TABLE_SYSTEM: {
540 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
541 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
542 }
543 } break;
544
545 default: {
546 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700547 }
548 }
549
Svetoslav683914b2015-01-15 14:22:26 -0800550 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700551 }
552
553 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800554 public int bulkInsert(Uri uri, ContentValues[] allValues) {
555 if (DEBUG) {
556 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700558
Svetoslav683914b2015-01-15 14:22:26 -0800559 int insertionCount = 0;
560 final int valuesCount = allValues.length;
561 for (int i = 0; i < valuesCount; i++) {
562 ContentValues values = allValues[i];
563 if (insert(uri, values) != null) {
564 insertionCount++;
565 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700566 }
Svetoslav683914b2015-01-15 14:22:26 -0800567
568 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700569 }
570
571 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800572 public int delete(Uri uri, String where, String[] whereArgs) {
573 if (DEBUG) {
574 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700576
Svetoslav683914b2015-01-15 14:22:26 -0800577 Arguments args = new Arguments(uri, where, whereArgs, false);
578
579 // If a legacy table that is gone, done.
580 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
581 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700582 }
Svetoslav683914b2015-01-15 14:22:26 -0800583
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700584 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800585 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700586 }
Svetoslav683914b2015-01-15 14:22:26 -0800587
Svetoslav7ec28e82015-05-20 17:01:10 -0700588 switch (args.table) {
589 case TABLE_GLOBAL: {
590 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700591 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700592 }
Svetoslav683914b2015-01-15 14:22:26 -0800593
Svetoslav7ec28e82015-05-20 17:01:10 -0700594 case TABLE_SECURE: {
595 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700596 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700597 }
Svetoslav683914b2015-01-15 14:22:26 -0800598
Svetoslav7ec28e82015-05-20 17:01:10 -0700599 case TABLE_SYSTEM: {
600 final int userId = UserHandle.getCallingUserId();
601 return deleteSystemSetting(args.name, userId) ? 1 : 0;
602 }
603
604 default: {
605 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800606 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700607 }
Svetoslav683914b2015-01-15 14:22:26 -0800608 }
609
610 @Override
611 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
612 if (DEBUG) {
613 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700614 }
Svetoslav683914b2015-01-15 14:22:26 -0800615
616 Arguments args = new Arguments(uri, where, whereArgs, false);
617
618 // If a legacy table that is gone, done.
619 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
620 return 0;
621 }
622
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700623 String name = values.getAsString(Settings.Secure.NAME);
624 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800625 return 0;
626 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700627 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800628
Svetoslav7ec28e82015-05-20 17:01:10 -0700629 switch (args.table) {
630 case TABLE_GLOBAL: {
631 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800632 return updateGlobalSetting(args.name, value, null, false,
633 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700634 }
Svetoslav683914b2015-01-15 14:22:26 -0800635
Svetoslav7ec28e82015-05-20 17:01:10 -0700636 case TABLE_SECURE: {
637 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800638 return updateSecureSetting(args.name, value, null, false,
639 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700640 }
Svetoslav683914b2015-01-15 14:22:26 -0800641
Svetoslav7ec28e82015-05-20 17:01:10 -0700642 case TABLE_SYSTEM: {
643 final int userId = UserHandle.getCallingUserId();
644 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
645 }
Svetoslav683914b2015-01-15 14:22:26 -0800646
Svetoslav7ec28e82015-05-20 17:01:10 -0700647 default: {
648 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800649 }
650 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651 }
652
653 @Override
654 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100655 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
656 if (userId != UserHandle.getCallingUserId()) {
657 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
658 "Access files from the settings of another user");
659 }
660 uri = ContentProvider.getUriWithoutUserId(uri);
661
Andre Lago3fa139c2016-08-04 13:53:44 +0100662 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700663 final String cacheName;
664 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100665 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700666 cacheName = Settings.System.RINGTONE_CACHE;
667 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100668 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700669 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
670 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100671 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700672 cacheName = Settings.System.ALARM_ALERT_CACHE;
673 } else {
674 throw new FileNotFoundException("Direct file access no longer supported; "
675 + "ringtone playback is available through android.media.Ringtone");
676 }
677
Andre Lago3fa139c2016-08-04 13:53:44 +0100678 int actualCacheOwner;
679 // Redirect cache to parent if ringtone setting is owned by profile parent
680 synchronized (mLock) {
681 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
682 cacheRingtoneSetting);
683 }
684 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700685 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
686 }
687
688 private File getRingtoneCacheDir(int userId) {
689 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
690 cacheDir.mkdir();
691 SELinux.restorecon(cacheDir);
692 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700693 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800694
Eugene Suslad72c3972016-12-27 15:49:30 -0800695 /**
696 * Dump all settings as a proto buf.
697 *
698 * @param fd The file to dump to
699 */
700 void dumpProto(@NonNull FileDescriptor fd) {
701 ProtoOutputStream proto = new ProtoOutputStream(fd);
702
703 synchronized (mLock) {
704 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800705 }
706
707 proto.flush();
708 }
709
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700710 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800711 synchronized (mLock) {
712 final long identity = Binder.clearCallingIdentity();
713 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700714 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800715 final int userCount = users.size();
716 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700717 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800718 }
719 } finally {
720 Binder.restoreCallingIdentity(identity);
721 }
722 }
723 }
724
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700725 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700726 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800727 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700728 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
729 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700730 if (globalSettings != null) {
731 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800732 pw.println();
733 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700734 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800735 }
736
737 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700738 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
739 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700740 if (secureSettings != null) {
741 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800742 pw.println();
743 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700744 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700745
Svetoslavb505ccc2015-02-17 12:41:04 -0800746 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700747 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
748 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700749 if (systemSettings != null) {
750 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800751 pw.println();
752 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700753 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800754 }
755
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700756 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
757 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800758
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700759 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800760
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700761 for (int i = 0; i < nameCount; i++) {
762 String name = names.get(i);
763 Setting setting = settingsState.getSettingLocked(name);
764 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
765 pw.print(" name:"); pw.print(toDumpString(name));
766 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800767 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700768 }
769 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800770 if (setting.getDefaultValue() != null) {
771 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800772 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800773 }
774 if (setting.getTag() != null) {
775 pw.print(" tag:"); pw.print(setting.getTag());
776 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800777 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700778 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800779 }
780
Svetoslav7e0683b2015-08-03 16:02:52 -0700781 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700782 if (s != null) {
783 return s;
784 }
785 return "{null}";
786 }
787
Svetoslav683914b2015-01-15 14:22:26 -0800788 private void registerBroadcastReceivers() {
789 IntentFilter userFilter = new IntentFilter();
790 userFilter.addAction(Intent.ACTION_USER_REMOVED);
791 userFilter.addAction(Intent.ACTION_USER_STOPPED);
792
793 getContext().registerReceiver(new BroadcastReceiver() {
794 @Override
795 public void onReceive(Context context, Intent intent) {
796 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700797 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800798
799 switch (intent.getAction()) {
800 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700801 synchronized (mLock) {
802 mSettingsRegistry.removeUserStateLocked(userId, true);
803 }
Svetoslav683914b2015-01-15 14:22:26 -0800804 } break;
805
806 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700807 synchronized (mLock) {
808 mSettingsRegistry.removeUserStateLocked(userId, false);
809 }
Svetoslav683914b2015-01-15 14:22:26 -0800810 } break;
811 }
812 }
813 }, userFilter);
814
815 PackageMonitor monitor = new PackageMonitor() {
816 @Override
817 public void onPackageRemoved(String packageName, int uid) {
818 synchronized (mLock) {
819 mSettingsRegistry.onPackageRemovedLocked(packageName,
820 UserHandle.getUserId(uid));
821 }
822 }
Mark Rathjend891f012017-01-19 04:10:37 +0000823
824 @Override
825 public void onUidRemoved(int uid) {
826 synchronized (mLock) {
827 mSettingsRegistry.onUidRemovedLocked(uid);
828 }
829 }
Svetoslav683914b2015-01-15 14:22:26 -0800830 };
831
832 // package changes
833 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
834 UserHandle.ALL, true);
835 }
836
Svet Ganov53a441c2016-04-19 19:38:00 -0700837 private void startWatchingUserRestrictionChanges() {
838 // TODO: The current design of settings looking different based on user restrictions
839 // should be reworked to keep them separate and system code should check the setting
840 // first followed by checking the user restriction before performing an operation.
841 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
842 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
843 Bundle prevRestrictions) -> {
844 // We are changing the settings affected by restrictions to their current
845 // value with a forced update to ensure that all cross profile dependencies
846 // are taken into account. Also make sure the settings update to.. the same
847 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800848 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
849 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700850 final long identity = Binder.clearCallingIdentity();
851 try {
852 synchronized (mLock) {
853 Setting setting = getSecureSetting(
854 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
855 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 setting != null ? setting.getValue() : null, null,
857 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700858 }
859 } finally {
860 Binder.restoreCallingIdentity(identity);
861 }
862 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800863 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
864 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700865 final long identity = Binder.clearCallingIdentity();
866 try {
867 synchronized (mLock) {
868 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800869 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700870 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800871 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700872 }
873 } finally {
874 Binder.restoreCallingIdentity(identity);
875 }
876 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800877 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
878 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700879 final long identity = Binder.clearCallingIdentity();
880 try {
881 synchronized (mLock) {
882 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800883 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700884 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800885 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700886 }
887 } finally {
888 Binder.restoreCallingIdentity(identity);
889 }
890 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800891 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
892 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700893 final long identity = Binder.clearCallingIdentity();
894 try {
895 synchronized (mLock) {
896 Setting enable = getGlobalSetting(
897 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800898 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700899 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800900 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700901 Setting include = getGlobalSetting(
902 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800903 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700904 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800905 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700906 }
907 } finally {
908 Binder.restoreCallingIdentity(identity);
909 }
910 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
912 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700913 final long identity = Binder.clearCallingIdentity();
914 try {
915 synchronized (mLock) {
916 Setting setting = getGlobalSetting(
917 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700919 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800920 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700921 }
922 } finally {
923 Binder.restoreCallingIdentity(identity);
924 }
925 }
926 });
927 }
928
Svetoslav7ec28e82015-05-20 17:01:10 -0700929 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800930 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700931 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800932 }
933
Svetoslav7ec28e82015-05-20 17:01:10 -0700934 synchronized (mLock) {
935 // Get the settings.
936 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700937 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800938
Chad Brubaker97bccee2017-01-05 15:51:41 -0800939 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
940 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800941
Svetoslav7ec28e82015-05-20 17:01:10 -0700942 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800943
Svetoslav7ec28e82015-05-20 17:01:10 -0700944 String[] normalizedProjection = normalizeProjection(projection);
945 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800946
Svetoslav7ec28e82015-05-20 17:01:10 -0700947 // Anyone can get the global settings, so no security checks.
948 for (int i = 0; i < nameCount; i++) {
949 String name = names.get(i);
950 Setting setting = settingsState.getSettingLocked(name);
951 appendSettingToCursor(result, setting);
952 }
953
954 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800955 }
Svetoslav683914b2015-01-15 14:22:26 -0800956 }
957
Svetoslav7ec28e82015-05-20 17:01:10 -0700958 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800959 if (DEBUG) {
960 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
961 }
962
Chad Brubakera6830e72017-04-28 17:34:36 -0700963 // Ensure the caller can access the setting.
964 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
965
Svetoslav683914b2015-01-15 14:22:26 -0800966 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700967 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700968 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700969 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800970 }
Svetoslav683914b2015-01-15 14:22:26 -0800971 }
972
Svetoslav Ganove080da92016-12-21 17:10:35 -0800973 private boolean updateGlobalSetting(String name, String value, String tag,
974 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800975 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800976 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
977 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
978 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800979 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800980 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
981 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800982 }
983
Svetoslav Ganove080da92016-12-21 17:10:35 -0800984 private boolean insertGlobalSetting(String name, String value, String tag,
985 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700986 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800987 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
988 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
989 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700990 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800991 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
992 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700993 }
994
Svet Ganov53a441c2016-04-19 19:38:00 -0700995 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800996 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800997 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
998 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800999 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1001 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001002 }
1003
Svetoslav Ganove080da92016-12-21 17:10:35 -08001004 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1005 if (DEBUG) {
1006 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1007 + mode + ", " + tag + ")");
1008 }
1009 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1010 MUTATION_OPERATION_RESET, false, mode);
1011 }
1012
1013 private boolean mutateGlobalSetting(String name, String value, String tag,
1014 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1015 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001016 // Make sure the caller can change the settings - treated as secure.
1017 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1018
Svetoslav683914b2015-01-15 14:22:26 -08001019 // Resolve the userId on whose behalf the call is made.
1020 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1021
Makoto Onuki28da2e32015-11-20 11:30:44 -08001022 // If this is a setting that is currently restricted for this user, do not allow
1023 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001024 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1025 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001026 return false;
1027 }
1028
1029 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001030 synchronized (mLock) {
1031 switch (operation) {
1032 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001033 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1034 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001035 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001036 }
Svetoslav683914b2015-01-15 14:22:26 -08001037
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001039 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001040 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001041 }
Svetoslav683914b2015-01-15 14:22:26 -08001042
Svetoslav7ec28e82015-05-20 17:01:10 -07001043 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001044 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1045 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001046 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001047 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001048
1049 case MUTATION_OPERATION_RESET: {
1050 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1051 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1052 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001053 }
1054 }
1055
1056 return false;
1057 }
1058
Christopher Tateb218e762017-04-05 16:34:07 -07001059 private PackageInfo getCallingPackageInfo(int userId) {
1060 try {
1061 return mPackageManager.getPackageInfo(getCallingPackage(),
1062 PackageManager.GET_SIGNATURES, userId);
1063 } catch (RemoteException e) {
1064 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1065 }
1066 }
1067
Svetoslav7ec28e82015-05-20 17:01:10 -07001068 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001069 if (DEBUG) {
1070 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1071 }
1072
1073 // Resolve the userId on whose behalf the call is made.
1074 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1075
Christopher Tateb218e762017-04-05 16:34:07 -07001076 // The relevant "calling package" userId will be the owning userId for some
1077 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1078 // up front who the effective "new SSAID" user ID for that settings name will be.
1079 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1080 Settings.Secure.ANDROID_ID);
1081 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1082
Svetoslav7ec28e82015-05-20 17:01:10 -07001083 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001084 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001085
Svetoslav7ec28e82015-05-20 17:01:10 -07001086 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001087
Svetoslav7ec28e82015-05-20 17:01:10 -07001088 String[] normalizedProjection = normalizeProjection(projection);
1089 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001090
Svetoslav7ec28e82015-05-20 17:01:10 -07001091 for (int i = 0; i < nameCount; i++) {
1092 String name = names.get(i);
1093 // Determine the owning user as some profile settings are cloned from the parent.
1094 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1095 name);
Svetoslav683914b2015-01-15 14:22:26 -08001096
Alex Klyubin1991f572017-03-03 14:08:36 -08001097 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1098 // This caller is not permitted to access this setting. Pretend the setting
1099 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001100 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001101 }
Svetoslav683914b2015-01-15 14:22:26 -08001102
Mark Rathjen7599f132017-01-23 14:15:54 -08001103 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001104 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1105 final Setting setting;
1106 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001107 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001108 } else {
1109 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1110 name);
1111 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001112 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001113 }
1114
Svetoslav7ec28e82015-05-20 17:01:10 -07001115 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001116 }
Svetoslav683914b2015-01-15 14:22:26 -08001117 }
1118
Svetoslav7ec28e82015-05-20 17:01:10 -07001119 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001120 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1121 }
1122
1123 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001124 if (DEBUG) {
1125 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1126 }
1127
1128 // Resolve the userId on whose behalf the call is made.
1129 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1130
Chad Brubakera6830e72017-04-28 17:34:36 -07001131 // Ensure the caller can access the setting.
1132 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1133
Svetoslav683914b2015-01-15 14:22:26 -08001134 // Determine the owning user as some profile settings are cloned from the parent.
1135 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1136
Alex Klyubin1991f572017-03-03 14:08:36 -08001137 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1138 // This caller is not permitted to access this setting. Pretend the setting doesn't
1139 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001140 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1141 owningUserId);
1142 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001143 }
1144
Christopher Tateb218e762017-04-05 16:34:07 -07001145 // As of Android O, the SSAID is read from an app-specific entry in table
1146 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1147 if (isNewSsaidSetting(name)) {
1148 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1149 synchronized (mLock) {
1150 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001151 }
Christopher Tateb218e762017-04-05 16:34:07 -07001152 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001153 if (enableOverride) {
1154 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1155 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1156 if (overridden != null) {
1157 return overridden;
1158 }
1159 }
1160 }
Mark Rathjend891f012017-01-19 04:10:37 +00001161
Christopher Tateb218e762017-04-05 16:34:07 -07001162 // Not the SSAID; do a straight lookup
1163 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001164 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 owningUserId, name);
1166 }
Svetoslav683914b2015-01-15 14:22:26 -08001167 }
1168
Mark Rathjend891f012017-01-19 04:10:37 +00001169 private boolean isNewSsaidSetting(String name) {
1170 return Settings.Secure.ANDROID_ID.equals(name)
1171 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1172 }
1173
Christopher Tateb218e762017-04-05 16:34:07 -07001174 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001175 // Get uid of caller (key) used to store ssaid value
1176 String name = Integer.toString(
1177 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1178
1179 if (DEBUG) {
1180 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1181 }
1182
1183 // Retrieve the ssaid from the table if present.
1184 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1185 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001186 // If the app is an Instant App use its stored SSAID instead of our own.
1187 final String instantSsaid;
1188 final long token = Binder.clearCallingIdentity();
1189 try {
1190 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1191 owningUserId);
1192 } catch (RemoteException e) {
1193 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1194 return null;
1195 } finally {
1196 Binder.restoreCallingIdentity(token);
1197 }
Svet Ganov96c99462017-05-05 14:27:13 -07001198
1199 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1200 SETTINGS_TYPE_SSAID, owningUserId);
1201
Chad Brubaker0d277a72017-04-12 16:56:53 -07001202 if (instantSsaid != null) {
1203 // Use the stored value if it is still valid.
1204 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001205 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001206 }
1207 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001208 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1209 true, callingPkg.packageName);
1210 if (!success) {
1211 throw new IllegalStateException("Failed to update instant app android id");
1212 }
Svet Ganov96c99462017-05-05 14:27:13 -07001213 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1214 owningUserId, name);
1215 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001216 }
Mark Rathjend891f012017-01-19 04:10:37 +00001217
1218 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001219 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001220 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1221 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001222 }
1223
Svet Ganov96c99462017-05-05 14:27:13 -07001224 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1225 }
1226
1227 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1228 // SSAID settings are located in a dedicated table for internal bookkeeping
1229 // but for the world they reside in the secure table, so adjust the key here.
1230 // We have a special name when looking it up but want the world to see it as
1231 // "android_id".
1232 if (ssaidSetting != null) {
1233 return settingsState.new Setting(ssaidSetting) {
1234 @Override
1235 public int getKey() {
1236 final int userId = getUserIdFromKey(super.getKey());
1237 return makeKey(SETTINGS_TYPE_SECURE, userId);
1238 }
1239
1240 @Override
1241 public String getName() {
1242 return Settings.Secure.ANDROID_ID;
1243 }
1244 };
1245 }
1246 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001247 }
1248
Makoto Onuki0000d322017-11-28 16:31:47 -08001249 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1250 synchronized (mLock) {
1251 final Setting setting = getGlobalSetting(
1252 Global.LOCATION_GLOBAL_KILL_SWITCH);
1253 if (!"1".equals(setting.getValue())) {
1254 return null;
1255 }
1256 // Global kill-switch is enabled. Return an empty value.
1257 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1258 SETTINGS_TYPE_SECURE, owningUserId);
1259 return settingsState.new Setting(
1260 Secure.LOCATION_PROVIDERS_ALLOWED,
1261 "", // value
1262 "", // tag
1263 "", // default value
1264 "", // package name
1265 false, // from system
1266 "0" // id
1267 ) {
1268 @Override
1269 public boolean update(String value, boolean setDefault, String packageName,
1270 String tag, boolean forceNonSystemPackage) {
1271 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1272 return false;
1273 }
1274 };
1275 }
1276 }
1277
Svetoslav Ganove080da92016-12-21 17:10:35 -08001278 private boolean insertSecureSetting(String name, String value, String tag,
1279 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001280 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001281 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001282 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1283 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001284 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001285 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1286 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001287 }
1288
Svet Ganov53a441c2016-04-19 19:38:00 -07001289 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001290 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001291 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1292 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001293 }
1294
Svetoslav Ganove080da92016-12-21 17:10:35 -08001295 return mutateSecureSetting(name, null, null, false, requestingUserId,
1296 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001297 }
1298
Svetoslav Ganove080da92016-12-21 17:10:35 -08001299 private boolean updateSecureSetting(String name, String value, String tag,
1300 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001301 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001302 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001303 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1304 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001305 }
1306
Svetoslav Ganove080da92016-12-21 17:10:35 -08001307 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1308 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001309 }
1310
Svetoslav Ganove080da92016-12-21 17:10:35 -08001311 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1312 if (DEBUG) {
1313 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1314 + mode + ", " + tag + ")");
1315 }
1316
1317 mutateSecureSetting(null, null, tag, false, requestingUserId,
1318 MUTATION_OPERATION_RESET, false, mode);
1319 }
1320
1321 private boolean mutateSecureSetting(String name, String value, String tag,
1322 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1323 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001324 // Make sure the caller can change the settings.
1325 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1326
Svetoslav683914b2015-01-15 14:22:26 -08001327 // Resolve the userId on whose behalf the call is made.
1328 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1329
Makoto Onuki28da2e32015-11-20 11:30:44 -08001330 // If this is a setting that is currently restricted for this user, do not allow
1331 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001332 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1333 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001334 return false;
1335 }
1336
1337 // Determine the owning user as some profile settings are cloned from the parent.
1338 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1339
1340 // Only the owning user can change the setting.
1341 if (owningUserId != callingUserId) {
1342 return false;
1343 }
1344
1345 // Special cases for location providers (sigh).
1346 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001347 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1348 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001349 }
1350
1351 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001352 synchronized (mLock) {
1353 switch (operation) {
1354 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001355 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001356 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001357 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001358 }
Svetoslav683914b2015-01-15 14:22:26 -08001359
Svetoslav7ec28e82015-05-20 17:01:10 -07001360 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001361 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001362 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001363 }
Svetoslav683914b2015-01-15 14:22:26 -08001364
Svetoslav7ec28e82015-05-20 17:01:10 -07001365 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001366 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001367 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001368 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001369 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001370
1371 case MUTATION_OPERATION_RESET: {
1372 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1373 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1374 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001375 }
1376 }
1377
1378 return false;
1379 }
1380
Svetoslav7ec28e82015-05-20 17:01:10 -07001381 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001382 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001383 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001384 }
1385
1386 // Resolve the userId on whose behalf the call is made.
1387 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1388
Svetoslav7ec28e82015-05-20 17:01:10 -07001389 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001390 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001391
Svetoslav7ec28e82015-05-20 17:01:10 -07001392 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001393
Svetoslav7ec28e82015-05-20 17:01:10 -07001394 String[] normalizedProjection = normalizeProjection(projection);
1395 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001396
Svetoslav7ec28e82015-05-20 17:01:10 -07001397 for (int i = 0; i < nameCount; i++) {
1398 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001399
Svetoslav7ec28e82015-05-20 17:01:10 -07001400 // Determine the owning user as some profile settings are cloned from the parent.
1401 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1402 name);
Svetoslav683914b2015-01-15 14:22:26 -08001403
Svetoslav7ec28e82015-05-20 17:01:10 -07001404 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001405 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001406 appendSettingToCursor(result, setting);
1407 }
1408
1409 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001410 }
Svetoslav683914b2015-01-15 14:22:26 -08001411 }
1412
Svetoslav7ec28e82015-05-20 17:01:10 -07001413 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001414 if (DEBUG) {
1415 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1416 }
1417
1418 // Resolve the userId on whose behalf the call is made.
1419 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1420
Chad Brubakera6830e72017-04-28 17:34:36 -07001421 // Ensure the caller can access the setting.
1422 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001423
Svetoslav683914b2015-01-15 14:22:26 -08001424 // Determine the owning user as some profile settings are cloned from the parent.
1425 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1426
1427 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001428 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001429 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001430 }
Svetoslav683914b2015-01-15 14:22:26 -08001431 }
1432
Svetoslav7ec28e82015-05-20 17:01:10 -07001433 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001434 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001435 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001436 + requestingUserId + ")");
1437 }
1438
Svetoslav7ec28e82015-05-20 17:01:10 -07001439 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001440 }
1441
Svetoslav7ec28e82015-05-20 17:01:10 -07001442 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001443 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001444 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001445 }
1446
Svetoslav7ec28e82015-05-20 17:01:10 -07001447 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001448 }
1449
Svetoslav7ec28e82015-05-20 17:01:10 -07001450 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001451 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001452 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001453 + requestingUserId + ")");
1454 }
1455
Svetoslav7ec28e82015-05-20 17:01:10 -07001456 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001457 }
1458
Svetoslav7ec28e82015-05-20 17:01:10 -07001459 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001460 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001461 if (!hasWriteSecureSettingsPermission()) {
1462 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1463 // operation is allowed for the calling package through appops.
1464 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1465 Binder.getCallingUid(), getCallingPackage(), true)) {
1466 return false;
1467 }
Svetoslav683914b2015-01-15 14:22:26 -08001468 }
1469
Svetoslav683914b2015-01-15 14:22:26 -08001470 // Resolve the userId on whose behalf the call is made.
1471 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1472
yuemingw1d13eae2018-01-30 17:27:54 +00001473 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1474 name, callingUserId, value, Binder.getCallingUid())) {
1475 return false;
1476 }
1477
Svetoslavd8d25e02015-11-20 13:09:26 -08001478 // Enforce what the calling package can mutate the system settings.
1479 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1480
Svetoslav683914b2015-01-15 14:22:26 -08001481 // Determine the owning user as some profile settings are cloned from the parent.
1482 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1483
1484 // Only the owning user id can change the setting.
1485 if (owningUserId != callingUserId) {
1486 return false;
1487 }
1488
Jeff Sharkey413573a2016-02-22 17:52:45 -07001489 // Invalidate any relevant cache files
1490 String cacheName = null;
1491 if (Settings.System.RINGTONE.equals(name)) {
1492 cacheName = Settings.System.RINGTONE_CACHE;
1493 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1494 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1495 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1496 cacheName = Settings.System.ALARM_ALERT_CACHE;
1497 }
1498 if (cacheName != null) {
1499 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001500 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001501 cacheFile.delete();
1502 }
1503
Svetoslav683914b2015-01-15 14:22:26 -08001504 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001505 synchronized (mLock) {
1506 switch (operation) {
1507 case MUTATION_OPERATION_INSERT: {
1508 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001509 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001510 owningUserId, name, value, null, false, getCallingPackage(),
1511 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001512 }
1513
1514 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001515 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001516 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001517 }
1518
1519 case MUTATION_OPERATION_UPDATE: {
1520 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001521 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001522 owningUserId, name, value, null, false, getCallingPackage(),
1523 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001524 }
Svetoslav683914b2015-01-15 14:22:26 -08001525 }
1526
Svetoslav7ec28e82015-05-20 17:01:10 -07001527 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001528 }
Svetoslav683914b2015-01-15 14:22:26 -08001529 }
1530
Billy Lau6ad2d662015-07-18 00:26:58 +01001531 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001532 // Write secure settings is a more protected permission. If caller has it we are good.
1533 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1534 == PackageManager.PERMISSION_GRANTED) {
1535 return true;
1536 }
1537
Svetoslavf41334b2015-06-23 12:06:03 -07001538 return false;
1539 }
1540
Svetoslav683914b2015-01-15 14:22:26 -08001541 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001542 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001543 if (validator != null && !validator.validate(value)) {
1544 throw new IllegalArgumentException("Invalid value: " + value
1545 + " for setting: " + name);
1546 }
1547 }
1548
Alex Klyubin1991f572017-03-03 14:08:36 -08001549 /**
1550 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1551 */
1552 private boolean isSecureSettingAccessible(String name, int callingUserId,
1553 int owningUserId) {
1554 // Special case for location (sigh).
1555 // This check is not inside the name-based checks below because this method performs checks
1556 // only if the calling user ID is not the same as the owning user ID.
1557 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1558 return false;
1559 }
1560
1561 switch (name) {
1562 case "bluetooth_address":
1563 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1564 // address in this secure setting. Secure settings can normally be read by any app,
1565 // which thus enables them to bypass the recently introduced restrictions on access
1566 // to device identifiers.
1567 // To mitigate this we make this setting available only to callers privileged to see
1568 // this device's MAC addresses, same as through public API
1569 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1570 return getContext().checkCallingOrSelfPermission(
1571 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1572 default:
1573 return true;
1574 }
1575 }
1576
Svetoslav683914b2015-01-15 14:22:26 -08001577 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1578 int owningUserId) {
1579 // Optimization - location providers are restricted only for managed profiles.
1580 if (callingUserId == owningUserId) {
1581 return false;
1582 }
1583 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1584 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1585 new UserHandle(callingUserId))) {
1586 return true;
1587 }
1588 return false;
1589 }
1590
Svetoslav683914b2015-01-15 14:22:26 -08001591 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1592 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1593 }
1594
1595 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001596 final int parentId;
1597 // Resolves dependency if setting has a dependency and the calling user has a parent
1598 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1599 && (parentId = getGroupParentLocked(userId)) != userId) {
1600 // The setting has a dependency and the profile has a parent
1601 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001602 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1603 final long token = Binder.clearCallingIdentity();
1604 try {
1605 Setting settingObj = getSecureSetting(dependency, userId);
1606 if (settingObj != null && settingObj.getValue().equals("1")) {
1607 return parentId;
1608 }
1609 } finally {
1610 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001611 }
1612 }
Svetoslav683914b2015-01-15 14:22:26 -08001613 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1614 }
1615
1616 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1617 final int parentId = getGroupParentLocked(userId);
1618 if (parentId != userId && keys.contains(name)) {
1619 return parentId;
1620 }
1621 return userId;
1622 }
1623
Svetoslavf41334b2015-06-23 12:06:03 -07001624 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001625 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001626 // System/root/shell can mutate whatever secure settings they want.
1627 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001628 final int appId = UserHandle.getAppId(callingUid);
1629 if (appId == android.os.Process.SYSTEM_UID
1630 || appId == Process.SHELL_UID
1631 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001632 return;
1633 }
1634
1635 switch (operation) {
1636 case MUTATION_OPERATION_INSERT:
1637 // Insert updates.
1638 case MUTATION_OPERATION_UPDATE: {
1639 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1640 return;
1641 }
1642
1643 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001644 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001645
1646 // Privileged apps can do whatever they want.
1647 if ((packageInfo.applicationInfo.privateFlags
1648 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1649 return;
1650 }
1651
1652 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1653 packageInfo.applicationInfo.targetSdkVersion, name);
1654 } break;
1655
1656 case MUTATION_OPERATION_DELETE: {
1657 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1658 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1659 throw new IllegalArgumentException("You cannot delete system defined"
1660 + " secure settings.");
1661 }
1662
1663 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001664 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001665
1666 // Privileged apps can do whatever they want.
1667 if ((packageInfo.applicationInfo.privateFlags &
1668 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1669 return;
1670 }
1671
1672 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1673 packageInfo.applicationInfo.targetSdkVersion, name);
1674 } break;
1675 }
1676 }
1677
Todd Kennedybe0b8892017-02-15 14:13:52 -08001678 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001679 switch (settingsType) {
1680 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001681 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001682 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001683 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001684 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001685 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001686 default:
1687 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1688 }
1689 }
1690
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001691 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1692 switch (settingsType) {
1693 case SETTINGS_TYPE_GLOBAL:
1694 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1695 case SETTINGS_TYPE_SYSTEM:
1696 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1697 case SETTINGS_TYPE_SECURE:
1698 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1699 default:
1700 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1701 }
1702 }
1703
Chad Brubaker97bccee2017-01-05 15:51:41 -08001704 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001705 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1706 // in the current form.
1707 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001708 }
1709
Chad Brubakera6830e72017-04-28 17:34:36 -07001710 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001711 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1712 return;
1713 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001714 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001715 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001716 return;
1717 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001718 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1719 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001720 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1721 // breakage in the current form.
1722 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1723 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001724 }
1725 }
1726
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001727 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1728 // We always use the callingUid for this lookup. This means that if hypothetically an
1729 // app was installed in user A with cross user and in user B as an Instant App
1730 // the app in A would be able to see all the settings in user B. However since cross
1731 // user is a system permission and the app must be uninstalled in B and then installed as
1732 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001733 ApplicationInfo ai = null;
1734 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001735 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1736 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001737 } catch (RemoteException ignored) {
1738 }
1739 if (ai == null) {
1740 throw new IllegalStateException("Failed to lookup info for package "
1741 + getCallingPackage());
1742 }
1743 return ai;
1744 }
1745
Xiaohui Chen43765b72015-08-31 10:57:33 -07001746 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001747 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001748 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1749 getCallingPackage(), 0, userId);
1750 if (packageInfo != null) {
1751 return packageInfo;
1752 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001753 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001754 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001755 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001756 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001757 }
1758
1759 private int getGroupParentLocked(int userId) {
1760 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001761 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001762 return userId;
1763 }
1764 // We are in the same process with the user manager and the returned
1765 // user info is a cached instance, so just look up instead of cache.
1766 final long identity = Binder.clearCallingIdentity();
1767 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001768 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001769 UserInfo userInfo = mUserManager.getProfileParent(userId);
1770 return (userInfo != null) ? userInfo.id : userId;
1771 } finally {
1772 Binder.restoreCallingIdentity(identity);
1773 }
1774 }
1775
Svetoslav683914b2015-01-15 14:22:26 -08001776 private void enforceWritePermission(String permission) {
1777 if (getContext().checkCallingOrSelfPermission(permission)
1778 != PackageManager.PERMISSION_GRANTED) {
1779 throw new SecurityException("Permission denial: writing to settings requires:"
1780 + permission);
1781 }
1782 }
1783
1784 /*
1785 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1786 * This setting contains a list of the currently enabled location providers.
1787 * But helper functions in android.providers.Settings can enable or disable
1788 * a single provider by using a "+" or "-" prefix before the provider name.
1789 *
yuemingw1d13eae2018-01-30 17:27:54 +00001790 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1791 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1792 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001793 *
Svetoslav683914b2015-01-15 14:22:26 -08001794 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001795 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001796 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1797 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001798 if (TextUtils.isEmpty(value)) {
1799 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001800 }
1801
Svetoslav683914b2015-01-15 14:22:26 -08001802 final char prefix = value.charAt(0);
1803 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001804 if (forceNotify) {
1805 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1806 mSettingsRegistry.notifyForSettingsChange(key,
1807 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1808 }
Svetoslav683914b2015-01-15 14:22:26 -08001809 return false;
1810 }
1811
1812 // skip prefix
1813 value = value.substring(1);
1814
Svetoslav7ec28e82015-05-20 17:01:10 -07001815 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001816 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001817 if (settingValue == null) {
1818 return false;
1819 }
Svetoslav683914b2015-01-15 14:22:26 -08001820
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001821 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001822
1823 int index = oldProviders.indexOf(value);
1824 int end = index + value.length();
1825
1826 // check for commas to avoid matching on partial string
1827 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1828 index = -1;
1829 }
1830
1831 // check for commas to avoid matching on partial string
1832 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1833 index = -1;
1834 }
1835
1836 String newProviders;
1837
1838 if (prefix == '+' && index < 0) {
1839 // append the provider to the list if not present
1840 if (oldProviders.length() == 0) {
1841 newProviders = value;
1842 } else {
1843 newProviders = oldProviders + ',' + value;
1844 }
1845 } else if (prefix == '-' && index >= 0) {
1846 // remove the provider from the list if present
1847 // remove leading or trailing comma
1848 if (index > 0) {
1849 index--;
1850 } else if (end < oldProviders.length()) {
1851 end++;
1852 }
1853
1854 newProviders = oldProviders.substring(0, index);
1855 if (end < oldProviders.length()) {
1856 newProviders += oldProviders.substring(end);
1857 }
1858 } else {
1859 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001860 if (forceNotify) {
1861 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1862 mSettingsRegistry.notifyForSettingsChange(key,
1863 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1864 }
Svetoslav683914b2015-01-15 14:22:26 -08001865 return false;
1866 }
1867
Svet Ganov53a441c2016-04-19 19:38:00 -07001868 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001869 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001870 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001871 }
1872
Svetoslav683914b2015-01-15 14:22:26 -08001873 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1874 int targetSdkVersion, String name) {
1875 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1876 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1877 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1878 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1879 + " This will soon become an error.");
1880 } else {
1881 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1882 + " This will soon become an error.");
1883 }
1884 } else {
1885 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1886 throw new IllegalArgumentException("You cannot change private secure settings.");
1887 } else {
1888 throw new IllegalArgumentException("You cannot keep your settings in"
1889 + " the secure settings.");
1890 }
1891 }
1892 }
1893
1894 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1895 if (requestingUserId == UserHandle.getCallingUserId()) {
1896 return requestingUserId;
1897 }
1898 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1899 Binder.getCallingUid(), requestingUserId, false, true,
1900 "get/set setting for user", null);
1901 }
1902
Svet Ganov53a441c2016-04-19 19:38:00 -07001903 private Bundle packageValueForCallResult(Setting setting,
1904 boolean trackingGeneration) {
1905 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001906 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001907 return NULL_SETTING_BUNDLE;
1908 }
1909 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001910 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001911 Bundle result = new Bundle();
1912 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001913 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001914
Svetoslav Ganove080da92016-12-21 17:10:35 -08001915 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001916 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001917 }
1918
1919 private static int getRequestingUserId(Bundle args) {
1920 final int callingUserId = UserHandle.getCallingUserId();
1921 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1922 : callingUserId;
1923 }
1924
Svet Ganov53a441c2016-04-19 19:38:00 -07001925 private boolean isTrackingGeneration(Bundle args) {
1926 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1927 }
1928
Svetoslav683914b2015-01-15 14:22:26 -08001929 private static String getSettingValue(Bundle args) {
1930 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1931 }
1932
Svetoslav Ganove080da92016-12-21 17:10:35 -08001933 private static String getSettingTag(Bundle args) {
1934 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1935 }
1936
1937 private static boolean getSettingMakeDefault(Bundle args) {
1938 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1939 }
1940
1941 private static int getResetModeEnforcingPermission(Bundle args) {
1942 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1943 switch (mode) {
1944 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1945 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1946 throw new SecurityException("Only system, shell/root on a "
1947 + "debuggable build can reset to untrusted defaults");
1948 }
1949 return mode;
1950 }
1951 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1952 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1953 throw new SecurityException("Only system, shell/root on a "
1954 + "debuggable build can reset untrusted changes");
1955 }
1956 return mode;
1957 }
1958 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1959 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1960 throw new SecurityException("Only system, shell/root on a "
1961 + "debuggable build can reset to trusted defaults");
1962 }
1963 return mode;
1964 }
1965 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1966 return mode;
1967 }
1968 }
1969 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1970 }
1971
1972 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1973 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1974 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1975 && (appId == SHELL_UID || appId == ROOT_UID));
1976 }
1977
Svetoslav683914b2015-01-15 14:22:26 -08001978 private static String getValidTableOrThrow(Uri uri) {
1979 if (uri.getPathSegments().size() > 0) {
1980 String table = uri.getPathSegments().get(0);
1981 if (DatabaseHelper.isValidTable(table)) {
1982 return table;
1983 }
1984 throw new IllegalArgumentException("Bad root path: " + table);
1985 }
1986 throw new IllegalArgumentException("Invalid URI:" + uri);
1987 }
1988
1989 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001990 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001991 return new MatrixCursor(projection, 0);
1992 }
1993 MatrixCursor cursor = new MatrixCursor(projection, 1);
1994 appendSettingToCursor(cursor, setting);
1995 return cursor;
1996 }
1997
1998 private static String[] normalizeProjection(String[] projection) {
1999 if (projection == null) {
2000 return ALL_COLUMNS;
2001 }
2002
2003 final int columnCount = projection.length;
2004 for (int i = 0; i < columnCount; i++) {
2005 String column = projection[i];
2006 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2007 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002008 }
2009 }
2010
Svetoslav683914b2015-01-15 14:22:26 -08002011 return projection;
2012 }
2013
2014 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002015 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002016 return;
2017 }
Svetoslav683914b2015-01-15 14:22:26 -08002018 final int columnCount = cursor.getColumnCount();
2019
2020 String[] values = new String[columnCount];
2021
2022 for (int i = 0; i < columnCount; i++) {
2023 String column = cursor.getColumnName(i);
2024
2025 switch (column) {
2026 case Settings.NameValueTable._ID: {
2027 values[i] = setting.getId();
2028 } break;
2029
2030 case Settings.NameValueTable.NAME: {
2031 values[i] = setting.getName();
2032 } break;
2033
2034 case Settings.NameValueTable.VALUE: {
2035 values[i] = setting.getValue();
2036 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002037 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002038 }
2039
Svetoslav683914b2015-01-15 14:22:26 -08002040 cursor.addRow(values);
2041 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002042
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002043 private static boolean isKeyValid(String key) {
2044 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2045 }
2046
Svetoslav683914b2015-01-15 14:22:26 -08002047 private static final class Arguments {
2048 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2049 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2050
2051 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2052 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2053
2054 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2055 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2056
2057 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2058 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2059
2060 public final String table;
2061 public final String name;
2062
2063 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2064 final int segmentSize = uri.getPathSegments().size();
2065 switch (segmentSize) {
2066 case 1: {
2067 if (where != null
2068 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2069 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2070 && whereArgs.length == 1) {
2071 name = whereArgs[0];
2072 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002073 return;
Svetoslav683914b2015-01-15 14:22:26 -08002074 } else if (where != null
2075 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2076 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2077 final int startIndex = Math.max(where.indexOf("'"),
2078 where.indexOf("\"")) + 1;
2079 final int endIndex = Math.max(where.lastIndexOf("'"),
2080 where.lastIndexOf("\""));
2081 name = where.substring(startIndex, endIndex);
2082 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002083 return;
Svetoslav683914b2015-01-15 14:22:26 -08002084 } else if (supportAll && where == null && whereArgs == null) {
2085 name = null;
2086 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002087 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002088 }
Svetoslav683914b2015-01-15 14:22:26 -08002089 } break;
2090
Svetoslav28494652015-02-12 14:11:42 -08002091 case 2: {
2092 if (where == null && whereArgs == null) {
2093 name = uri.getPathSegments().get(1);
2094 table = computeTableForSetting(uri, name);
2095 return;
2096 }
2097 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002098 }
Svetoslav28494652015-02-12 14:11:42 -08002099
2100 EventLogTags.writeUnsupportedSettingsQuery(
2101 uri.toSafeString(), where, Arrays.toString(whereArgs));
2102 String message = String.format( "Supported SQL:\n"
2103 + " uri content://some_table/some_property with null where and where args\n"
2104 + " uri content://some_table with query name=? and single name as arg\n"
2105 + " uri content://some_table with query name=some_name and null args\n"
2106 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2107 Arrays.toString(whereArgs));
2108 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002109 }
2110
Svetoslav28494652015-02-12 14:11:42 -08002111 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002112 String table = getValidTableOrThrow(uri);
2113
2114 if (name != null) {
2115 if (sSystemMovedToSecureSettings.contains(name)) {
2116 table = TABLE_SECURE;
2117 }
2118
2119 if (sSystemMovedToGlobalSettings.contains(name)) {
2120 table = TABLE_GLOBAL;
2121 }
2122
2123 if (sSecureMovedToGlobalSettings.contains(name)) {
2124 table = TABLE_GLOBAL;
2125 }
2126
2127 if (sGlobalMovedToSecureSettings.contains(name)) {
2128 table = TABLE_SECURE;
2129 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002130 }
Svetoslav683914b2015-01-15 14:22:26 -08002131
2132 return table;
2133 }
2134 }
2135
2136 final class SettingsRegistry {
2137 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2138
Svetoslav683914b2015-01-15 14:22:26 -08002139 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2140 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2141 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002142 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2143
2144 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002145
2146 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2147
Svet Ganov53a441c2016-04-19 19:38:00 -07002148 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002149
Svetoslav7e0683b2015-08-03 16:02:52 -07002150 private final Handler mHandler;
2151
Svet Ganov53a441c2016-04-19 19:38:00 -07002152 private final BackupManager mBackupManager;
2153
Amith Yamasani39452022017-03-21 15:23:47 -07002154 private String mSettingsCreationBuildId;
2155
Svetoslav683914b2015-01-15 14:22:26 -08002156 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002157 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002158 mGenerationRegistry = new GenerationRegistry(mLock);
2159 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002160 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002161 syncSsaidTableOnStart();
2162 }
2163
2164 private void generateUserKeyLocked(int userId) {
2165 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002166 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002167 final SecureRandom rand = new SecureRandom();
2168 rand.nextBytes(keyBytes);
2169
2170 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002171 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002172
2173 // Store the key in the ssaid table.
2174 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2175 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2176 true, SettingsState.SYSTEM_PACKAGE_NAME);
2177
2178 if (!success) {
2179 throw new IllegalStateException("Ssaid settings not accessible");
2180 }
2181 }
2182
Mark Rathjen7599f132017-01-23 14:15:54 -08002183 private byte[] getLengthPrefix(byte[] data) {
2184 return ByteBuffer.allocate(4).putInt(data.length).array();
2185 }
2186
Christopher Tateb218e762017-04-05 16:34:07 -07002187 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002188 // Read the user's key from the ssaid table.
2189 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002190 if (userKeySetting == null || userKeySetting.isNull()
2191 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002192 // Lazy initialize and store the user key.
2193 generateUserKeyLocked(userId);
2194 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002195 if (userKeySetting == null || userKeySetting.isNull()
2196 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002197 throw new IllegalStateException("User key not accessible");
2198 }
2199 }
2200 final String userKey = userKeySetting.getValue();
2201
2202 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002203 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2204
2205 // Validate that the key is of expected length.
2206 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2207 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002208 throw new IllegalStateException("User key invalid");
2209 }
2210
Mark Rathjen7599f132017-01-23 14:15:54 -08002211 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002212 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002213 m = Mac.getInstance("HmacSHA256");
2214 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002215 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002216 throw new IllegalStateException("HmacSHA256 is not available", e);
2217 } catch (InvalidKeyException e) {
2218 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002219 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002220
Mark Rathjenf42dd912017-06-05 19:04:34 -07002221 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002222 for (int i = 0; i < callingPkg.signatures.length; i++) {
2223 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002224 m.update(getLengthPrefix(sig), 0, 4);
2225 m.update(sig);
2226 }
Mark Rathjend891f012017-01-19 04:10:37 +00002227
2228 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002229 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2230 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002231
2232 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002233 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002234 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2235 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002236 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002237
2238 if (!success) {
2239 throw new IllegalStateException("Ssaid settings not accessible");
2240 }
2241
2242 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2243 }
2244
2245 public void syncSsaidTableOnStart() {
2246 synchronized (mLock) {
2247 // Verify that each user's packages and ssaid's are in sync.
2248 for (UserInfo user : mUserManager.getUsers(true)) {
2249 // Get all uids for the user's packages.
2250 final List<PackageInfo> packages;
2251 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002252 packages = mPackageManager.getInstalledPackages(
2253 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2254 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002255 } catch (RemoteException e) {
2256 throw new IllegalStateException("Package manager not available");
2257 }
2258 final Set<String> appUids = new HashSet<>();
2259 for (PackageInfo info : packages) {
2260 appUids.add(Integer.toString(info.applicationInfo.uid));
2261 }
2262
2263 // Get all uids currently stored in the user's ssaid table.
2264 final Set<String> ssaidUids = new HashSet<>(
2265 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2266 ssaidUids.remove(SSAID_USER_KEY);
2267
2268 // Perform a set difference for the appUids and ssaidUids.
2269 ssaidUids.removeAll(appUids);
2270
2271 // If there are ssaidUids left over they need to be removed from the table.
2272 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2273 user.id);
2274 for (String uid : ssaidUids) {
2275 ssaidSettings.deleteSettingLocked(uid);
2276 }
2277 }
2278 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002279 }
2280
Svetoslav683914b2015-01-15 14:22:26 -08002281 public List<String> getSettingsNamesLocked(int type, int userId) {
2282 final int key = makeKey(type, userId);
2283 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002284 if (settingsState == null) {
2285 return new ArrayList<String>();
2286 }
Svetoslav683914b2015-01-15 14:22:26 -08002287 return settingsState.getSettingNamesLocked();
2288 }
2289
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002290 public SparseBooleanArray getKnownUsersLocked() {
2291 SparseBooleanArray users = new SparseBooleanArray();
2292 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2293 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2294 }
2295 return users;
2296 }
2297
Kweku Adamsb0886f32017-10-31 15:32:09 -07002298 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002299 public SettingsState getSettingsLocked(int type, int userId) {
2300 final int key = makeKey(type, userId);
2301 return peekSettingsStateLocked(key);
2302 }
2303
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002304 public boolean ensureSettingsForUserLocked(int userId) {
2305 // First make sure this user actually exists.
2306 if (mUserManager.getUserInfo(userId) == null) {
2307 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2308 return false;
2309 }
2310
Svetoslav683914b2015-01-15 14:22:26 -08002311 // Migrate the setting for this user if needed.
2312 migrateLegacySettingsForUserIfNeededLocked(userId);
2313
2314 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002315 if (userId == UserHandle.USER_SYSTEM) {
2316 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002317 ensureSettingsStateLocked(globalKey);
2318 }
2319
2320 // Ensure secure settings loaded.
2321 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2322 ensureSettingsStateLocked(secureKey);
2323
2324 // Make sure the secure settings have an Android id set.
2325 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2326 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2327
2328 // Ensure system settings loaded.
2329 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2330 ensureSettingsStateLocked(systemKey);
2331
Mark Rathjend891f012017-01-19 04:10:37 +00002332 // Ensure secure settings loaded.
2333 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2334 ensureSettingsStateLocked(ssaidKey);
2335
Svetoslav683914b2015-01-15 14:22:26 -08002336 // Upgrade the settings to the latest version.
2337 UpgradeController upgrader = new UpgradeController(userId);
2338 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002339 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002340 }
2341
2342 private void ensureSettingsStateLocked(int key) {
2343 if (mSettingsStates.get(key) == null) {
2344 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002345 SettingsState settingsState = new SettingsState(getContext(), mLock,
2346 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002347 mSettingsStates.put(key, settingsState);
2348 }
2349 }
2350
2351 public void removeUserStateLocked(int userId, boolean permanently) {
2352 // We always keep the global settings in memory.
2353
2354 // Nuke system settings.
2355 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2356 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2357 if (systemSettingsState != null) {
2358 if (permanently) {
2359 mSettingsStates.remove(systemKey);
2360 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002361 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002362 systemSettingsState.destroyLocked(new Runnable() {
2363 @Override
2364 public void run() {
2365 mSettingsStates.remove(systemKey);
2366 }
2367 });
2368 }
2369 }
2370
2371 // Nuke secure settings.
2372 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2373 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2374 if (secureSettingsState != null) {
2375 if (permanently) {
2376 mSettingsStates.remove(secureKey);
2377 secureSettingsState.destroyLocked(null);
2378 } else {
2379 secureSettingsState.destroyLocked(new Runnable() {
2380 @Override
2381 public void run() {
2382 mSettingsStates.remove(secureKey);
2383 }
2384 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002385 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002386 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002387
Mark Rathjend891f012017-01-19 04:10:37 +00002388 // Nuke ssaid settings.
2389 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2390 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2391 if (ssaidSettingsState != null) {
2392 if (permanently) {
2393 mSettingsStates.remove(ssaidKey);
2394 ssaidSettingsState.destroyLocked(null);
2395 } else {
2396 ssaidSettingsState.destroyLocked(new Runnable() {
2397 @Override
2398 public void run() {
2399 mSettingsStates.remove(ssaidKey);
2400 }
2401 });
2402 }
2403 }
2404
Svet Ganov53a441c2016-04-19 19:38:00 -07002405 // Nuke generation tracking data
2406 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002407 }
2408
Svetoslav683914b2015-01-15 14:22:26 -08002409 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002410 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2411 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002412 final int key = makeKey(type, userId);
2413
Svetoslav Ganove080da92016-12-21 17:10:35 -08002414 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002415 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002416 if (settingsState != null) {
2417 success = settingsState.insertSettingLocked(name, value,
2418 tag, makeDefault, packageName);
2419 }
Svetoslav683914b2015-01-15 14:22:26 -08002420
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002421 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2422 settingsState.persistSyncLocked();
2423 }
2424
Svet Ganov53a441c2016-04-19 19:38:00 -07002425 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002426 notifyForSettingsChange(key, name);
2427 }
2428 return success;
2429 }
2430
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002431 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2432 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002433 final int key = makeKey(type, userId);
2434
Svetoslav Ganove080da92016-12-21 17:10:35 -08002435 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002436 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002437 if (settingsState != null) {
2438 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002439 }
Svetoslav683914b2015-01-15 14:22:26 -08002440
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002441 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2442 settingsState.persistSyncLocked();
2443 }
2444
Svet Ganov53a441c2016-04-19 19:38:00 -07002445 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002446 notifyForSettingsChange(key, name);
2447 }
2448 return success;
2449 }
2450
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002451 public boolean updateSettingLocked(int type, int userId, String name, String value,
2452 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2453 Set<String> criticalSettings) {
2454 final int key = makeKey(type, userId);
2455
2456 boolean success = false;
2457 SettingsState settingsState = peekSettingsStateLocked(key);
2458 if (settingsState != null) {
2459 success = settingsState.updateSettingLocked(name, value, tag,
2460 makeDefault, packageName);
2461 }
2462
2463 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2464 settingsState.persistSyncLocked();
2465 }
2466
2467 if (forceNotify || success) {
2468 notifyForSettingsChange(key, name);
2469 }
2470
2471 return success;
2472 }
2473
Svetoslav683914b2015-01-15 14:22:26 -08002474 public Setting getSettingLocked(int type, int userId, String name) {
2475 final int key = makeKey(type, userId);
2476
2477 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002478 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002479 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002480 }
Mark Rathjend891f012017-01-19 04:10:37 +00002481
2482 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002483 return settingsState.getSettingLocked(name);
2484 }
2485
Svetoslav Ganove080da92016-12-21 17:10:35 -08002486 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2487 String tag) {
2488 final int key = makeKey(type, userId);
2489 SettingsState settingsState = peekSettingsStateLocked(key);
2490 if (settingsState == null) {
2491 return;
2492 }
2493
2494 switch (mode) {
2495 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2496 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002497 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002498 Setting setting = settingsState.getSettingLocked(name);
2499 if (packageName.equals(setting.getPackageName())) {
2500 if (tag != null && !tag.equals(setting.getTag())) {
2501 continue;
2502 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002503 if (settingsState.resetSettingLocked(name)) {
2504 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002505 notifyForSettingsChange(key, name);
2506 }
2507 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002508 if (someSettingChanged) {
2509 settingsState.persistSyncLocked();
2510 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002511 }
2512 } break;
2513
2514 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2515 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002516 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002517 Setting setting = settingsState.getSettingLocked(name);
2518 if (!SettingsState.isSystemPackage(getContext(),
2519 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002520 if (settingsState.resetSettingLocked(name)) {
2521 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002522 notifyForSettingsChange(key, name);
2523 }
2524 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002525 if (someSettingChanged) {
2526 settingsState.persistSyncLocked();
2527 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002528 }
2529 } break;
2530
2531 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2532 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002533 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002534 Setting setting = settingsState.getSettingLocked(name);
2535 if (!SettingsState.isSystemPackage(getContext(),
2536 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002537 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002538 if (settingsState.resetSettingLocked(name)) {
2539 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002540 notifyForSettingsChange(key, name);
2541 }
2542 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002543 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002544 notifyForSettingsChange(key, name);
2545 }
2546 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002547 if (someSettingChanged) {
2548 settingsState.persistSyncLocked();
2549 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002550 }
2551 } break;
2552
2553 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2554 for (String name : settingsState.getSettingNamesLocked()) {
2555 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002556 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002557 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002558 if (settingsState.resetSettingLocked(name)) {
2559 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002560 notifyForSettingsChange(key, name);
2561 }
2562 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002563 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002564 notifyForSettingsChange(key, name);
2565 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002566 if (someSettingChanged) {
2567 settingsState.persistSyncLocked();
2568 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002569 }
2570 } break;
2571 }
2572 }
2573
Svetoslav683914b2015-01-15 14:22:26 -08002574 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002575 // Global and secure settings are signature protected. Apps signed
2576 // by the platform certificate are generally not uninstalled and
2577 // the main exception is tests. We trust components signed
2578 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002579
2580 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2581 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002582 if (systemSettings != null) {
2583 systemSettings.onPackageRemovedLocked(packageName);
2584 }
Svetoslav683914b2015-01-15 14:22:26 -08002585 }
2586
Mark Rathjend891f012017-01-19 04:10:37 +00002587 public void onUidRemovedLocked(int uid) {
2588 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2589 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002590 if (ssaidSettings != null) {
2591 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2592 }
Mark Rathjend891f012017-01-19 04:10:37 +00002593 }
2594
Kweku Adamsb0886f32017-10-31 15:32:09 -07002595 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002596 private SettingsState peekSettingsStateLocked(int key) {
2597 SettingsState settingsState = mSettingsStates.get(key);
2598 if (settingsState != null) {
2599 return settingsState;
2600 }
2601
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002602 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2603 return null;
2604 }
Svetoslav683914b2015-01-15 14:22:26 -08002605 return mSettingsStates.get(key);
2606 }
2607
2608 private void migrateAllLegacySettingsIfNeeded() {
2609 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002610 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002611 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002612 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002613 return;
2614 }
2615
Amith Yamasani39452022017-03-21 15:23:47 -07002616 mSettingsCreationBuildId = Build.ID;
2617
Svetoslav683914b2015-01-15 14:22:26 -08002618 final long identity = Binder.clearCallingIdentity();
2619 try {
2620 List<UserInfo> users = mUserManager.getUsers(true);
2621
2622 final int userCount = users.size();
2623 for (int i = 0; i < userCount; i++) {
2624 final int userId = users.get(i).id;
2625
2626 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2627 SQLiteDatabase database = dbHelper.getWritableDatabase();
2628 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2629
2630 // Upgrade to the latest version.
2631 UpgradeController upgrader = new UpgradeController(userId);
2632 upgrader.upgradeIfNeededLocked();
2633
2634 // Drop from memory if not a running user.
2635 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2636 removeUserStateLocked(userId, false);
2637 }
2638 }
2639 } finally {
2640 Binder.restoreCallingIdentity(identity);
2641 }
2642 }
2643 }
2644
2645 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2646 // Every user has secure settings and if no file we need to migrate.
2647 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2648 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002649 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002650 return;
2651 }
2652
2653 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2654 SQLiteDatabase database = dbHelper.getWritableDatabase();
2655
2656 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2657 }
2658
2659 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2660 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002661 // Move over the system settings.
2662 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2663 ensureSettingsStateLocked(systemKey);
2664 SettingsState systemSettings = mSettingsStates.get(systemKey);
2665 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2666 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002667
2668 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002669 // Do this after System settings, since this is the first thing we check when deciding
2670 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002671 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2672 ensureSettingsStateLocked(secureKey);
2673 SettingsState secureSettings = mSettingsStates.get(secureKey);
2674 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2675 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2676 secureSettings.persistSyncLocked();
2677
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002678 // Move over the global settings if owner.
2679 // Do this last, since this is the first thing we check when deciding
2680 // to skip over migration from db to xml for owner user.
2681 if (userId == UserHandle.USER_SYSTEM) {
2682 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2683 ensureSettingsStateLocked(globalKey);
2684 SettingsState globalSettings = mSettingsStates.get(globalKey);
2685 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002686 // If this was just created
2687 if (mSettingsCreationBuildId != null) {
2688 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2689 mSettingsCreationBuildId, null, true,
2690 SettingsState.SYSTEM_PACKAGE_NAME);
2691 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002692 globalSettings.persistSyncLocked();
2693 }
Svetoslav683914b2015-01-15 14:22:26 -08002694
2695 // Drop the database as now all is moved and persisted.
2696 if (DROP_DATABASE_ON_MIGRATION) {
2697 dbHelper.dropDatabase();
2698 } else {
2699 dbHelper.backupDatabase();
2700 }
2701 }
2702
2703 private void migrateLegacySettingsLocked(SettingsState settingsState,
2704 SQLiteDatabase database, String table) {
2705 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2706 queryBuilder.setTables(table);
2707
2708 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2709 null, null, null, null, null);
2710
2711 if (cursor == null) {
2712 return;
2713 }
2714
2715 try {
2716 if (!cursor.moveToFirst()) {
2717 return;
2718 }
2719
2720 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2721 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2722
2723 settingsState.setVersionLocked(database.getVersion());
2724
2725 while (!cursor.isAfterLast()) {
2726 String name = cursor.getString(nameColumnIdx);
2727 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002728 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002729 SettingsState.SYSTEM_PACKAGE_NAME);
2730 cursor.moveToNext();
2731 }
2732 } finally {
2733 cursor.close();
2734 }
2735 }
2736
2737 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2738 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2739
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002740 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002741 return;
2742 }
2743
2744 final int userId = getUserIdFromKey(secureSettings.mKey);
2745
2746 final UserInfo user;
2747 final long identity = Binder.clearCallingIdentity();
2748 try {
2749 user = mUserManager.getUserInfo(userId);
2750 } finally {
2751 Binder.restoreCallingIdentity(identity);
2752 }
2753 if (user == null) {
2754 // Can happen due to races when deleting users - treat as benign.
2755 return;
2756 }
2757
2758 String androidId = Long.toHexString(new SecureRandom().nextLong());
2759 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002760 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002761
2762 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2763 + "] for user " + userId);
2764
2765 // Write a drop box entry if it's a restricted profile
2766 if (user.isRestricted()) {
2767 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2768 Context.DROPBOX_SERVICE);
2769 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2770 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2771 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2772 }
2773 }
2774 }
2775
2776 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002777 final int userId = getUserIdFromKey(key);
2778 Uri uri = getNotificationUriFor(key, name);
2779
Phil Weaver83fec002016-05-11 10:55:29 -07002780 mGenerationRegistry.incrementGeneration(key);
2781
Svetoslav7e0683b2015-08-03 16:02:52 -07002782 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2783 userId, 0, uri).sendToTarget();
2784
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002785 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002786 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2787 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002788 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2789 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002790 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002791 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2792 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002793 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002794
Svet Ganov53a441c2016-04-19 19:38:00 -07002795 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Makoto Onuki0000d322017-11-28 16:31:47 -08002796
2797 // When the global kill switch is updated, send the change notification for
2798 // the location setting.
2799 if (isGlobalSettingsKey(key) && Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2800 notifyLocationChangeForRunningUsers();
2801 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002802 }
2803
Svet Ganov53a441c2016-04-19 19:38:00 -07002804 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002805 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002806 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002807 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002808 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002809 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002810 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002811 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002812 final int key = makeKey(type, profileId);
2813 mGenerationRegistry.incrementGeneration(key);
2814
2815 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002816 }
2817 }
2818 }
Svetoslav683914b2015-01-15 14:22:26 -08002819 }
2820
Makoto Onuki0000d322017-11-28 16:31:47 -08002821 private void notifyLocationChangeForRunningUsers() {
2822 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2823
2824 for (int i = 0; i < users.size(); i++) {
2825 final int userId = users.get(i).id;
2826
Makoto Onuki8e498252018-01-22 17:00:00 -08002827 // Do we have to increment the generation for users that are not running?
2828 // Yeah let's assume so...
2829 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2830 mGenerationRegistry.incrementGeneration(key);
2831
Makoto Onuki0000d322017-11-28 16:31:47 -08002832 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2833 continue;
2834 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002835 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
2836
2837 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2838 userId, 0, uri).sendToTarget();
2839 }
2840 }
2841
Svetoslav683914b2015-01-15 14:22:26 -08002842 private boolean isGlobalSettingsKey(int key) {
2843 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2844 }
2845
2846 private boolean isSystemSettingsKey(int key) {
2847 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2848 }
2849
2850 private boolean isSecureSettingsKey(int key) {
2851 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2852 }
2853
Mark Rathjend891f012017-01-19 04:10:37 +00002854 private boolean isSsaidSettingsKey(int key) {
2855 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2856 }
2857
Svetoslav683914b2015-01-15 14:22:26 -08002858 private File getSettingsFile(int key) {
2859 if (isGlobalSettingsKey(key)) {
2860 final int userId = getUserIdFromKey(key);
2861 return new File(Environment.getUserSystemDirectory(userId),
2862 SETTINGS_FILE_GLOBAL);
2863 } else if (isSystemSettingsKey(key)) {
2864 final int userId = getUserIdFromKey(key);
2865 return new File(Environment.getUserSystemDirectory(userId),
2866 SETTINGS_FILE_SYSTEM);
2867 } else if (isSecureSettingsKey(key)) {
2868 final int userId = getUserIdFromKey(key);
2869 return new File(Environment.getUserSystemDirectory(userId),
2870 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002871 } else if (isSsaidSettingsKey(key)) {
2872 final int userId = getUserIdFromKey(key);
2873 return new File(Environment.getUserSystemDirectory(userId),
2874 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002875 } else {
2876 throw new IllegalArgumentException("Invalid settings key:" + key);
2877 }
2878 }
2879
2880 private Uri getNotificationUriFor(int key, String name) {
2881 if (isGlobalSettingsKey(key)) {
2882 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2883 : Settings.Global.CONTENT_URI;
2884 } else if (isSecureSettingsKey(key)) {
2885 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2886 : Settings.Secure.CONTENT_URI;
2887 } else if (isSystemSettingsKey(key)) {
2888 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2889 : Settings.System.CONTENT_URI;
2890 } else {
2891 throw new IllegalArgumentException("Invalid settings key:" + key);
2892 }
2893 }
2894
2895 private int getMaxBytesPerPackageForType(int type) {
2896 switch (type) {
2897 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002898 case SETTINGS_TYPE_SECURE:
2899 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002900 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2901 }
2902
2903 default: {
2904 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2905 }
2906 }
2907 }
2908
Svetoslav7e0683b2015-08-03 16:02:52 -07002909 private final class MyHandler extends Handler {
2910 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2911 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2912
2913 public MyHandler(Looper looper) {
2914 super(looper);
2915 }
2916
2917 @Override
2918 public void handleMessage(Message msg) {
2919 switch (msg.what) {
2920 case MSG_NOTIFY_URI_CHANGED: {
2921 final int userId = msg.arg1;
2922 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002923 try {
2924 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2925 } catch (SecurityException e) {
2926 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2927 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002928 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002929 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2930 }
2931 } break;
2932
2933 case MSG_NOTIFY_DATA_CHANGED: {
2934 mBackupManager.dataChanged();
2935 } break;
2936 }
2937 }
2938 }
2939
Svetoslav683914b2015-01-15 14:22:26 -08002940 private final class UpgradeController {
Pavel Grafovc5c97302018-03-19 13:37:15 +00002941 private static final int SETTINGS_VERSION = 160;
Svetoslav683914b2015-01-15 14:22:26 -08002942
2943 private final int mUserId;
2944
2945 public UpgradeController(int userId) {
2946 mUserId = userId;
2947 }
2948
2949 public void upgradeIfNeededLocked() {
2950 // The version of all settings for a user is the same (all users have secure).
2951 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002952 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002953
2954 // Try an update from the current state.
2955 final int oldVersion = secureSettings.getVersionLocked();
2956 final int newVersion = SETTINGS_VERSION;
2957
Svet Ganovc9755bc2015-03-28 13:21:22 -07002958 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002959 if (oldVersion == newVersion) {
2960 return;
2961 }
2962
2963 // Try to upgrade.
2964 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2965
2966 // If upgrade failed start from scratch and upgrade.
2967 if (curVersion != newVersion) {
2968 // Drop state we have for this user.
2969 removeUserStateLocked(mUserId, true);
2970
2971 // Recreate the database.
2972 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2973 SQLiteDatabase database = dbHelper.getWritableDatabase();
2974 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2975
2976 // Migrate the settings for this user.
2977 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2978
2979 // Now upgrade should work fine.
2980 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002981
2982 // Make a note what happened, so we don't wonder why data was lost
2983 String reason = "Settings rebuilt! Current version: "
2984 + curVersion + " while expected: " + newVersion;
2985 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002986 Settings.Global.DATABASE_DOWNGRADE_REASON,
2987 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002988 }
2989
2990 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002991 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002992 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002993 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002994 globalSettings.setVersionLocked(newVersion);
2995 }
2996
2997 // Set the secure settings version.
2998 secureSettings.setVersionLocked(newVersion);
2999
3000 // Set the system settings version.
3001 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003002 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003003 systemSettings.setVersionLocked(newVersion);
3004 }
3005
3006 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003007 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003008 }
3009
3010 private SettingsState getSecureSettingsLocked(int userId) {
3011 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3012 }
3013
Mark Rathjend891f012017-01-19 04:10:37 +00003014 private SettingsState getSsaidSettingsLocked(int userId) {
3015 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3016 }
3017
Svetoslav683914b2015-01-15 14:22:26 -08003018 private SettingsState getSystemSettingsLocked(int userId) {
3019 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3020 }
3021
Jeff Brown503cffc2015-03-26 18:08:51 -07003022 /**
3023 * You must perform all necessary mutations to bring the settings
3024 * for this user from the old to the new version. When you add a new
3025 * upgrade step you *must* update SETTINGS_VERSION.
3026 *
3027 * This is an example of moving a setting from secure to global.
3028 *
3029 * // v119: Example settings changes.
3030 * if (currentVersion == 118) {
3031 * if (userId == UserHandle.USER_OWNER) {
3032 * // Remove from the secure settings.
3033 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3034 * String name = "example_setting_to_move";
3035 * String value = secureSettings.getSetting(name);
3036 * secureSettings.deleteSetting(name);
3037 *
3038 * // Add to the global settings.
3039 * SettingsState globalSettings = getGlobalSettingsLocked();
3040 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3041 * }
3042 *
3043 * // Update the current version.
3044 * currentVersion = 119;
3045 * }
3046 */
Svetoslav683914b2015-01-15 14:22:26 -08003047 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3048 if (DEBUG) {
3049 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3050 + oldVersion + " to version: " + newVersion);
3051 }
3052
Jeff Brown503cffc2015-03-26 18:08:51 -07003053 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003054
John Spurlocke11ae112015-05-11 16:09:03 -04003055 // v119: Reset zen + ringer mode.
3056 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003057 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003058 final SettingsState globalSettings = getGlobalSettingsLocked();
3059 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003060 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3061 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003062 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003063 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3064 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003065 }
3066 currentVersion = 119;
3067 }
3068
Jason Monk27bbb2d2015-03-31 16:46:39 -04003069 // v120: Add double tap to wake setting.
3070 if (currentVersion == 119) {
3071 SettingsState secureSettings = getSecureSettingsLocked(userId);
3072 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3073 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003074 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003075 SettingsState.SYSTEM_PACKAGE_NAME);
3076
3077 currentVersion = 120;
3078 }
3079
Svetoslav7e0683b2015-08-03 16:02:52 -07003080 if (currentVersion == 120) {
3081 // Before 121, we used a different string encoding logic. We just bump the
3082 // version here; SettingsState knows how to handle pre-version 120 files.
3083 currentVersion = 121;
3084 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003085
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003086 if (currentVersion == 121) {
3087 // Version 122: allow OEMs to set a default payment component in resources.
3088 // Note that we only write the default if no default has been set;
3089 // if there is, we just leave the default at whatever it currently is.
3090 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3091 String defaultComponent = (getContext().getResources().getString(
3092 R.string.def_nfc_payment_component));
3093 Setting currentSetting = secureSettings.getSettingLocked(
3094 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3095 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003096 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003097 secureSettings.insertSettingLocked(
3098 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003099 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003100 }
3101 currentVersion = 122;
3102 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003103
3104 if (currentVersion == 122) {
3105 // Version 123: Adding a default value for the ability to add a user from
3106 // the lock screen.
3107 if (userId == UserHandle.USER_SYSTEM) {
3108 final SettingsState globalSettings = getGlobalSettingsLocked();
3109 Setting currentSetting = globalSettings.getSettingLocked(
3110 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003111 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003112 globalSettings.insertSettingLocked(
3113 Settings.Global.ADD_USERS_WHEN_LOCKED,
3114 getContext().getResources().getBoolean(
3115 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003116 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003117 }
3118 }
3119 currentVersion = 123;
3120 }
Bryce Leebd179282015-12-17 19:01:37 -08003121
3122 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003123 final SettingsState globalSettings = getGlobalSettingsLocked();
3124 String defaultDisabledProfiles = (getContext().getResources().getString(
3125 R.string.def_bluetooth_disabled_profiles));
3126 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003127 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003128 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003129 }
3130
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003131 if (currentVersion == 124) {
3132 // Version 124: allow OEMs to set a default value for whether IME should be
3133 // shown when a physical keyboard is connected.
3134 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3135 Setting currentSetting = secureSettings.getSettingLocked(
3136 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003137 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003138 secureSettings.insertSettingLocked(
3139 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3140 getContext().getResources().getBoolean(
3141 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003142 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003143 }
3144 currentVersion = 125;
3145 }
3146
Ruben Brunk98576cf2016-03-07 18:54:28 -08003147 if (currentVersion == 125) {
3148 // Version 125: Allow OEMs to set the default VR service.
3149 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3150
3151 Setting currentSetting = secureSettings.getSettingLocked(
3152 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003153 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003154 ArraySet<ComponentName> l =
3155 SystemConfig.getInstance().getDefaultVrComponents();
3156
3157 if (l != null && !l.isEmpty()) {
3158 StringBuilder b = new StringBuilder();
3159 boolean start = true;
3160 for (ComponentName c : l) {
3161 if (!start) {
3162 b.append(':');
3163 }
3164 b.append(c.flattenToString());
3165 start = false;
3166 }
3167 secureSettings.insertSettingLocked(
3168 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003169 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003170 }
3171
3172 }
3173 currentVersion = 126;
3174 }
3175
Daniel U02ba6122016-04-01 18:41:42 +01003176 if (currentVersion == 126) {
3177 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3178 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3179 if (mUserManager.isManagedProfile(userId)) {
3180 final SettingsState systemSecureSettings =
3181 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3182
3183 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3184 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003185 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003186 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3187 secureSettings.insertSettingLocked(
3188 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003189 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003190 SettingsState.SYSTEM_PACKAGE_NAME);
3191 }
3192
3193 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3194 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003195 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003196 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3197 secureSettings.insertSettingLocked(
3198 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003199 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003200 SettingsState.SYSTEM_PACKAGE_NAME);
3201 }
3202 }
3203 currentVersion = 127;
3204 }
3205
Steven Ngdc20ba62016-04-26 18:19:04 +01003206 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003207 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003208 currentVersion = 128;
3209 }
3210
Julia Reynolds1f721e12016-07-11 08:50:58 -04003211 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003212 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003213 currentVersion = 129;
3214 }
3215
Dan Sandler71f85e92016-07-20 13:46:05 -04003216 if (currentVersion == 129) {
3217 // default longpress timeout changed from 500 to 400. If unchanged from the old
3218 // default, update to the new default.
3219 final SettingsState systemSecureSettings =
3220 getSecureSettingsLocked(userId);
3221 final String oldValue = systemSecureSettings.getSettingLocked(
3222 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3223 if (TextUtils.equals("500", oldValue)) {
3224 systemSecureSettings.insertSettingLocked(
3225 Settings.Secure.LONG_PRESS_TIMEOUT,
3226 String.valueOf(getContext().getResources().getInteger(
3227 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003228 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003229 }
3230 currentVersion = 130;
3231 }
3232
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003233 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003234 // Split Ambient settings
3235 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3236 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3237 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3238
3239 if (dozeExplicitlyDisabled) {
3240 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003241 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003242 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003243 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003244 }
3245 currentVersion = 131;
3246 }
3247
3248 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003249 // Initialize new multi-press timeout to default value
3250 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3251 final String oldValue = systemSecureSettings.getSettingLocked(
3252 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3253 if (TextUtils.equals(null, oldValue)) {
3254 systemSecureSettings.insertSettingLocked(
3255 Settings.Secure.MULTI_PRESS_TIMEOUT,
3256 String.valueOf(getContext().getResources().getInteger(
3257 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003258 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003259 }
3260
Adrian Roos69741a22016-10-21 14:49:17 -07003261 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003262 }
3263
Adrian Roos69741a22016-10-21 14:49:17 -07003264 if (currentVersion == 132) {
3265 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003266 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3267 String defaultSyncParentSounds = (getContext().getResources()
3268 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3269 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003270 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3271 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003272 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003273 }
3274
Adrian Roos69741a22016-10-21 14:49:17 -07003275 if (currentVersion == 133) {
3276 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003277 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3278 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3279 null) {
3280 String defaultEndButtonBehavior = Integer.toString(getContext()
3281 .getResources().getInteger(R.integer.def_end_button_behavior));
3282 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003283 defaultEndButtonBehavior, null, true,
3284 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003285 }
Adrian Roos69741a22016-10-21 14:49:17 -07003286 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003287 }
3288
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003289 if (currentVersion == 134) {
3290 // Remove setting that specifies if magnification values should be preserved.
3291 // This setting defaulted to true and never has a UI.
3292 getSecureSettingsLocked(userId).deleteSettingLocked(
3293 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3294 currentVersion = 135;
3295 }
3296
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003297 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003298 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003299 currentVersion = 136;
3300 }
3301
Mark Rathjend891f012017-01-19 04:10:37 +00003302 if (currentVersion == 136) {
3303 // Version 136: Store legacy SSAID for all apps currently installed on the
3304 // device as first step in migrating SSAID to be unique per application.
3305
3306 final boolean isUpgrade;
3307 try {
3308 isUpgrade = mPackageManager.isUpgrade();
3309 } catch (RemoteException e) {
3310 throw new IllegalStateException("Package manager not available");
3311 }
3312 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3313 // user data or first boot on a new device should use new ssaid generation.
3314 if (isUpgrade) {
3315 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003316 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3317 userId, Settings.Secure.ANDROID_ID);
3318 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3319 || legacySsaidSetting.getValue() == null) {
3320 throw new IllegalStateException("Legacy ssaid not accessible");
3321 }
3322 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003323
3324 // Fill each uid with the legacy ssaid to be backwards compatible.
3325 final List<PackageInfo> packages;
3326 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003327 packages = mPackageManager.getInstalledPackages(
3328 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3329 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003330 } catch (RemoteException e) {
3331 throw new IllegalStateException("Package manager not available");
3332 }
3333
3334 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3335 for (PackageInfo info : packages) {
3336 // Check if the UID already has an entry in the table.
3337 final String uid = Integer.toString(info.applicationInfo.uid);
3338 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3339
3340 if (ssaid.isNull() || ssaid.getValue() == null) {
3341 // Android Id doesn't exist for this package so create it.
3342 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3343 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003344 if (DEBUG) {
3345 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3346 }
Mark Rathjend891f012017-01-19 04:10:37 +00003347 }
3348 }
3349 }
3350
3351 currentVersion = 137;
3352 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003353 if (currentVersion == 137) {
3354 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3355 // default value set to 1. The user can no longer change the value of this
3356 // setting through the UI.
3357 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3358 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003359 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3360 && secureSetting.getSettingLocked(
3361 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3362
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003363 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3364 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003365 // For managed profiles with profile owners, DevicePolicyManagerService
3366 // may want to set the user restriction in this case
3367 secureSetting.insertSettingLocked(
3368 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3369 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003370 }
3371 currentVersion = 138;
3372 }
Mark Rathjend891f012017-01-19 04:10:37 +00003373
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003374 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003375 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003376 currentVersion = 139;
3377 }
3378
Phil Weaver385912e2017-02-10 10:06:56 -08003379 if (currentVersion == 139) {
3380 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3381 // the user can no longer change the value of this setting through the UI.
3382 // Force to true.
3383 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3384 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3385 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3386 currentVersion = 140;
3387 }
3388
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003389 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003390 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003391 currentVersion = 141;
3392 }
3393
Svet Ganov13701552017-02-23 12:45:17 -08003394 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003395 // This implementation was incorrectly setting the current value of
3396 // settings changed by non-system packages as the default which default
3397 // is set by the system. We add a new upgrade step at the end to properly
3398 // handle this case which would also fix incorrect changes made by the
3399 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003400 currentVersion = 142;
3401 }
3402
Stephen Chen5d0922f2017-03-27 10:28:04 -07003403 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003404 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003405 if (userId == UserHandle.USER_SYSTEM) {
3406 final SettingsState globalSettings = getGlobalSettingsLocked();
3407 Setting currentSetting = globalSettings.getSettingLocked(
3408 Settings.Global.WIFI_WAKEUP_ENABLED);
3409 if (currentSetting.isNull()) {
3410 globalSettings.insertSettingLocked(
3411 Settings.Global.WIFI_WAKEUP_ENABLED,
3412 getContext().getResources().getBoolean(
3413 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3414 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3415 }
3416 }
3417
3418 currentVersion = 143;
3419 }
3420
Felipe Lemeff355092017-04-03 12:55:02 -07003421 if (currentVersion == 143) {
3422 // Version 144: Set a default value for Autofill service.
3423 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3424 final Setting currentSetting = secureSettings
3425 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3426 if (currentSetting.isNull()) {
3427 final String defaultValue = getContext().getResources().getString(
3428 com.android.internal.R.string.config_defaultAutofillService);
3429 if (defaultValue != null) {
3430 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3431 + "for user " + userId);
3432 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3433 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3434 }
3435 }
3436
3437 currentVersion = 144;
3438 }
3439
Jeremy Joslin45caa252017-05-04 11:22:46 -07003440 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003441 // Version 145: Removed
3442 currentVersion = 145;
3443 }
3444
3445 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003446 // Version 146: In step 142 we had a bug where incorrectly
3447 // some settings were considered system set and as a result
3448 // made the default and marked as the default being set by
3449 // the system. Here reevaluate the default and default system
3450 // set flags. This would both fix corruption by the old impl
3451 // of step 142 and also properly handle devices which never
3452 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003453 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003454 SettingsState globalSettings = getGlobalSettingsLocked();
3455 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3456 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003457 }
3458
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003459 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3460 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3461 secureSettings.persistSyncLocked();
3462
3463 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3464 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3465 systemSettings.persistSyncLocked();
3466
Amin Shaikh86367962017-06-07 08:58:22 -07003467 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003468 }
3469
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003470 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003471 // Version 147: Removed. (This version previously allowed showing the
3472 // "wifi_wakeup_available" setting).
3473 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003474 currentVersion = 147;
3475 }
3476
3477 if (currentVersion == 147) {
3478 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003479 if (userId == UserHandle.USER_SYSTEM) {
3480 final SettingsState globalSettings = getGlobalSettingsLocked();
3481 final Setting currentSetting = globalSettings.getSettingLocked(
3482 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3483 if (currentSetting.isNull()) {
3484 globalSettings.insertSettingLocked(
3485 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3486 getContext().getResources().getBoolean(
3487 R.bool.def_restrict_background_data) ? "1" : "0",
3488 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3489 }
3490 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003491 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003492 }
3493
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003494 if (currentVersion == 148) {
3495 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3496 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3497 final String oldValue = systemSecureSettings.getSettingLocked(
3498 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3499 if (TextUtils.equals(null, oldValue)) {
3500 final String defaultValue = getContext().getResources().getString(
3501 R.string.def_backup_manager_constants);
3502 if (!TextUtils.isEmpty(defaultValue)) {
3503 systemSecureSettings.insertSettingLocked(
3504 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3505 true, SettingsState.SYSTEM_PACKAGE_NAME);
3506 }
3507 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003508 currentVersion = 149;
3509 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003510
3511 if (currentVersion == 149) {
3512 // Version 150: Set a default value for mobile data always on
3513 final SettingsState globalSettings = getGlobalSettingsLocked();
3514 final Setting currentSetting = globalSettings.getSettingLocked(
3515 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3516 if (currentSetting.isNull()) {
3517 globalSettings.insertSettingLocked(
3518 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3519 getContext().getResources().getBoolean(
3520 R.bool.def_mobile_data_always_on) ? "1" : "0",
3521 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3522 }
3523
3524 currentVersion = 150;
3525 }
3526
Mike Digman4af4a6f2018-01-16 14:49:38 -08003527 if (currentVersion == 150) {
3528 // Version 151: Reset rotate locked setting for upgrading users
3529 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3530 systemSettings.insertSettingLocked(
3531 Settings.System.ACCELEROMETER_ROTATION,
3532 getContext().getResources().getBoolean(
3533 R.bool.def_accelerometer_rotation) ? "1" : "0",
3534 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3535
3536 currentVersion = 151;
3537 }
3538
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003539 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003540 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3541 // by default but it is now no longer configurable).
3542 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003543 currentVersion = 152;
3544 }
3545
Joe LaPenna250d7842018-01-25 10:19:42 -08003546 if (currentVersion == 152) {
3547 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3548 currentVersion = 153;
3549 }
3550
Ben Linb4df8bc2018-01-29 11:48:20 -08003551 if (currentVersion == 153) {
3552 // Version 154: Read notification badge configuration from config.
3553 // If user has already set the value, don't do anything.
3554 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3555 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3556 Settings.Secure.NOTIFICATION_BADGING);
3557 if (showNotificationBadges.isNull()) {
3558 final boolean defaultValue = getContext().getResources().getBoolean(
3559 com.android.internal.R.bool.config_notificationBadging);
3560 systemSecureSettings.insertSettingLocked(
3561 Secure.NOTIFICATION_BADGING,
3562 defaultValue ? "1" : "0",
3563 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3564 }
3565 currentVersion = 154;
3566 }
3567
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003568 if (currentVersion == 154) {
3569 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3570 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3571 final String oldValue = systemSecureSettings.getSettingLocked(
3572 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3573 if (TextUtils.equals(null, oldValue)) {
3574 final String defaultValue = getContext().getResources().getString(
3575 R.string.def_backup_local_transport_parameters);
3576 if (!TextUtils.isEmpty(defaultValue)) {
3577 systemSecureSettings.insertSettingLocked(
3578 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3579 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3580 }
3581
3582 }
3583 currentVersion = 155;
3584 }
3585
Beverlyda904812018-03-02 09:55:30 -05003586 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003587 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003588 final SettingsState globalSettings = getGlobalSettingsLocked();
3589 final String oldValue = globalSettings.getSettingLocked(
3590 Global.CHARGING_STARTED_SOUND).getValue();
3591 final String oldDefault = getContext().getResources().getString(
3592 R.string.def_wireless_charging_started_sound);
3593 if (TextUtils.equals(null, oldValue)
3594 || TextUtils.equals(oldValue, oldDefault)) {
3595 final String defaultValue = getContext().getResources().getString(
3596 R.string.def_charging_started_sound);
3597 if (!TextUtils.isEmpty(defaultValue)) {
3598 globalSettings.insertSettingLocked(
3599 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3600 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3601 }
3602
3603 }
3604 currentVersion = 156;
3605 }
3606
Beverly09da25f2018-02-26 09:17:07 -05003607 if (currentVersion == 156) {
Annie Mengd069a882018-03-13 15:31:40 +00003608 // Version 157: Set a default value for zen duration
Beverly09da25f2018-02-26 09:17:07 -05003609 final SettingsState globalSettings = getGlobalSettingsLocked();
3610 final Setting currentSetting = globalSettings.getSettingLocked(
3611 Global.ZEN_DURATION);
3612 if (currentSetting.isNull()) {
3613 String defaultZenDuration = Integer.toString(getContext()
3614 .getResources().getInteger(R.integer.def_zen_duration));
3615 globalSettings.insertSettingLocked(
3616 Global.ZEN_DURATION, defaultZenDuration,
3617 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3618 }
Beverly09da25f2018-02-26 09:17:07 -05003619 currentVersion = 157;
3620 }
Annie Mengd069a882018-03-13 15:31:40 +00003621
3622 if (currentVersion == 157) {
3623 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3624 final SettingsState globalSettings = getGlobalSettingsLocked();
3625 final String oldValue = globalSettings.getSettingLocked(
3626 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3627 if (TextUtils.equals(null, oldValue)) {
3628 final String defaultValue = getContext().getResources().getString(
3629 R.string.def_backup_agent_timeout_parameters);
3630 if (!TextUtils.isEmpty(defaultValue)) {
3631 globalSettings.insertSettingLocked(
3632 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3633 null, true,
3634 SettingsState.SYSTEM_PACKAGE_NAME);
3635 }
3636 }
3637 currentVersion = 158;
3638 }
Roshan Pius9c396672018-03-02 14:54:13 -08003639
3640 if (currentVersion == 158) {
3641 // Remove setting that specifies wifi bgscan throttling params
3642 getGlobalSettingsLocked().deleteSettingLocked(
3643 "wifi_scan_background_throttle_interval_ms");
3644 getGlobalSettingsLocked().deleteSettingLocked(
3645 "wifi_scan_background_throttle_package_whitelist");
3646 currentVersion = 159;
3647 }
3648
Pavel Grafovc5c97302018-03-19 13:37:15 +00003649 if (currentVersion == 159) {
3650 // Version 160: Hiding notifications from the lockscreen is only available as
3651 // primary user option, profiles can only make them redacted. If a profile was
3652 // configured to not show lockscreen notifications, ensure that at the very
3653 // least these will be come hidden.
3654 if (mUserManager.isManagedProfile(userId)) {
3655 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3656 Setting showNotifications = secureSettings.getSettingLocked(
3657 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3658 // The default value is "1", check if user has turned it off.
3659 if ("0".equals(showNotifications.getValue())) {
3660 secureSettings.insertSettingLocked(
3661 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3662 null /* tag */, false /* makeDefault */,
3663 SettingsState.SYSTEM_PACKAGE_NAME);
3664 }
3665 // The setting is no longer valid for managed profiles, it should be
3666 // treated as if it was set to "1".
3667 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3668 }
3669 currentVersion = 160;
3670 }
Felipe Lemeff355092017-04-03 12:55:02 -07003671 // vXXX: Add new settings above this point.
3672
Dan Sandler71f85e92016-07-20 13:46:05 -04003673 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003674 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003675 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003676 + currentVersion +
3677 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3678 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003679 if (DEBUG) {
3680 throw new RuntimeException("db upgrade error");
3681 }
3682 }
3683
Jeff Brown503cffc2015-03-26 18:08:51 -07003684 // Return the current version.
3685 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003686 }
3687 }
Svet Ganov13701552017-02-23 12:45:17 -08003688
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003689 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3690 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003691 List<String> names = settings.getSettingNamesLocked();
3692 final int nameCount = names.size();
3693 for (int i = 0; i < nameCount; i++) {
3694 String name = names.get(i);
3695 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003696
3697 // In the upgrade case we pretend the call is made from the app
3698 // that made the last change to the setting to properly determine
3699 // whether the call has been made by a system component.
3700 int callingUid = -1;
3701 try {
3702 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3703 } catch (RemoteException e) {
3704 /* ignore - handled below */
3705 }
3706 if (callingUid < 0) {
3707 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3708 continue;
3709 }
3710 try {
3711 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3712 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003713 if (systemSet) {
3714 settings.insertSettingLocked(name, setting.getValue(),
3715 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003716 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3717 // We had a bug where changes by non-system packages were marked
3718 // as system made and as a result set as the default. Therefore, if
3719 // the package changed the setting last is not a system one but the
3720 // setting is marked as its default coming from the system we clear
3721 // the default and clear the system set flag.
3722 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003723 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003724 } catch (IllegalStateException e) {
3725 // If the package goes over its quota during the upgrade, don't
3726 // crash but just log the error as the system does the upgrade.
3727 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3728
Svet Ganov13701552017-02-23 12:45:17 -08003729 }
3730 }
3731 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003732 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003733}