blob: f4d18928fd2e9e4f71a310e64015beb97ea1a06c [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
Andreas Gampeb58893072018-09-05 16:52:31 -0700725 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700726 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700727 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800728 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700729 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
730 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700731 if (globalSettings != null) {
732 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800733 pw.println();
734 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700735 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800736 }
737
738 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700739 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
740 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700741 if (secureSettings != null) {
742 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800743 pw.println();
744 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700745 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700746
Svetoslavb505ccc2015-02-17 12:41:04 -0800747 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700748 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
749 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700750 if (systemSettings != null) {
751 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800752 pw.println();
753 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700754 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800755 }
756
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700757 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
758 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800759
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700760 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800761
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700762 for (int i = 0; i < nameCount; i++) {
763 String name = names.get(i);
764 Setting setting = settingsState.getSettingLocked(name);
765 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
766 pw.print(" name:"); pw.print(toDumpString(name));
767 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800768 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700769 }
770 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800771 if (setting.getDefaultValue() != null) {
772 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800773 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800774 }
775 if (setting.getTag() != null) {
776 pw.print(" tag:"); pw.print(setting.getTag());
777 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800778 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700779 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800780 }
781
Svetoslav7e0683b2015-08-03 16:02:52 -0700782 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700783 if (s != null) {
784 return s;
785 }
786 return "{null}";
787 }
788
Svetoslav683914b2015-01-15 14:22:26 -0800789 private void registerBroadcastReceivers() {
790 IntentFilter userFilter = new IntentFilter();
791 userFilter.addAction(Intent.ACTION_USER_REMOVED);
792 userFilter.addAction(Intent.ACTION_USER_STOPPED);
793
794 getContext().registerReceiver(new BroadcastReceiver() {
795 @Override
796 public void onReceive(Context context, Intent intent) {
797 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700798 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800799
800 switch (intent.getAction()) {
801 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700802 synchronized (mLock) {
803 mSettingsRegistry.removeUserStateLocked(userId, true);
804 }
Svetoslav683914b2015-01-15 14:22:26 -0800805 } break;
806
807 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700808 synchronized (mLock) {
809 mSettingsRegistry.removeUserStateLocked(userId, false);
810 }
Svetoslav683914b2015-01-15 14:22:26 -0800811 } break;
812 }
813 }
814 }, userFilter);
815
816 PackageMonitor monitor = new PackageMonitor() {
817 @Override
818 public void onPackageRemoved(String packageName, int uid) {
819 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100820 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800821 UserHandle.getUserId(uid));
822 }
823 }
Mark Rathjend891f012017-01-19 04:10:37 +0000824
825 @Override
826 public void onUidRemoved(int uid) {
827 synchronized (mLock) {
828 mSettingsRegistry.onUidRemovedLocked(uid);
829 }
830 }
Zimuzoc56192c2018-07-25 10:40:01 +0100831
832 @Override
833 public void onPackageDataCleared(String packageName, int uid) {
834 synchronized (mLock) {
835 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
836 UserHandle.getUserId(uid));
837 }
838 }
Svetoslav683914b2015-01-15 14:22:26 -0800839 };
840
841 // package changes
842 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
843 UserHandle.ALL, true);
844 }
845
Svet Ganov53a441c2016-04-19 19:38:00 -0700846 private void startWatchingUserRestrictionChanges() {
847 // TODO: The current design of settings looking different based on user restrictions
848 // should be reworked to keep them separate and system code should check the setting
849 // first followed by checking the user restriction before performing an operation.
850 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
851 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
852 Bundle prevRestrictions) -> {
853 // We are changing the settings affected by restrictions to their current
854 // value with a forced update to ensure that all cross profile dependencies
855 // are taken into account. Also make sure the settings update to.. the same
856 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800857 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
858 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700859 final long identity = Binder.clearCallingIdentity();
860 try {
861 synchronized (mLock) {
862 Setting setting = getSecureSetting(
863 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
864 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800865 setting != null ? setting.getValue() : null, null,
866 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700867 }
868 } finally {
869 Binder.restoreCallingIdentity(identity);
870 }
871 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800872 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100873 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
874 newRestrictions.getBoolean(
875 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
876 != prevRestrictions.getBoolean(
877 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700878 final long identity = Binder.clearCallingIdentity();
879 try {
880 synchronized (mLock) {
881 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800882 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700883 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800884 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700885 }
886 } finally {
887 Binder.restoreCallingIdentity(identity);
888 }
889 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800890 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
891 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700892 final long identity = Binder.clearCallingIdentity();
893 try {
894 synchronized (mLock) {
895 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800896 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700897 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800898 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700899 }
900 } finally {
901 Binder.restoreCallingIdentity(identity);
902 }
903 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800904 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
905 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700906 final long identity = Binder.clearCallingIdentity();
907 try {
908 synchronized (mLock) {
909 Setting enable = getGlobalSetting(
910 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700912 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800913 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700914 Setting include = getGlobalSetting(
915 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800916 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700917 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700919 }
920 } finally {
921 Binder.restoreCallingIdentity(identity);
922 }
923 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800924 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
925 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700926 final long identity = Binder.clearCallingIdentity();
927 try {
928 synchronized (mLock) {
929 Setting setting = getGlobalSetting(
930 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800931 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700932 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800933 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700934 }
935 } finally {
936 Binder.restoreCallingIdentity(identity);
937 }
938 }
939 });
940 }
941
Svetoslav7ec28e82015-05-20 17:01:10 -0700942 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800943 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700944 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800945 }
946
Svetoslav7ec28e82015-05-20 17:01:10 -0700947 synchronized (mLock) {
948 // Get the settings.
949 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700950 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800951
Chad Brubaker97bccee2017-01-05 15:51:41 -0800952 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
953 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800954
Svetoslav7ec28e82015-05-20 17:01:10 -0700955 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800956
Svetoslav7ec28e82015-05-20 17:01:10 -0700957 String[] normalizedProjection = normalizeProjection(projection);
958 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800959
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 // Anyone can get the global settings, so no security checks.
961 for (int i = 0; i < nameCount; i++) {
962 String name = names.get(i);
963 Setting setting = settingsState.getSettingLocked(name);
964 appendSettingToCursor(result, setting);
965 }
966
967 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800968 }
Svetoslav683914b2015-01-15 14:22:26 -0800969 }
970
Svetoslav7ec28e82015-05-20 17:01:10 -0700971 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800972 if (DEBUG) {
973 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
974 }
975
Chad Brubakera6830e72017-04-28 17:34:36 -0700976 // Ensure the caller can access the setting.
977 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
978
Svetoslav683914b2015-01-15 14:22:26 -0800979 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700980 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700981 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700982 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800983 }
Svetoslav683914b2015-01-15 14:22:26 -0800984 }
985
Svetoslav Ganove080da92016-12-21 17:10:35 -0800986 private boolean updateGlobalSetting(String name, String value, String tag,
987 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800988 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800989 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
990 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
991 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800992 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800993 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
994 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800995 }
996
Svetoslav Ganove080da92016-12-21 17:10:35 -0800997 private boolean insertGlobalSetting(String name, String value, String tag,
998 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700999 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1001 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1002 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001003 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001004 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1005 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001006 }
1007
Svet Ganov53a441c2016-04-19 19:38:00 -07001008 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001009 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001010 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1011 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001012 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001013 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1014 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001015 }
1016
Svetoslav Ganove080da92016-12-21 17:10:35 -08001017 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1018 if (DEBUG) {
1019 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1020 + mode + ", " + tag + ")");
1021 }
1022 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1023 MUTATION_OPERATION_RESET, false, mode);
1024 }
1025
1026 private boolean mutateGlobalSetting(String name, String value, String tag,
1027 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1028 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001029 // Make sure the caller can change the settings - treated as secure.
1030 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1031
Svetoslav683914b2015-01-15 14:22:26 -08001032 // Resolve the userId on whose behalf the call is made.
1033 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1034
Makoto Onuki28da2e32015-11-20 11:30:44 -08001035 // If this is a setting that is currently restricted for this user, do not allow
1036 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001037 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1038 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001039 return false;
1040 }
1041
1042 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001043 synchronized (mLock) {
1044 switch (operation) {
1045 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001046 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1047 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001048 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001049 }
Svetoslav683914b2015-01-15 14:22:26 -08001050
Svetoslav7ec28e82015-05-20 17:01:10 -07001051 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001052 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001053 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001054 }
Svetoslav683914b2015-01-15 14:22:26 -08001055
Svetoslav7ec28e82015-05-20 17:01:10 -07001056 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001057 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1058 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001059 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001060 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001061
1062 case MUTATION_OPERATION_RESET: {
1063 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1064 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1065 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001066 }
1067 }
1068
1069 return false;
1070 }
1071
Christopher Tateb218e762017-04-05 16:34:07 -07001072 private PackageInfo getCallingPackageInfo(int userId) {
1073 try {
1074 return mPackageManager.getPackageInfo(getCallingPackage(),
1075 PackageManager.GET_SIGNATURES, userId);
1076 } catch (RemoteException e) {
1077 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1078 }
1079 }
1080
Svetoslav7ec28e82015-05-20 17:01:10 -07001081 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001082 if (DEBUG) {
1083 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1084 }
1085
1086 // Resolve the userId on whose behalf the call is made.
1087 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1088
Christopher Tateb218e762017-04-05 16:34:07 -07001089 // The relevant "calling package" userId will be the owning userId for some
1090 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1091 // up front who the effective "new SSAID" user ID for that settings name will be.
1092 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1093 Settings.Secure.ANDROID_ID);
1094 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1095
Svetoslav7ec28e82015-05-20 17:01:10 -07001096 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001097 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001098
Svetoslav7ec28e82015-05-20 17:01:10 -07001099 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001100
Svetoslav7ec28e82015-05-20 17:01:10 -07001101 String[] normalizedProjection = normalizeProjection(projection);
1102 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001103
Svetoslav7ec28e82015-05-20 17:01:10 -07001104 for (int i = 0; i < nameCount; i++) {
1105 String name = names.get(i);
1106 // Determine the owning user as some profile settings are cloned from the parent.
1107 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1108 name);
Svetoslav683914b2015-01-15 14:22:26 -08001109
Alex Klyubin1991f572017-03-03 14:08:36 -08001110 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1111 // This caller is not permitted to access this setting. Pretend the setting
1112 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001113 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001114 }
Svetoslav683914b2015-01-15 14:22:26 -08001115
Mark Rathjen7599f132017-01-23 14:15:54 -08001116 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001117 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1118 final Setting setting;
1119 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001120 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001121 } else {
1122 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1123 name);
1124 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001125 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001126 }
1127
Svetoslav7ec28e82015-05-20 17:01:10 -07001128 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001129 }
Svetoslav683914b2015-01-15 14:22:26 -08001130 }
1131
Svetoslav7ec28e82015-05-20 17:01:10 -07001132 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001133 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1134 }
1135
1136 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001137 if (DEBUG) {
1138 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1139 }
1140
1141 // Resolve the userId on whose behalf the call is made.
1142 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1143
Chad Brubakera6830e72017-04-28 17:34:36 -07001144 // Ensure the caller can access the setting.
1145 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1146
Svetoslav683914b2015-01-15 14:22:26 -08001147 // Determine the owning user as some profile settings are cloned from the parent.
1148 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1149
Alex Klyubin1991f572017-03-03 14:08:36 -08001150 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1151 // This caller is not permitted to access this setting. Pretend the setting doesn't
1152 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001153 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1154 owningUserId);
1155 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001156 }
1157
Christopher Tateb218e762017-04-05 16:34:07 -07001158 // As of Android O, the SSAID is read from an app-specific entry in table
1159 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1160 if (isNewSsaidSetting(name)) {
1161 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1162 synchronized (mLock) {
1163 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001164 }
Christopher Tateb218e762017-04-05 16:34:07 -07001165 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001166 if (enableOverride) {
1167 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1168 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1169 if (overridden != null) {
1170 return overridden;
1171 }
1172 }
1173 }
Mark Rathjend891f012017-01-19 04:10:37 +00001174
Christopher Tateb218e762017-04-05 16:34:07 -07001175 // Not the SSAID; do a straight lookup
1176 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001177 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001178 owningUserId, name);
1179 }
Svetoslav683914b2015-01-15 14:22:26 -08001180 }
1181
Mark Rathjend891f012017-01-19 04:10:37 +00001182 private boolean isNewSsaidSetting(String name) {
1183 return Settings.Secure.ANDROID_ID.equals(name)
1184 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1185 }
1186
Andreas Gampeb58893072018-09-05 16:52:31 -07001187 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001188 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001189 // Get uid of caller (key) used to store ssaid value
1190 String name = Integer.toString(
1191 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1192
1193 if (DEBUG) {
1194 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1195 }
1196
1197 // Retrieve the ssaid from the table if present.
1198 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1199 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001200 // If the app is an Instant App use its stored SSAID instead of our own.
1201 final String instantSsaid;
1202 final long token = Binder.clearCallingIdentity();
1203 try {
1204 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1205 owningUserId);
1206 } catch (RemoteException e) {
1207 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1208 return null;
1209 } finally {
1210 Binder.restoreCallingIdentity(token);
1211 }
Svet Ganov96c99462017-05-05 14:27:13 -07001212
1213 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1214 SETTINGS_TYPE_SSAID, owningUserId);
1215
Chad Brubaker0d277a72017-04-12 16:56:53 -07001216 if (instantSsaid != null) {
1217 // Use the stored value if it is still valid.
1218 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001219 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001220 }
1221 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001222 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1223 true, callingPkg.packageName);
1224 if (!success) {
1225 throw new IllegalStateException("Failed to update instant app android id");
1226 }
Svet Ganov96c99462017-05-05 14:27:13 -07001227 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1228 owningUserId, name);
1229 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001230 }
Mark Rathjend891f012017-01-19 04:10:37 +00001231
1232 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001233 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001234 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1235 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001236 }
1237
Svet Ganov96c99462017-05-05 14:27:13 -07001238 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1239 }
1240
1241 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1242 // SSAID settings are located in a dedicated table for internal bookkeeping
1243 // but for the world they reside in the secure table, so adjust the key here.
1244 // We have a special name when looking it up but want the world to see it as
1245 // "android_id".
1246 if (ssaidSetting != null) {
1247 return settingsState.new Setting(ssaidSetting) {
1248 @Override
1249 public int getKey() {
1250 final int userId = getUserIdFromKey(super.getKey());
1251 return makeKey(SETTINGS_TYPE_SECURE, userId);
1252 }
1253
1254 @Override
1255 public String getName() {
1256 return Settings.Secure.ANDROID_ID;
1257 }
1258 };
1259 }
1260 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001261 }
1262
Makoto Onuki0000d322017-11-28 16:31:47 -08001263 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1264 synchronized (mLock) {
1265 final Setting setting = getGlobalSetting(
1266 Global.LOCATION_GLOBAL_KILL_SWITCH);
1267 if (!"1".equals(setting.getValue())) {
1268 return null;
1269 }
1270 // Global kill-switch is enabled. Return an empty value.
1271 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1272 SETTINGS_TYPE_SECURE, owningUserId);
1273 return settingsState.new Setting(
1274 Secure.LOCATION_PROVIDERS_ALLOWED,
1275 "", // value
1276 "", // tag
1277 "", // default value
1278 "", // package name
1279 false, // from system
1280 "0" // id
1281 ) {
1282 @Override
1283 public boolean update(String value, boolean setDefault, String packageName,
1284 String tag, boolean forceNonSystemPackage) {
1285 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1286 return false;
1287 }
1288 };
1289 }
1290 }
1291
Svetoslav Ganove080da92016-12-21 17:10:35 -08001292 private boolean insertSecureSetting(String name, String value, String tag,
1293 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001294 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001295 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001296 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1297 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001298 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001299 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1300 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001301 }
1302
Svet Ganov53a441c2016-04-19 19:38:00 -07001303 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001304 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001305 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1306 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001307 }
1308
Svetoslav Ganove080da92016-12-21 17:10:35 -08001309 return mutateSecureSetting(name, null, null, false, requestingUserId,
1310 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001311 }
1312
Svetoslav Ganove080da92016-12-21 17:10:35 -08001313 private boolean updateSecureSetting(String name, String value, String tag,
1314 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001315 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001316 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001317 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1318 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001319 }
1320
Svetoslav Ganove080da92016-12-21 17:10:35 -08001321 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1322 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001323 }
1324
Svetoslav Ganove080da92016-12-21 17:10:35 -08001325 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1326 if (DEBUG) {
1327 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1328 + mode + ", " + tag + ")");
1329 }
1330
1331 mutateSecureSetting(null, null, tag, false, requestingUserId,
1332 MUTATION_OPERATION_RESET, false, mode);
1333 }
1334
1335 private boolean mutateSecureSetting(String name, String value, String tag,
1336 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1337 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001338 // Make sure the caller can change the settings.
1339 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1340
Svetoslav683914b2015-01-15 14:22:26 -08001341 // Resolve the userId on whose behalf the call is made.
1342 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1343
Makoto Onuki28da2e32015-11-20 11:30:44 -08001344 // If this is a setting that is currently restricted for this user, do not allow
1345 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001346 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1347 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001348 return false;
1349 }
1350
1351 // Determine the owning user as some profile settings are cloned from the parent.
1352 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1353
1354 // Only the owning user can change the setting.
1355 if (owningUserId != callingUserId) {
1356 return false;
1357 }
1358
1359 // Special cases for location providers (sigh).
1360 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001361 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1362 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001363 }
1364
1365 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001366 synchronized (mLock) {
1367 switch (operation) {
1368 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001369 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001370 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001371 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001372 }
Svetoslav683914b2015-01-15 14:22:26 -08001373
Svetoslav7ec28e82015-05-20 17:01:10 -07001374 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001375 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001376 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001377 }
Svetoslav683914b2015-01-15 14:22:26 -08001378
Svetoslav7ec28e82015-05-20 17:01:10 -07001379 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001380 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001381 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001382 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001383 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001384
1385 case MUTATION_OPERATION_RESET: {
1386 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1387 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1388 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001389 }
1390 }
1391
1392 return false;
1393 }
1394
Svetoslav7ec28e82015-05-20 17:01:10 -07001395 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001396 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001397 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001398 }
1399
1400 // Resolve the userId on whose behalf the call is made.
1401 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1402
Svetoslav7ec28e82015-05-20 17:01:10 -07001403 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001404 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001405
Svetoslav7ec28e82015-05-20 17:01:10 -07001406 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001407
Svetoslav7ec28e82015-05-20 17:01:10 -07001408 String[] normalizedProjection = normalizeProjection(projection);
1409 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001410
Svetoslav7ec28e82015-05-20 17:01:10 -07001411 for (int i = 0; i < nameCount; i++) {
1412 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001413
Svetoslav7ec28e82015-05-20 17:01:10 -07001414 // Determine the owning user as some profile settings are cloned from the parent.
1415 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1416 name);
Svetoslav683914b2015-01-15 14:22:26 -08001417
Svetoslav7ec28e82015-05-20 17:01:10 -07001418 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001419 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001420 appendSettingToCursor(result, setting);
1421 }
1422
1423 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001424 }
Svetoslav683914b2015-01-15 14:22:26 -08001425 }
1426
Svetoslav7ec28e82015-05-20 17:01:10 -07001427 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001428 if (DEBUG) {
1429 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1430 }
1431
1432 // Resolve the userId on whose behalf the call is made.
1433 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1434
Chad Brubakera6830e72017-04-28 17:34:36 -07001435 // Ensure the caller can access the setting.
1436 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001437
Svetoslav683914b2015-01-15 14:22:26 -08001438 // Determine the owning user as some profile settings are cloned from the parent.
1439 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1440
1441 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001442 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001443 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001444 }
Svetoslav683914b2015-01-15 14:22:26 -08001445 }
1446
Svetoslav7ec28e82015-05-20 17:01:10 -07001447 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001448 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001449 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001450 + requestingUserId + ")");
1451 }
1452
Svetoslav7ec28e82015-05-20 17:01:10 -07001453 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001454 }
1455
Svetoslav7ec28e82015-05-20 17:01:10 -07001456 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001457 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001458 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001459 }
1460
Svetoslav7ec28e82015-05-20 17:01:10 -07001461 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001462 }
1463
Svetoslav7ec28e82015-05-20 17:01:10 -07001464 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001465 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001466 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001467 + requestingUserId + ")");
1468 }
1469
Svetoslav7ec28e82015-05-20 17:01:10 -07001470 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001471 }
1472
Svetoslav7ec28e82015-05-20 17:01:10 -07001473 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001474 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001475 if (!hasWriteSecureSettingsPermission()) {
1476 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1477 // operation is allowed for the calling package through appops.
1478 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1479 Binder.getCallingUid(), getCallingPackage(), true)) {
1480 return false;
1481 }
Svetoslav683914b2015-01-15 14:22:26 -08001482 }
1483
Svetoslav683914b2015-01-15 14:22:26 -08001484 // Resolve the userId on whose behalf the call is made.
1485 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1486
yuemingw1d13eae2018-01-30 17:27:54 +00001487 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1488 name, callingUserId, value, Binder.getCallingUid())) {
1489 return false;
1490 }
1491
Svetoslavd8d25e02015-11-20 13:09:26 -08001492 // Enforce what the calling package can mutate the system settings.
1493 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1494
Svetoslav683914b2015-01-15 14:22:26 -08001495 // Determine the owning user as some profile settings are cloned from the parent.
1496 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1497
1498 // Only the owning user id can change the setting.
1499 if (owningUserId != callingUserId) {
1500 return false;
1501 }
1502
Jeff Sharkey413573a2016-02-22 17:52:45 -07001503 // Invalidate any relevant cache files
1504 String cacheName = null;
1505 if (Settings.System.RINGTONE.equals(name)) {
1506 cacheName = Settings.System.RINGTONE_CACHE;
1507 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1508 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1509 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1510 cacheName = Settings.System.ALARM_ALERT_CACHE;
1511 }
1512 if (cacheName != null) {
1513 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001514 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001515 cacheFile.delete();
1516 }
1517
Svetoslav683914b2015-01-15 14:22:26 -08001518 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001519 synchronized (mLock) {
1520 switch (operation) {
1521 case MUTATION_OPERATION_INSERT: {
1522 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001523 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001524 owningUserId, name, value, null, false, getCallingPackage(),
1525 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001526 }
1527
1528 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001529 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001530 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001531 }
1532
1533 case MUTATION_OPERATION_UPDATE: {
1534 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001535 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001536 owningUserId, name, value, null, false, getCallingPackage(),
1537 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001538 }
Svetoslav683914b2015-01-15 14:22:26 -08001539 }
1540
Svetoslav7ec28e82015-05-20 17:01:10 -07001541 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001542 }
Svetoslav683914b2015-01-15 14:22:26 -08001543 }
1544
Billy Lau6ad2d662015-07-18 00:26:58 +01001545 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001546 // Write secure settings is a more protected permission. If caller has it we are good.
1547 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1548 == PackageManager.PERMISSION_GRANTED) {
1549 return true;
1550 }
1551
Svetoslavf41334b2015-06-23 12:06:03 -07001552 return false;
1553 }
1554
Svetoslav683914b2015-01-15 14:22:26 -08001555 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001556 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001557 if (validator != null && !validator.validate(value)) {
1558 throw new IllegalArgumentException("Invalid value: " + value
1559 + " for setting: " + name);
1560 }
1561 }
1562
Alex Klyubin1991f572017-03-03 14:08:36 -08001563 /**
1564 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1565 */
1566 private boolean isSecureSettingAccessible(String name, int callingUserId,
1567 int owningUserId) {
1568 // Special case for location (sigh).
1569 // This check is not inside the name-based checks below because this method performs checks
1570 // only if the calling user ID is not the same as the owning user ID.
1571 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1572 return false;
1573 }
1574
1575 switch (name) {
1576 case "bluetooth_address":
1577 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1578 // address in this secure setting. Secure settings can normally be read by any app,
1579 // which thus enables them to bypass the recently introduced restrictions on access
1580 // to device identifiers.
1581 // To mitigate this we make this setting available only to callers privileged to see
1582 // this device's MAC addresses, same as through public API
1583 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1584 return getContext().checkCallingOrSelfPermission(
1585 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1586 default:
1587 return true;
1588 }
1589 }
1590
Svetoslav683914b2015-01-15 14:22:26 -08001591 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1592 int owningUserId) {
1593 // Optimization - location providers are restricted only for managed profiles.
1594 if (callingUserId == owningUserId) {
1595 return false;
1596 }
1597 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1598 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1599 new UserHandle(callingUserId))) {
1600 return true;
1601 }
1602 return false;
1603 }
1604
Svetoslav683914b2015-01-15 14:22:26 -08001605 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1606 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1607 }
1608
1609 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001610 final int parentId;
1611 // Resolves dependency if setting has a dependency and the calling user has a parent
1612 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1613 && (parentId = getGroupParentLocked(userId)) != userId) {
1614 // The setting has a dependency and the profile has a parent
1615 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001616 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1617 final long token = Binder.clearCallingIdentity();
1618 try {
1619 Setting settingObj = getSecureSetting(dependency, userId);
1620 if (settingObj != null && settingObj.getValue().equals("1")) {
1621 return parentId;
1622 }
1623 } finally {
1624 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001625 }
1626 }
Svetoslav683914b2015-01-15 14:22:26 -08001627 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1628 }
1629
1630 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1631 final int parentId = getGroupParentLocked(userId);
1632 if (parentId != userId && keys.contains(name)) {
1633 return parentId;
1634 }
1635 return userId;
1636 }
1637
Svetoslavf41334b2015-06-23 12:06:03 -07001638 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001639 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001640 // System/root/shell can mutate whatever secure settings they want.
1641 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001642 final int appId = UserHandle.getAppId(callingUid);
1643 if (appId == android.os.Process.SYSTEM_UID
1644 || appId == Process.SHELL_UID
1645 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001646 return;
1647 }
1648
1649 switch (operation) {
1650 case MUTATION_OPERATION_INSERT:
1651 // Insert updates.
1652 case MUTATION_OPERATION_UPDATE: {
1653 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1654 return;
1655 }
1656
1657 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001658 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001659
1660 // Privileged apps can do whatever they want.
1661 if ((packageInfo.applicationInfo.privateFlags
1662 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1663 return;
1664 }
1665
1666 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1667 packageInfo.applicationInfo.targetSdkVersion, name);
1668 } break;
1669
1670 case MUTATION_OPERATION_DELETE: {
1671 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1672 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1673 throw new IllegalArgumentException("You cannot delete system defined"
1674 + " secure settings.");
1675 }
1676
1677 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001678 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001679
1680 // Privileged apps can do whatever they want.
1681 if ((packageInfo.applicationInfo.privateFlags &
1682 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1683 return;
1684 }
1685
1686 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1687 packageInfo.applicationInfo.targetSdkVersion, name);
1688 } break;
1689 }
1690 }
1691
Todd Kennedybe0b8892017-02-15 14:13:52 -08001692 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001693 switch (settingsType) {
1694 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001695 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001696 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001697 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001698 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001699 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001700 default:
1701 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1702 }
1703 }
1704
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001705 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1706 switch (settingsType) {
1707 case SETTINGS_TYPE_GLOBAL:
1708 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1709 case SETTINGS_TYPE_SYSTEM:
1710 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1711 case SETTINGS_TYPE_SECURE:
1712 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1713 default:
1714 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1715 }
1716 }
1717
Andreas Gampeb58893072018-09-05 16:52:31 -07001718 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001719 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001720 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1721 // in the current form.
1722 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001723 }
1724
Chad Brubakera6830e72017-04-28 17:34:36 -07001725 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001726 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1727 return;
1728 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001729 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001730 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001731 return;
1732 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001733 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1734 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001735 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1736 // breakage in the current form.
1737 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1738 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001739 }
1740 }
1741
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001742 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1743 // We always use the callingUid for this lookup. This means that if hypothetically an
1744 // app was installed in user A with cross user and in user B as an Instant App
1745 // the app in A would be able to see all the settings in user B. However since cross
1746 // user is a system permission and the app must be uninstalled in B and then installed as
1747 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001748 ApplicationInfo ai = null;
1749 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001750 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1751 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001752 } catch (RemoteException ignored) {
1753 }
1754 if (ai == null) {
1755 throw new IllegalStateException("Failed to lookup info for package "
1756 + getCallingPackage());
1757 }
1758 return ai;
1759 }
1760
Xiaohui Chen43765b72015-08-31 10:57:33 -07001761 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001762 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001763 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1764 getCallingPackage(), 0, userId);
1765 if (packageInfo != null) {
1766 return packageInfo;
1767 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001768 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001769 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001770 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001771 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001772 }
1773
1774 private int getGroupParentLocked(int userId) {
1775 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001776 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001777 return userId;
1778 }
1779 // We are in the same process with the user manager and the returned
1780 // user info is a cached instance, so just look up instead of cache.
1781 final long identity = Binder.clearCallingIdentity();
1782 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001783 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001784 UserInfo userInfo = mUserManager.getProfileParent(userId);
1785 return (userInfo != null) ? userInfo.id : userId;
1786 } finally {
1787 Binder.restoreCallingIdentity(identity);
1788 }
1789 }
1790
Svetoslav683914b2015-01-15 14:22:26 -08001791 private void enforceWritePermission(String permission) {
1792 if (getContext().checkCallingOrSelfPermission(permission)
1793 != PackageManager.PERMISSION_GRANTED) {
1794 throw new SecurityException("Permission denial: writing to settings requires:"
1795 + permission);
1796 }
1797 }
1798
1799 /*
1800 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1801 * This setting contains a list of the currently enabled location providers.
1802 * But helper functions in android.providers.Settings can enable or disable
1803 * a single provider by using a "+" or "-" prefix before the provider name.
1804 *
yuemingw1d13eae2018-01-30 17:27:54 +00001805 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1806 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1807 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001808 *
Svetoslav683914b2015-01-15 14:22:26 -08001809 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001810 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001811 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001812 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1813 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001814 if (TextUtils.isEmpty(value)) {
1815 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001816 }
Maggie83e03f52018-03-16 12:22:20 -07001817 Setting oldSetting = getSecureSetting(
1818 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1819 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001820 return false;
1821 }
Maggie83e03f52018-03-16 12:22:20 -07001822 String oldProviders = oldSetting.getValue();
1823 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1824 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1825 Set<String> newProvidersSet = new ArraySet<>();
1826 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08001827
Maggie83e03f52018-03-16 12:22:20 -07001828 String[] providerUpdates = value.split(",");
1829 boolean inputError = false;
1830 for (String provider : providerUpdates) {
1831 // do not update location_providers_allowed when input is invalid
1832 if (TextUtils.isEmpty(provider)) {
1833 inputError = true;
1834 break;
Svetoslav683914b2015-01-15 14:22:26 -08001835 }
Maggie83e03f52018-03-16 12:22:20 -07001836 final char prefix = provider.charAt(0);
1837 // do not update location_providers_allowed when input is invalid
1838 if (prefix != '+' && prefix != '-') {
1839 inputError = true;
1840 break;
Svetoslav683914b2015-01-15 14:22:26 -08001841 }
Maggie83e03f52018-03-16 12:22:20 -07001842 // skip prefix
1843 provider = provider.substring(1);
1844 if (prefix == '+') {
1845 newProvidersSet.add(provider);
1846 } else if (prefix == '-') {
1847 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08001848 }
Maggie83e03f52018-03-16 12:22:20 -07001849 }
1850 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
1851 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08001852 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001853 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07001854 mSettingsRegistry.notifyForSettingsChange(
1855 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07001856 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1857 }
Svetoslav683914b2015-01-15 14:22:26 -08001858 return false;
1859 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001860 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07001861 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
1862 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001863 }
1864
Svetoslav683914b2015-01-15 14:22:26 -08001865 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1866 int targetSdkVersion, String name) {
1867 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1868 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1869 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1870 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1871 + " This will soon become an error.");
1872 } else {
1873 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1874 + " This will soon become an error.");
1875 }
1876 } else {
1877 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1878 throw new IllegalArgumentException("You cannot change private secure settings.");
1879 } else {
1880 throw new IllegalArgumentException("You cannot keep your settings in"
1881 + " the secure settings.");
1882 }
1883 }
1884 }
1885
1886 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1887 if (requestingUserId == UserHandle.getCallingUserId()) {
1888 return requestingUserId;
1889 }
1890 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1891 Binder.getCallingUid(), requestingUserId, false, true,
1892 "get/set setting for user", null);
1893 }
1894
Svet Ganov53a441c2016-04-19 19:38:00 -07001895 private Bundle packageValueForCallResult(Setting setting,
1896 boolean trackingGeneration) {
1897 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001898 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001899 return NULL_SETTING_BUNDLE;
1900 }
1901 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001902 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001903 Bundle result = new Bundle();
1904 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001905 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001906
Svetoslav Ganove080da92016-12-21 17:10:35 -08001907 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001908 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001909 }
1910
1911 private static int getRequestingUserId(Bundle args) {
1912 final int callingUserId = UserHandle.getCallingUserId();
1913 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1914 : callingUserId;
1915 }
1916
Svet Ganov53a441c2016-04-19 19:38:00 -07001917 private boolean isTrackingGeneration(Bundle args) {
1918 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1919 }
1920
Svetoslav683914b2015-01-15 14:22:26 -08001921 private static String getSettingValue(Bundle args) {
1922 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1923 }
1924
Svetoslav Ganove080da92016-12-21 17:10:35 -08001925 private static String getSettingTag(Bundle args) {
1926 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1927 }
1928
1929 private static boolean getSettingMakeDefault(Bundle args) {
1930 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1931 }
1932
1933 private static int getResetModeEnforcingPermission(Bundle args) {
1934 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1935 switch (mode) {
1936 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1937 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1938 throw new SecurityException("Only system, shell/root on a "
1939 + "debuggable build can reset to untrusted defaults");
1940 }
1941 return mode;
1942 }
1943 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1944 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1945 throw new SecurityException("Only system, shell/root on a "
1946 + "debuggable build can reset untrusted changes");
1947 }
1948 return mode;
1949 }
1950 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1951 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1952 throw new SecurityException("Only system, shell/root on a "
1953 + "debuggable build can reset to trusted defaults");
1954 }
1955 return mode;
1956 }
1957 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1958 return mode;
1959 }
1960 }
1961 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1962 }
1963
1964 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1965 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1966 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1967 && (appId == SHELL_UID || appId == ROOT_UID));
1968 }
1969
Svetoslav683914b2015-01-15 14:22:26 -08001970 private static String getValidTableOrThrow(Uri uri) {
1971 if (uri.getPathSegments().size() > 0) {
1972 String table = uri.getPathSegments().get(0);
1973 if (DatabaseHelper.isValidTable(table)) {
1974 return table;
1975 }
1976 throw new IllegalArgumentException("Bad root path: " + table);
1977 }
1978 throw new IllegalArgumentException("Invalid URI:" + uri);
1979 }
1980
1981 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001982 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001983 return new MatrixCursor(projection, 0);
1984 }
1985 MatrixCursor cursor = new MatrixCursor(projection, 1);
1986 appendSettingToCursor(cursor, setting);
1987 return cursor;
1988 }
1989
1990 private static String[] normalizeProjection(String[] projection) {
1991 if (projection == null) {
1992 return ALL_COLUMNS;
1993 }
1994
1995 final int columnCount = projection.length;
1996 for (int i = 0; i < columnCount; i++) {
1997 String column = projection[i];
1998 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1999 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002000 }
2001 }
2002
Svetoslav683914b2015-01-15 14:22:26 -08002003 return projection;
2004 }
2005
2006 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002007 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002008 return;
2009 }
Svetoslav683914b2015-01-15 14:22:26 -08002010 final int columnCount = cursor.getColumnCount();
2011
2012 String[] values = new String[columnCount];
2013
2014 for (int i = 0; i < columnCount; i++) {
2015 String column = cursor.getColumnName(i);
2016
2017 switch (column) {
2018 case Settings.NameValueTable._ID: {
2019 values[i] = setting.getId();
2020 } break;
2021
2022 case Settings.NameValueTable.NAME: {
2023 values[i] = setting.getName();
2024 } break;
2025
2026 case Settings.NameValueTable.VALUE: {
2027 values[i] = setting.getValue();
2028 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002029 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002030 }
2031
Svetoslav683914b2015-01-15 14:22:26 -08002032 cursor.addRow(values);
2033 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002034
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002035 private static boolean isKeyValid(String key) {
2036 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2037 }
2038
Svetoslav683914b2015-01-15 14:22:26 -08002039 private static final class Arguments {
2040 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2041 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2042
2043 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2044 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2045
2046 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2047 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2048
2049 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2050 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2051
2052 public final String table;
2053 public final String name;
2054
2055 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2056 final int segmentSize = uri.getPathSegments().size();
2057 switch (segmentSize) {
2058 case 1: {
2059 if (where != null
2060 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2061 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2062 && whereArgs.length == 1) {
2063 name = whereArgs[0];
2064 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002065 return;
Svetoslav683914b2015-01-15 14:22:26 -08002066 } else if (where != null
2067 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2068 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2069 final int startIndex = Math.max(where.indexOf("'"),
2070 where.indexOf("\"")) + 1;
2071 final int endIndex = Math.max(where.lastIndexOf("'"),
2072 where.lastIndexOf("\""));
2073 name = where.substring(startIndex, endIndex);
2074 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002075 return;
Svetoslav683914b2015-01-15 14:22:26 -08002076 } else if (supportAll && where == null && whereArgs == null) {
2077 name = null;
2078 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002079 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002080 }
Svetoslav683914b2015-01-15 14:22:26 -08002081 } break;
2082
Svetoslav28494652015-02-12 14:11:42 -08002083 case 2: {
2084 if (where == null && whereArgs == null) {
2085 name = uri.getPathSegments().get(1);
2086 table = computeTableForSetting(uri, name);
2087 return;
2088 }
2089 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002090 }
Svetoslav28494652015-02-12 14:11:42 -08002091
2092 EventLogTags.writeUnsupportedSettingsQuery(
2093 uri.toSafeString(), where, Arrays.toString(whereArgs));
2094 String message = String.format( "Supported SQL:\n"
2095 + " uri content://some_table/some_property with null where and where args\n"
2096 + " uri content://some_table with query name=? and single name as arg\n"
2097 + " uri content://some_table with query name=some_name and null args\n"
2098 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2099 Arrays.toString(whereArgs));
2100 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002101 }
2102
Svetoslav28494652015-02-12 14:11:42 -08002103 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002104 String table = getValidTableOrThrow(uri);
2105
2106 if (name != null) {
2107 if (sSystemMovedToSecureSettings.contains(name)) {
2108 table = TABLE_SECURE;
2109 }
2110
2111 if (sSystemMovedToGlobalSettings.contains(name)) {
2112 table = TABLE_GLOBAL;
2113 }
2114
2115 if (sSecureMovedToGlobalSettings.contains(name)) {
2116 table = TABLE_GLOBAL;
2117 }
2118
2119 if (sGlobalMovedToSecureSettings.contains(name)) {
2120 table = TABLE_SECURE;
2121 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002122 }
Svetoslav683914b2015-01-15 14:22:26 -08002123
2124 return table;
2125 }
2126 }
2127
2128 final class SettingsRegistry {
2129 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2130
Svetoslav683914b2015-01-15 14:22:26 -08002131 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2132 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2133 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002134 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2135
2136 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002137
2138 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2139
Svet Ganov53a441c2016-04-19 19:38:00 -07002140 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002141
Svetoslav7e0683b2015-08-03 16:02:52 -07002142 private final Handler mHandler;
2143
Svet Ganov53a441c2016-04-19 19:38:00 -07002144 private final BackupManager mBackupManager;
2145
Amith Yamasani39452022017-03-21 15:23:47 -07002146 private String mSettingsCreationBuildId;
2147
Svetoslav683914b2015-01-15 14:22:26 -08002148 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002149 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002150 mGenerationRegistry = new GenerationRegistry(mLock);
2151 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002152 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002153 syncSsaidTableOnStart();
2154 }
2155
2156 private void generateUserKeyLocked(int userId) {
2157 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002158 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002159 final SecureRandom rand = new SecureRandom();
2160 rand.nextBytes(keyBytes);
2161
2162 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002163 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002164
2165 // Store the key in the ssaid table.
2166 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2167 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2168 true, SettingsState.SYSTEM_PACKAGE_NAME);
2169
2170 if (!success) {
2171 throw new IllegalStateException("Ssaid settings not accessible");
2172 }
2173 }
2174
Mark Rathjen7599f132017-01-23 14:15:54 -08002175 private byte[] getLengthPrefix(byte[] data) {
2176 return ByteBuffer.allocate(4).putInt(data.length).array();
2177 }
2178
Christopher Tateb218e762017-04-05 16:34:07 -07002179 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002180 // Read the user's key from the ssaid table.
2181 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002182 if (userKeySetting == null || userKeySetting.isNull()
2183 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002184 // Lazy initialize and store the user key.
2185 generateUserKeyLocked(userId);
2186 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002187 if (userKeySetting == null || userKeySetting.isNull()
2188 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002189 throw new IllegalStateException("User key not accessible");
2190 }
2191 }
2192 final String userKey = userKeySetting.getValue();
2193
2194 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002195 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2196
2197 // Validate that the key is of expected length.
2198 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2199 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002200 throw new IllegalStateException("User key invalid");
2201 }
2202
Mark Rathjen7599f132017-01-23 14:15:54 -08002203 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002204 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002205 m = Mac.getInstance("HmacSHA256");
2206 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002207 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002208 throw new IllegalStateException("HmacSHA256 is not available", e);
2209 } catch (InvalidKeyException e) {
2210 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002211 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002212
Mark Rathjenf42dd912017-06-05 19:04:34 -07002213 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002214 for (int i = 0; i < callingPkg.signatures.length; i++) {
2215 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002216 m.update(getLengthPrefix(sig), 0, 4);
2217 m.update(sig);
2218 }
Mark Rathjend891f012017-01-19 04:10:37 +00002219
2220 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002221 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2222 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002223
2224 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002225 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002226 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2227 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002228 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002229
2230 if (!success) {
2231 throw new IllegalStateException("Ssaid settings not accessible");
2232 }
2233
2234 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2235 }
2236
2237 public void syncSsaidTableOnStart() {
2238 synchronized (mLock) {
2239 // Verify that each user's packages and ssaid's are in sync.
2240 for (UserInfo user : mUserManager.getUsers(true)) {
2241 // Get all uids for the user's packages.
2242 final List<PackageInfo> packages;
2243 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002244 packages = mPackageManager.getInstalledPackages(
2245 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2246 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002247 } catch (RemoteException e) {
2248 throw new IllegalStateException("Package manager not available");
2249 }
2250 final Set<String> appUids = new HashSet<>();
2251 for (PackageInfo info : packages) {
2252 appUids.add(Integer.toString(info.applicationInfo.uid));
2253 }
2254
2255 // Get all uids currently stored in the user's ssaid table.
2256 final Set<String> ssaidUids = new HashSet<>(
2257 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2258 ssaidUids.remove(SSAID_USER_KEY);
2259
2260 // Perform a set difference for the appUids and ssaidUids.
2261 ssaidUids.removeAll(appUids);
2262
2263 // If there are ssaidUids left over they need to be removed from the table.
2264 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2265 user.id);
2266 for (String uid : ssaidUids) {
2267 ssaidSettings.deleteSettingLocked(uid);
2268 }
2269 }
2270 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002271 }
2272
Svetoslav683914b2015-01-15 14:22:26 -08002273 public List<String> getSettingsNamesLocked(int type, int userId) {
2274 final int key = makeKey(type, userId);
2275 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002276 if (settingsState == null) {
2277 return new ArrayList<String>();
2278 }
Svetoslav683914b2015-01-15 14:22:26 -08002279 return settingsState.getSettingNamesLocked();
2280 }
2281
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002282 public SparseBooleanArray getKnownUsersLocked() {
2283 SparseBooleanArray users = new SparseBooleanArray();
2284 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2285 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2286 }
2287 return users;
2288 }
2289
Kweku Adamsb0886f32017-10-31 15:32:09 -07002290 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002291 public SettingsState getSettingsLocked(int type, int userId) {
2292 final int key = makeKey(type, userId);
2293 return peekSettingsStateLocked(key);
2294 }
2295
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002296 public boolean ensureSettingsForUserLocked(int userId) {
2297 // First make sure this user actually exists.
2298 if (mUserManager.getUserInfo(userId) == null) {
2299 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2300 return false;
2301 }
2302
Svetoslav683914b2015-01-15 14:22:26 -08002303 // Migrate the setting for this user if needed.
2304 migrateLegacySettingsForUserIfNeededLocked(userId);
2305
2306 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002307 if (userId == UserHandle.USER_SYSTEM) {
2308 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002309 ensureSettingsStateLocked(globalKey);
2310 }
2311
2312 // Ensure secure settings loaded.
2313 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2314 ensureSettingsStateLocked(secureKey);
2315
2316 // Make sure the secure settings have an Android id set.
2317 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2318 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2319
2320 // Ensure system settings loaded.
2321 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2322 ensureSettingsStateLocked(systemKey);
2323
Mark Rathjend891f012017-01-19 04:10:37 +00002324 // Ensure secure settings loaded.
2325 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2326 ensureSettingsStateLocked(ssaidKey);
2327
Svetoslav683914b2015-01-15 14:22:26 -08002328 // Upgrade the settings to the latest version.
2329 UpgradeController upgrader = new UpgradeController(userId);
2330 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002331 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002332 }
2333
2334 private void ensureSettingsStateLocked(int key) {
2335 if (mSettingsStates.get(key) == null) {
2336 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002337 SettingsState settingsState = new SettingsState(getContext(), mLock,
2338 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002339 mSettingsStates.put(key, settingsState);
2340 }
2341 }
2342
2343 public void removeUserStateLocked(int userId, boolean permanently) {
2344 // We always keep the global settings in memory.
2345
2346 // Nuke system settings.
2347 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2348 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2349 if (systemSettingsState != null) {
2350 if (permanently) {
2351 mSettingsStates.remove(systemKey);
2352 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002353 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002354 systemSettingsState.destroyLocked(new Runnable() {
2355 @Override
2356 public void run() {
2357 mSettingsStates.remove(systemKey);
2358 }
2359 });
2360 }
2361 }
2362
2363 // Nuke secure settings.
2364 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2365 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2366 if (secureSettingsState != null) {
2367 if (permanently) {
2368 mSettingsStates.remove(secureKey);
2369 secureSettingsState.destroyLocked(null);
2370 } else {
2371 secureSettingsState.destroyLocked(new Runnable() {
2372 @Override
2373 public void run() {
2374 mSettingsStates.remove(secureKey);
2375 }
2376 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002377 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002378 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002379
Mark Rathjend891f012017-01-19 04:10:37 +00002380 // Nuke ssaid settings.
2381 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2382 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2383 if (ssaidSettingsState != null) {
2384 if (permanently) {
2385 mSettingsStates.remove(ssaidKey);
2386 ssaidSettingsState.destroyLocked(null);
2387 } else {
2388 ssaidSettingsState.destroyLocked(new Runnable() {
2389 @Override
2390 public void run() {
2391 mSettingsStates.remove(ssaidKey);
2392 }
2393 });
2394 }
2395 }
2396
Svet Ganov53a441c2016-04-19 19:38:00 -07002397 // Nuke generation tracking data
2398 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002399 }
2400
Svetoslav683914b2015-01-15 14:22:26 -08002401 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002402 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2403 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002404 final int key = makeKey(type, userId);
2405
Svetoslav Ganove080da92016-12-21 17:10:35 -08002406 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002407 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002408 if (settingsState != null) {
2409 success = settingsState.insertSettingLocked(name, value,
2410 tag, makeDefault, packageName);
2411 }
Svetoslav683914b2015-01-15 14:22:26 -08002412
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002413 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2414 settingsState.persistSyncLocked();
2415 }
2416
Svet Ganov53a441c2016-04-19 19:38:00 -07002417 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002418 notifyForSettingsChange(key, name);
2419 }
2420 return success;
2421 }
2422
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002423 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2424 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002425 final int key = makeKey(type, userId);
2426
Svetoslav Ganove080da92016-12-21 17:10:35 -08002427 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002428 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002429 if (settingsState != null) {
2430 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002431 }
Svetoslav683914b2015-01-15 14:22:26 -08002432
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002433 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2434 settingsState.persistSyncLocked();
2435 }
2436
Svet Ganov53a441c2016-04-19 19:38:00 -07002437 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002438 notifyForSettingsChange(key, name);
2439 }
2440 return success;
2441 }
2442
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002443 public boolean updateSettingLocked(int type, int userId, String name, String value,
2444 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2445 Set<String> criticalSettings) {
2446 final int key = makeKey(type, userId);
2447
2448 boolean success = false;
2449 SettingsState settingsState = peekSettingsStateLocked(key);
2450 if (settingsState != null) {
2451 success = settingsState.updateSettingLocked(name, value, tag,
2452 makeDefault, packageName);
2453 }
2454
2455 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2456 settingsState.persistSyncLocked();
2457 }
2458
2459 if (forceNotify || success) {
2460 notifyForSettingsChange(key, name);
2461 }
2462
2463 return success;
2464 }
2465
Svetoslav683914b2015-01-15 14:22:26 -08002466 public Setting getSettingLocked(int type, int userId, String name) {
2467 final int key = makeKey(type, userId);
2468
2469 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002470 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002471 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002472 }
Mark Rathjend891f012017-01-19 04:10:37 +00002473
2474 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002475 return settingsState.getSettingLocked(name);
2476 }
2477
Svetoslav Ganove080da92016-12-21 17:10:35 -08002478 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2479 String tag) {
2480 final int key = makeKey(type, userId);
2481 SettingsState settingsState = peekSettingsStateLocked(key);
2482 if (settingsState == null) {
2483 return;
2484 }
2485
2486 switch (mode) {
2487 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2488 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002489 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002490 Setting setting = settingsState.getSettingLocked(name);
2491 if (packageName.equals(setting.getPackageName())) {
2492 if (tag != null && !tag.equals(setting.getTag())) {
2493 continue;
2494 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002495 if (settingsState.resetSettingLocked(name)) {
2496 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002497 notifyForSettingsChange(key, name);
2498 }
2499 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002500 if (someSettingChanged) {
2501 settingsState.persistSyncLocked();
2502 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002503 }
2504 } break;
2505
2506 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2507 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002508 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002509 Setting setting = settingsState.getSettingLocked(name);
2510 if (!SettingsState.isSystemPackage(getContext(),
2511 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002512 if (settingsState.resetSettingLocked(name)) {
2513 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002514 notifyForSettingsChange(key, name);
2515 }
2516 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002517 if (someSettingChanged) {
2518 settingsState.persistSyncLocked();
2519 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002520 }
2521 } break;
2522
2523 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2524 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002525 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002526 Setting setting = settingsState.getSettingLocked(name);
2527 if (!SettingsState.isSystemPackage(getContext(),
2528 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002529 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002530 if (settingsState.resetSettingLocked(name)) {
2531 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002532 notifyForSettingsChange(key, name);
2533 }
2534 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002535 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002536 notifyForSettingsChange(key, name);
2537 }
2538 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002539 if (someSettingChanged) {
2540 settingsState.persistSyncLocked();
2541 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002542 }
2543 } break;
2544
2545 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2546 for (String name : settingsState.getSettingNamesLocked()) {
2547 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002548 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002549 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002550 if (settingsState.resetSettingLocked(name)) {
2551 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002552 notifyForSettingsChange(key, name);
2553 }
2554 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002555 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002556 notifyForSettingsChange(key, name);
2557 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002558 if (someSettingChanged) {
2559 settingsState.persistSyncLocked();
2560 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002561 }
2562 } break;
2563 }
2564 }
2565
Zimuzoc56192c2018-07-25 10:40:01 +01002566 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002567 // Global and secure settings are signature protected. Apps signed
2568 // by the platform certificate are generally not uninstalled and
2569 // the main exception is tests. We trust components signed
2570 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002571
2572 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2573 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002574 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002575 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002576 }
Svetoslav683914b2015-01-15 14:22:26 -08002577 }
2578
Mark Rathjend891f012017-01-19 04:10:37 +00002579 public void onUidRemovedLocked(int uid) {
2580 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2581 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002582 if (ssaidSettings != null) {
2583 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2584 }
Mark Rathjend891f012017-01-19 04:10:37 +00002585 }
2586
Kweku Adamsb0886f32017-10-31 15:32:09 -07002587 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002588 private SettingsState peekSettingsStateLocked(int key) {
2589 SettingsState settingsState = mSettingsStates.get(key);
2590 if (settingsState != null) {
2591 return settingsState;
2592 }
2593
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002594 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2595 return null;
2596 }
Svetoslav683914b2015-01-15 14:22:26 -08002597 return mSettingsStates.get(key);
2598 }
2599
2600 private void migrateAllLegacySettingsIfNeeded() {
2601 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002602 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002603 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002604 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002605 return;
2606 }
2607
Amith Yamasani39452022017-03-21 15:23:47 -07002608 mSettingsCreationBuildId = Build.ID;
2609
Svetoslav683914b2015-01-15 14:22:26 -08002610 final long identity = Binder.clearCallingIdentity();
2611 try {
2612 List<UserInfo> users = mUserManager.getUsers(true);
2613
2614 final int userCount = users.size();
2615 for (int i = 0; i < userCount; i++) {
2616 final int userId = users.get(i).id;
2617
2618 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2619 SQLiteDatabase database = dbHelper.getWritableDatabase();
2620 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2621
2622 // Upgrade to the latest version.
2623 UpgradeController upgrader = new UpgradeController(userId);
2624 upgrader.upgradeIfNeededLocked();
2625
2626 // Drop from memory if not a running user.
2627 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2628 removeUserStateLocked(userId, false);
2629 }
2630 }
2631 } finally {
2632 Binder.restoreCallingIdentity(identity);
2633 }
2634 }
2635 }
2636
2637 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2638 // Every user has secure settings and if no file we need to migrate.
2639 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2640 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002641 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002642 return;
2643 }
2644
2645 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2646 SQLiteDatabase database = dbHelper.getWritableDatabase();
2647
2648 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2649 }
2650
2651 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2652 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002653 // Move over the system settings.
2654 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2655 ensureSettingsStateLocked(systemKey);
2656 SettingsState systemSettings = mSettingsStates.get(systemKey);
2657 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2658 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002659
2660 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002661 // Do this after System settings, since this is the first thing we check when deciding
2662 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002663 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2664 ensureSettingsStateLocked(secureKey);
2665 SettingsState secureSettings = mSettingsStates.get(secureKey);
2666 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2667 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2668 secureSettings.persistSyncLocked();
2669
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002670 // Move over the global settings if owner.
2671 // Do this last, since this is the first thing we check when deciding
2672 // to skip over migration from db to xml for owner user.
2673 if (userId == UserHandle.USER_SYSTEM) {
2674 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2675 ensureSettingsStateLocked(globalKey);
2676 SettingsState globalSettings = mSettingsStates.get(globalKey);
2677 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002678 // If this was just created
2679 if (mSettingsCreationBuildId != null) {
2680 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2681 mSettingsCreationBuildId, null, true,
2682 SettingsState.SYSTEM_PACKAGE_NAME);
2683 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002684 globalSettings.persistSyncLocked();
2685 }
Svetoslav683914b2015-01-15 14:22:26 -08002686
2687 // Drop the database as now all is moved and persisted.
2688 if (DROP_DATABASE_ON_MIGRATION) {
2689 dbHelper.dropDatabase();
2690 } else {
2691 dbHelper.backupDatabase();
2692 }
2693 }
2694
2695 private void migrateLegacySettingsLocked(SettingsState settingsState,
2696 SQLiteDatabase database, String table) {
2697 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2698 queryBuilder.setTables(table);
2699
2700 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2701 null, null, null, null, null);
2702
2703 if (cursor == null) {
2704 return;
2705 }
2706
2707 try {
2708 if (!cursor.moveToFirst()) {
2709 return;
2710 }
2711
2712 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2713 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2714
2715 settingsState.setVersionLocked(database.getVersion());
2716
2717 while (!cursor.isAfterLast()) {
2718 String name = cursor.getString(nameColumnIdx);
2719 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002720 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002721 SettingsState.SYSTEM_PACKAGE_NAME);
2722 cursor.moveToNext();
2723 }
2724 } finally {
2725 cursor.close();
2726 }
2727 }
2728
Andreas Gampeb58893072018-09-05 16:52:31 -07002729 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002730 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2731 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2732
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002733 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002734 return;
2735 }
2736
2737 final int userId = getUserIdFromKey(secureSettings.mKey);
2738
2739 final UserInfo user;
2740 final long identity = Binder.clearCallingIdentity();
2741 try {
2742 user = mUserManager.getUserInfo(userId);
2743 } finally {
2744 Binder.restoreCallingIdentity(identity);
2745 }
2746 if (user == null) {
2747 // Can happen due to races when deleting users - treat as benign.
2748 return;
2749 }
2750
2751 String androidId = Long.toHexString(new SecureRandom().nextLong());
2752 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002753 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002754
2755 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2756 + "] for user " + userId);
2757
2758 // Write a drop box entry if it's a restricted profile
2759 if (user.isRestricted()) {
2760 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2761 Context.DROPBOX_SERVICE);
2762 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2763 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2764 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2765 }
2766 }
2767 }
2768
2769 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07002770 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07002771 mGenerationRegistry.incrementGeneration(key);
2772
Svet Ganov945864c2018-03-22 21:49:10 -07002773 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06002774 final long token = Binder.clearCallingIdentity();
2775 try {
2776 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2777 // When the global kill switch is updated, send the
2778 // change notification for the location setting.
2779 notifyLocationChangeForRunningUsers();
2780 }
2781 notifyGlobalSettingChangeForRunningUsers(key, name);
2782 } finally {
2783 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07002784 }
Svet Ganov945864c2018-03-22 21:49:10 -07002785 } else {
2786 final int userId = getUserIdFromKey(key);
2787 final Uri uri = getNotificationUriFor(key, name);
2788 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2789 userId, 0, uri).sendToTarget();
2790 if (isSecureSettingsKey(key)) {
2791 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2792 sSecureCloneToManagedSettings);
2793 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2794 sSystemCloneFromParentOnDependency.values());
2795 } else if (isSystemSettingsKey(key)) {
2796 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2797 sSystemCloneToManagedSettings);
2798 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002799 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002800
Svet Ganov945864c2018-03-22 21:49:10 -07002801 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07002802 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002803 }
2804
Svet Ganov53a441c2016-04-19 19:38:00 -07002805 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002806 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002807 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002808 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002809 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002810 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07002811 final int key = makeKey(type, profileId);
2812 // Increment the generation first, so observers always see the new value
2813 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07002814 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002815 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002816 }
2817 }
2818 }
Svetoslav683914b2015-01-15 14:22:26 -08002819 }
2820
Svet Ganov945864c2018-03-22 21:49:10 -07002821 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
2822 // Important: No need to update generation for each user as there
2823 // is a singleton generation entry for the global settings which
2824 // is already incremented be the caller.
2825 final Uri uri = getNotificationUriFor(key, name);
2826 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
2827 for (int i = 0; i < users.size(); i++) {
2828 final int userId = users.get(i).id;
2829 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
2830 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2831 userId, 0, uri).sendToTarget();
2832 }
2833 }
2834 }
2835
Makoto Onuki0000d322017-11-28 16:31:47 -08002836 private void notifyLocationChangeForRunningUsers() {
2837 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2838
2839 for (int i = 0; i < users.size(); i++) {
2840 final int userId = users.get(i).id;
2841
2842 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2843 continue;
2844 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002845
Svet Ganov945864c2018-03-22 21:49:10 -07002846 // Increment the generation first, so observers always see the new value
2847 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2848 mGenerationRegistry.incrementGeneration(key);
2849
2850 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08002851 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2852 userId, 0, uri).sendToTarget();
2853 }
2854 }
2855
Svetoslav683914b2015-01-15 14:22:26 -08002856 private boolean isGlobalSettingsKey(int key) {
2857 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2858 }
2859
2860 private boolean isSystemSettingsKey(int key) {
2861 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2862 }
2863
2864 private boolean isSecureSettingsKey(int key) {
2865 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2866 }
2867
Mark Rathjend891f012017-01-19 04:10:37 +00002868 private boolean isSsaidSettingsKey(int key) {
2869 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2870 }
2871
Svetoslav683914b2015-01-15 14:22:26 -08002872 private File getSettingsFile(int key) {
2873 if (isGlobalSettingsKey(key)) {
2874 final int userId = getUserIdFromKey(key);
2875 return new File(Environment.getUserSystemDirectory(userId),
2876 SETTINGS_FILE_GLOBAL);
2877 } else if (isSystemSettingsKey(key)) {
2878 final int userId = getUserIdFromKey(key);
2879 return new File(Environment.getUserSystemDirectory(userId),
2880 SETTINGS_FILE_SYSTEM);
2881 } else if (isSecureSettingsKey(key)) {
2882 final int userId = getUserIdFromKey(key);
2883 return new File(Environment.getUserSystemDirectory(userId),
2884 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002885 } else if (isSsaidSettingsKey(key)) {
2886 final int userId = getUserIdFromKey(key);
2887 return new File(Environment.getUserSystemDirectory(userId),
2888 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002889 } else {
2890 throw new IllegalArgumentException("Invalid settings key:" + key);
2891 }
2892 }
2893
2894 private Uri getNotificationUriFor(int key, String name) {
2895 if (isGlobalSettingsKey(key)) {
2896 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2897 : Settings.Global.CONTENT_URI;
2898 } else if (isSecureSettingsKey(key)) {
2899 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2900 : Settings.Secure.CONTENT_URI;
2901 } else if (isSystemSettingsKey(key)) {
2902 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2903 : Settings.System.CONTENT_URI;
2904 } else {
2905 throw new IllegalArgumentException("Invalid settings key:" + key);
2906 }
2907 }
2908
2909 private int getMaxBytesPerPackageForType(int type) {
2910 switch (type) {
2911 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002912 case SETTINGS_TYPE_SECURE:
2913 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002914 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2915 }
2916
2917 default: {
2918 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2919 }
2920 }
2921 }
2922
Svetoslav7e0683b2015-08-03 16:02:52 -07002923 private final class MyHandler extends Handler {
2924 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2925 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2926
2927 public MyHandler(Looper looper) {
2928 super(looper);
2929 }
2930
2931 @Override
2932 public void handleMessage(Message msg) {
2933 switch (msg.what) {
2934 case MSG_NOTIFY_URI_CHANGED: {
2935 final int userId = msg.arg1;
2936 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002937 try {
2938 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2939 } catch (SecurityException e) {
2940 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2941 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002942 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002943 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2944 }
2945 } break;
2946
2947 case MSG_NOTIFY_DATA_CHANGED: {
2948 mBackupManager.dataChanged();
2949 } break;
2950 }
2951 }
2952 }
2953
Svetoslav683914b2015-01-15 14:22:26 -08002954 private final class UpgradeController {
Beverly91d0a632018-07-02 16:45:00 -04002955 private static final int SETTINGS_VERSION = 171;
Svetoslav683914b2015-01-15 14:22:26 -08002956
2957 private final int mUserId;
2958
2959 public UpgradeController(int userId) {
2960 mUserId = userId;
2961 }
2962
2963 public void upgradeIfNeededLocked() {
2964 // The version of all settings for a user is the same (all users have secure).
2965 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002966 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002967
2968 // Try an update from the current state.
2969 final int oldVersion = secureSettings.getVersionLocked();
2970 final int newVersion = SETTINGS_VERSION;
2971
Svet Ganovc9755bc2015-03-28 13:21:22 -07002972 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002973 if (oldVersion == newVersion) {
2974 return;
2975 }
2976
2977 // Try to upgrade.
2978 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2979
2980 // If upgrade failed start from scratch and upgrade.
2981 if (curVersion != newVersion) {
2982 // Drop state we have for this user.
2983 removeUserStateLocked(mUserId, true);
2984
2985 // Recreate the database.
2986 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2987 SQLiteDatabase database = dbHelper.getWritableDatabase();
2988 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2989
2990 // Migrate the settings for this user.
2991 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2992
2993 // Now upgrade should work fine.
2994 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002995
2996 // Make a note what happened, so we don't wonder why data was lost
2997 String reason = "Settings rebuilt! Current version: "
2998 + curVersion + " while expected: " + newVersion;
2999 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003000 Settings.Global.DATABASE_DOWNGRADE_REASON,
3001 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003002 }
3003
3004 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003005 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003006 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003007 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003008 globalSettings.setVersionLocked(newVersion);
3009 }
3010
3011 // Set the secure settings version.
3012 secureSettings.setVersionLocked(newVersion);
3013
3014 // Set the system settings version.
3015 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003016 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003017 systemSettings.setVersionLocked(newVersion);
3018 }
3019
3020 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003021 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003022 }
3023
3024 private SettingsState getSecureSettingsLocked(int userId) {
3025 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3026 }
3027
Mark Rathjend891f012017-01-19 04:10:37 +00003028 private SettingsState getSsaidSettingsLocked(int userId) {
3029 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3030 }
3031
Svetoslav683914b2015-01-15 14:22:26 -08003032 private SettingsState getSystemSettingsLocked(int userId) {
3033 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3034 }
3035
Jeff Brown503cffc2015-03-26 18:08:51 -07003036 /**
3037 * You must perform all necessary mutations to bring the settings
3038 * for this user from the old to the new version. When you add a new
3039 * upgrade step you *must* update SETTINGS_VERSION.
3040 *
3041 * This is an example of moving a setting from secure to global.
3042 *
3043 * // v119: Example settings changes.
3044 * if (currentVersion == 118) {
3045 * if (userId == UserHandle.USER_OWNER) {
3046 * // Remove from the secure settings.
3047 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3048 * String name = "example_setting_to_move";
3049 * String value = secureSettings.getSetting(name);
3050 * secureSettings.deleteSetting(name);
3051 *
3052 * // Add to the global settings.
3053 * SettingsState globalSettings = getGlobalSettingsLocked();
3054 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3055 * }
3056 *
3057 * // Update the current version.
3058 * currentVersion = 119;
3059 * }
3060 */
Svetoslav683914b2015-01-15 14:22:26 -08003061 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3062 if (DEBUG) {
3063 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3064 + oldVersion + " to version: " + newVersion);
3065 }
3066
Jeff Brown503cffc2015-03-26 18:08:51 -07003067 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003068
John Spurlocke11ae112015-05-11 16:09:03 -04003069 // v119: Reset zen + ringer mode.
3070 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003071 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003072 final SettingsState globalSettings = getGlobalSettingsLocked();
3073 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003074 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3075 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003076 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003077 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3078 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003079 }
3080 currentVersion = 119;
3081 }
3082
Jason Monk27bbb2d2015-03-31 16:46:39 -04003083 // v120: Add double tap to wake setting.
3084 if (currentVersion == 119) {
3085 SettingsState secureSettings = getSecureSettingsLocked(userId);
3086 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3087 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003088 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003089 SettingsState.SYSTEM_PACKAGE_NAME);
3090
3091 currentVersion = 120;
3092 }
3093
Svetoslav7e0683b2015-08-03 16:02:52 -07003094 if (currentVersion == 120) {
3095 // Before 121, we used a different string encoding logic. We just bump the
3096 // version here; SettingsState knows how to handle pre-version 120 files.
3097 currentVersion = 121;
3098 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003099
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003100 if (currentVersion == 121) {
3101 // Version 122: allow OEMs to set a default payment component in resources.
3102 // Note that we only write the default if no default has been set;
3103 // if there is, we just leave the default at whatever it currently is.
3104 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3105 String defaultComponent = (getContext().getResources().getString(
3106 R.string.def_nfc_payment_component));
3107 Setting currentSetting = secureSettings.getSettingLocked(
3108 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3109 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003110 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003111 secureSettings.insertSettingLocked(
3112 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003113 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003114 }
3115 currentVersion = 122;
3116 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003117
3118 if (currentVersion == 122) {
3119 // Version 123: Adding a default value for the ability to add a user from
3120 // the lock screen.
3121 if (userId == UserHandle.USER_SYSTEM) {
3122 final SettingsState globalSettings = getGlobalSettingsLocked();
3123 Setting currentSetting = globalSettings.getSettingLocked(
3124 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003125 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003126 globalSettings.insertSettingLocked(
3127 Settings.Global.ADD_USERS_WHEN_LOCKED,
3128 getContext().getResources().getBoolean(
3129 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003130 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003131 }
3132 }
3133 currentVersion = 123;
3134 }
Bryce Leebd179282015-12-17 19:01:37 -08003135
3136 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003137 final SettingsState globalSettings = getGlobalSettingsLocked();
3138 String defaultDisabledProfiles = (getContext().getResources().getString(
3139 R.string.def_bluetooth_disabled_profiles));
3140 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003141 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003142 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003143 }
3144
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003145 if (currentVersion == 124) {
3146 // Version 124: allow OEMs to set a default value for whether IME should be
3147 // shown when a physical keyboard is connected.
3148 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3149 Setting currentSetting = secureSettings.getSettingLocked(
3150 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003151 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003152 secureSettings.insertSettingLocked(
3153 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3154 getContext().getResources().getBoolean(
3155 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003156 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003157 }
3158 currentVersion = 125;
3159 }
3160
Ruben Brunk98576cf2016-03-07 18:54:28 -08003161 if (currentVersion == 125) {
3162 // Version 125: Allow OEMs to set the default VR service.
3163 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3164
3165 Setting currentSetting = secureSettings.getSettingLocked(
3166 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003167 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003168 ArraySet<ComponentName> l =
3169 SystemConfig.getInstance().getDefaultVrComponents();
3170
3171 if (l != null && !l.isEmpty()) {
3172 StringBuilder b = new StringBuilder();
3173 boolean start = true;
3174 for (ComponentName c : l) {
3175 if (!start) {
3176 b.append(':');
3177 }
3178 b.append(c.flattenToString());
3179 start = false;
3180 }
3181 secureSettings.insertSettingLocked(
3182 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003183 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003184 }
3185
3186 }
3187 currentVersion = 126;
3188 }
3189
Daniel U02ba6122016-04-01 18:41:42 +01003190 if (currentVersion == 126) {
3191 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3192 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3193 if (mUserManager.isManagedProfile(userId)) {
3194 final SettingsState systemSecureSettings =
3195 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3196
3197 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3198 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003199 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003200 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3201 secureSettings.insertSettingLocked(
3202 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003203 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003204 SettingsState.SYSTEM_PACKAGE_NAME);
3205 }
3206
3207 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3208 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003209 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003210 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3211 secureSettings.insertSettingLocked(
3212 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003213 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003214 SettingsState.SYSTEM_PACKAGE_NAME);
3215 }
3216 }
3217 currentVersion = 127;
3218 }
3219
Steven Ngdc20ba62016-04-26 18:19:04 +01003220 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003221 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003222 currentVersion = 128;
3223 }
3224
Julia Reynolds1f721e12016-07-11 08:50:58 -04003225 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003226 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003227 currentVersion = 129;
3228 }
3229
Dan Sandler71f85e92016-07-20 13:46:05 -04003230 if (currentVersion == 129) {
3231 // default longpress timeout changed from 500 to 400. If unchanged from the old
3232 // default, update to the new default.
3233 final SettingsState systemSecureSettings =
3234 getSecureSettingsLocked(userId);
3235 final String oldValue = systemSecureSettings.getSettingLocked(
3236 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3237 if (TextUtils.equals("500", oldValue)) {
3238 systemSecureSettings.insertSettingLocked(
3239 Settings.Secure.LONG_PRESS_TIMEOUT,
3240 String.valueOf(getContext().getResources().getInteger(
3241 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003242 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003243 }
3244 currentVersion = 130;
3245 }
3246
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003247 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003248 // Split Ambient settings
3249 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3250 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3251 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3252
3253 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003254 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003255 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003256 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003257 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003258 }
3259 currentVersion = 131;
3260 }
3261
3262 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003263 // Initialize new multi-press timeout to default value
3264 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3265 final String oldValue = systemSecureSettings.getSettingLocked(
3266 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3267 if (TextUtils.equals(null, oldValue)) {
3268 systemSecureSettings.insertSettingLocked(
3269 Settings.Secure.MULTI_PRESS_TIMEOUT,
3270 String.valueOf(getContext().getResources().getInteger(
3271 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003272 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003273 }
3274
Adrian Roos69741a22016-10-21 14:49:17 -07003275 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003276 }
3277
Adrian Roos69741a22016-10-21 14:49:17 -07003278 if (currentVersion == 132) {
3279 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003280 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3281 String defaultSyncParentSounds = (getContext().getResources()
3282 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3283 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003284 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3285 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003286 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003287 }
3288
Adrian Roos69741a22016-10-21 14:49:17 -07003289 if (currentVersion == 133) {
3290 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003291 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3292 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3293 null) {
3294 String defaultEndButtonBehavior = Integer.toString(getContext()
3295 .getResources().getInteger(R.integer.def_end_button_behavior));
3296 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003297 defaultEndButtonBehavior, null, true,
3298 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003299 }
Adrian Roos69741a22016-10-21 14:49:17 -07003300 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003301 }
3302
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003303 if (currentVersion == 134) {
3304 // Remove setting that specifies if magnification values should be preserved.
3305 // This setting defaulted to true and never has a UI.
3306 getSecureSettingsLocked(userId).deleteSettingLocked(
3307 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3308 currentVersion = 135;
3309 }
3310
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003311 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003312 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003313 currentVersion = 136;
3314 }
3315
Mark Rathjend891f012017-01-19 04:10:37 +00003316 if (currentVersion == 136) {
3317 // Version 136: Store legacy SSAID for all apps currently installed on the
3318 // device as first step in migrating SSAID to be unique per application.
3319
3320 final boolean isUpgrade;
3321 try {
3322 isUpgrade = mPackageManager.isUpgrade();
3323 } catch (RemoteException e) {
3324 throw new IllegalStateException("Package manager not available");
3325 }
3326 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3327 // user data or first boot on a new device should use new ssaid generation.
3328 if (isUpgrade) {
3329 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003330 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3331 userId, Settings.Secure.ANDROID_ID);
3332 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3333 || legacySsaidSetting.getValue() == null) {
3334 throw new IllegalStateException("Legacy ssaid not accessible");
3335 }
3336 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003337
3338 // Fill each uid with the legacy ssaid to be backwards compatible.
3339 final List<PackageInfo> packages;
3340 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003341 packages = mPackageManager.getInstalledPackages(
3342 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3343 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003344 } catch (RemoteException e) {
3345 throw new IllegalStateException("Package manager not available");
3346 }
3347
3348 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3349 for (PackageInfo info : packages) {
3350 // Check if the UID already has an entry in the table.
3351 final String uid = Integer.toString(info.applicationInfo.uid);
3352 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3353
3354 if (ssaid.isNull() || ssaid.getValue() == null) {
3355 // Android Id doesn't exist for this package so create it.
3356 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3357 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003358 if (DEBUG) {
3359 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3360 }
Mark Rathjend891f012017-01-19 04:10:37 +00003361 }
3362 }
3363 }
3364
3365 currentVersion = 137;
3366 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003367 if (currentVersion == 137) {
3368 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3369 // default value set to 1. The user can no longer change the value of this
3370 // setting through the UI.
3371 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3372 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003373 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3374 && secureSetting.getSettingLocked(
3375 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3376
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003377 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3378 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003379 // For managed profiles with profile owners, DevicePolicyManagerService
3380 // may want to set the user restriction in this case
3381 secureSetting.insertSettingLocked(
3382 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3383 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003384 }
3385 currentVersion = 138;
3386 }
Mark Rathjend891f012017-01-19 04:10:37 +00003387
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003388 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003389 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003390 currentVersion = 139;
3391 }
3392
Phil Weaver385912e2017-02-10 10:06:56 -08003393 if (currentVersion == 139) {
3394 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3395 // the user can no longer change the value of this setting through the UI.
3396 // Force to true.
3397 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3398 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3399 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3400 currentVersion = 140;
3401 }
3402
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003403 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003404 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003405 currentVersion = 141;
3406 }
3407
Svet Ganov13701552017-02-23 12:45:17 -08003408 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003409 // This implementation was incorrectly setting the current value of
3410 // settings changed by non-system packages as the default which default
3411 // is set by the system. We add a new upgrade step at the end to properly
3412 // handle this case which would also fix incorrect changes made by the
3413 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003414 currentVersion = 142;
3415 }
3416
Stephen Chen5d0922f2017-03-27 10:28:04 -07003417 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003418 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003419 if (userId == UserHandle.USER_SYSTEM) {
3420 final SettingsState globalSettings = getGlobalSettingsLocked();
3421 Setting currentSetting = globalSettings.getSettingLocked(
3422 Settings.Global.WIFI_WAKEUP_ENABLED);
3423 if (currentSetting.isNull()) {
3424 globalSettings.insertSettingLocked(
3425 Settings.Global.WIFI_WAKEUP_ENABLED,
3426 getContext().getResources().getBoolean(
3427 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3428 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3429 }
3430 }
3431
3432 currentVersion = 143;
3433 }
3434
Felipe Lemeff355092017-04-03 12:55:02 -07003435 if (currentVersion == 143) {
3436 // Version 144: Set a default value for Autofill service.
3437 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3438 final Setting currentSetting = secureSettings
3439 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3440 if (currentSetting.isNull()) {
3441 final String defaultValue = getContext().getResources().getString(
3442 com.android.internal.R.string.config_defaultAutofillService);
3443 if (defaultValue != null) {
3444 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3445 + "for user " + userId);
3446 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3447 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3448 }
3449 }
3450
3451 currentVersion = 144;
3452 }
3453
Jeremy Joslin45caa252017-05-04 11:22:46 -07003454 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003455 // Version 145: Removed
3456 currentVersion = 145;
3457 }
3458
3459 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003460 // Version 146: In step 142 we had a bug where incorrectly
3461 // some settings were considered system set and as a result
3462 // made the default and marked as the default being set by
3463 // the system. Here reevaluate the default and default system
3464 // set flags. This would both fix corruption by the old impl
3465 // of step 142 and also properly handle devices which never
3466 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003467 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003468 SettingsState globalSettings = getGlobalSettingsLocked();
3469 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3470 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003471 }
3472
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003473 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3474 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3475 secureSettings.persistSyncLocked();
3476
3477 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3478 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3479 systemSettings.persistSyncLocked();
3480
Amin Shaikh86367962017-06-07 08:58:22 -07003481 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003482 }
3483
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003484 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003485 // Version 147: Removed. (This version previously allowed showing the
3486 // "wifi_wakeup_available" setting).
3487 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003488 currentVersion = 147;
3489 }
3490
3491 if (currentVersion == 147) {
3492 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003493 if (userId == UserHandle.USER_SYSTEM) {
3494 final SettingsState globalSettings = getGlobalSettingsLocked();
3495 final Setting currentSetting = globalSettings.getSettingLocked(
3496 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3497 if (currentSetting.isNull()) {
3498 globalSettings.insertSettingLocked(
3499 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3500 getContext().getResources().getBoolean(
3501 R.bool.def_restrict_background_data) ? "1" : "0",
3502 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3503 }
3504 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003505 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003506 }
3507
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003508 if (currentVersion == 148) {
3509 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3510 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3511 final String oldValue = systemSecureSettings.getSettingLocked(
3512 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3513 if (TextUtils.equals(null, oldValue)) {
3514 final String defaultValue = getContext().getResources().getString(
3515 R.string.def_backup_manager_constants);
3516 if (!TextUtils.isEmpty(defaultValue)) {
3517 systemSecureSettings.insertSettingLocked(
3518 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3519 true, SettingsState.SYSTEM_PACKAGE_NAME);
3520 }
3521 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003522 currentVersion = 149;
3523 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003524
3525 if (currentVersion == 149) {
3526 // Version 150: Set a default value for mobile data always on
3527 final SettingsState globalSettings = getGlobalSettingsLocked();
3528 final Setting currentSetting = globalSettings.getSettingLocked(
3529 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3530 if (currentSetting.isNull()) {
3531 globalSettings.insertSettingLocked(
3532 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3533 getContext().getResources().getBoolean(
3534 R.bool.def_mobile_data_always_on) ? "1" : "0",
3535 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3536 }
3537
3538 currentVersion = 150;
3539 }
3540
Mike Digman4af4a6f2018-01-16 14:49:38 -08003541 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003542 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003543 currentVersion = 151;
3544 }
3545
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003546 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003547 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3548 // by default but it is now no longer configurable).
3549 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003550 currentVersion = 152;
3551 }
3552
Joe LaPenna250d7842018-01-25 10:19:42 -08003553 if (currentVersion == 152) {
3554 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3555 currentVersion = 153;
3556 }
3557
Ben Linb4df8bc2018-01-29 11:48:20 -08003558 if (currentVersion == 153) {
3559 // Version 154: Read notification badge configuration from config.
3560 // If user has already set the value, don't do anything.
3561 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3562 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3563 Settings.Secure.NOTIFICATION_BADGING);
3564 if (showNotificationBadges.isNull()) {
3565 final boolean defaultValue = getContext().getResources().getBoolean(
3566 com.android.internal.R.bool.config_notificationBadging);
3567 systemSecureSettings.insertSettingLocked(
3568 Secure.NOTIFICATION_BADGING,
3569 defaultValue ? "1" : "0",
3570 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3571 }
3572 currentVersion = 154;
3573 }
3574
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003575 if (currentVersion == 154) {
3576 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3577 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3578 final String oldValue = systemSecureSettings.getSettingLocked(
3579 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3580 if (TextUtils.equals(null, oldValue)) {
3581 final String defaultValue = getContext().getResources().getString(
3582 R.string.def_backup_local_transport_parameters);
3583 if (!TextUtils.isEmpty(defaultValue)) {
3584 systemSecureSettings.insertSettingLocked(
3585 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3586 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3587 }
3588
3589 }
3590 currentVersion = 155;
3591 }
3592
Beverlyda904812018-03-02 09:55:30 -05003593 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003594 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003595 final SettingsState globalSettings = getGlobalSettingsLocked();
3596 final String oldValue = globalSettings.getSettingLocked(
3597 Global.CHARGING_STARTED_SOUND).getValue();
3598 final String oldDefault = getContext().getResources().getString(
3599 R.string.def_wireless_charging_started_sound);
3600 if (TextUtils.equals(null, oldValue)
3601 || TextUtils.equals(oldValue, oldDefault)) {
3602 final String defaultValue = getContext().getResources().getString(
3603 R.string.def_charging_started_sound);
3604 if (!TextUtils.isEmpty(defaultValue)) {
3605 globalSettings.insertSettingLocked(
3606 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3607 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3608 }
3609
3610 }
3611 currentVersion = 156;
3612 }
3613
Beverly09da25f2018-02-26 09:17:07 -05003614 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003615 // Version 157: Set a default value for zen duration,
3616 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003617 final SettingsState globalSettings = getGlobalSettingsLocked();
3618 final Setting currentSetting = globalSettings.getSettingLocked(
3619 Global.ZEN_DURATION);
3620 if (currentSetting.isNull()) {
3621 String defaultZenDuration = Integer.toString(getContext()
3622 .getResources().getInteger(R.integer.def_zen_duration));
3623 globalSettings.insertSettingLocked(
3624 Global.ZEN_DURATION, defaultZenDuration,
3625 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3626 }
Beverly09da25f2018-02-26 09:17:07 -05003627 currentVersion = 157;
3628 }
Annie Mengd069a882018-03-13 15:31:40 +00003629
3630 if (currentVersion == 157) {
3631 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3632 final SettingsState globalSettings = getGlobalSettingsLocked();
3633 final String oldValue = globalSettings.getSettingLocked(
3634 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3635 if (TextUtils.equals(null, oldValue)) {
3636 final String defaultValue = getContext().getResources().getString(
3637 R.string.def_backup_agent_timeout_parameters);
3638 if (!TextUtils.isEmpty(defaultValue)) {
3639 globalSettings.insertSettingLocked(
3640 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3641 null, true,
3642 SettingsState.SYSTEM_PACKAGE_NAME);
3643 }
3644 }
3645 currentVersion = 158;
3646 }
Roshan Pius9c396672018-03-02 14:54:13 -08003647
3648 if (currentVersion == 158) {
3649 // Remove setting that specifies wifi bgscan throttling params
3650 getGlobalSettingsLocked().deleteSettingLocked(
3651 "wifi_scan_background_throttle_interval_ms");
3652 getGlobalSettingsLocked().deleteSettingLocked(
3653 "wifi_scan_background_throttle_package_whitelist");
3654 currentVersion = 159;
3655 }
3656
Pavel Grafovc5c97302018-03-19 13:37:15 +00003657 if (currentVersion == 159) {
3658 // Version 160: Hiding notifications from the lockscreen is only available as
3659 // primary user option, profiles can only make them redacted. If a profile was
3660 // configured to not show lockscreen notifications, ensure that at the very
3661 // least these will be come hidden.
3662 if (mUserManager.isManagedProfile(userId)) {
3663 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3664 Setting showNotifications = secureSettings.getSettingLocked(
3665 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3666 // The default value is "1", check if user has turned it off.
3667 if ("0".equals(showNotifications.getValue())) {
3668 secureSettings.insertSettingLocked(
3669 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3670 null /* tag */, false /* makeDefault */,
3671 SettingsState.SYSTEM_PACKAGE_NAME);
3672 }
3673 // The setting is no longer valid for managed profiles, it should be
3674 // treated as if it was set to "1".
3675 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3676 }
3677 currentVersion = 160;
3678 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003679
3680 if (currentVersion == 160) {
3681 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003682 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003683 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3684 final SettingsState globalSettings = getGlobalSettingsLocked();
3685
3686 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003687 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3688 if (TextUtils.equals(null, oldValue)) {
3689 globalSettings.insertSettingLocked(
3690 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3691 Integer.toString(getContext().getResources().getInteger(
3692 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3693 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3694 }
3695
3696 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003697 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3698 if (TextUtils.equals(null, oldValue)) {
3699 globalSettings.insertSettingLocked(
3700 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3701 Integer.toString(getContext().getResources().getInteger(
3702 R.integer.def_sound_trigger_detection_service_op_timeout)),
3703 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3704 }
3705 currentVersion = 161;
3706 }
3707
Mike Digman55272862018-02-20 14:35:17 -08003708 if (currentVersion == 161) {
3709 // Version 161: Add a gesture for silencing phones
3710 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3711 final Setting currentSetting = secureSettings.getSettingLocked(
3712 Secure.VOLUME_HUSH_GESTURE);
3713 if (currentSetting.isNull()) {
3714 secureSettings.insertSettingLocked(
3715 Secure.VOLUME_HUSH_GESTURE,
3716 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3717 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3718 }
3719
3720 currentVersion = 162;
3721 }
3722
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003723 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003724 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003725 currentVersion = 163;
3726 }
3727
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003728 if (currentVersion == 163) {
3729 // Version 163: Update default value of
3730 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3731 final SettingsState settings = getGlobalSettingsLocked();
3732 final Setting currentSetting = settings.getSettingLocked(
3733 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3734 if (currentSetting.isDefaultFromSystem()) {
3735 settings.insertSettingLocked(
3736 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3737 Integer.toString(getContext().getResources().getInteger(
3738 R.integer
3739 .def_max_sound_trigger_detection_service_ops_per_day)),
3740 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3741 }
3742
3743 currentVersion = 164;
3744 }
3745
Julia Reynolds76bfa602018-04-23 09:38:47 -04003746 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003747 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003748 currentVersion = 165;
3749 }
3750
Beverly301e92a2018-04-27 09:43:05 -04003751 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003752 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3753 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003754 currentVersion = 166;
3755 }
3756
Beverly38fcfd02018-05-18 17:33:40 -04003757 if (currentVersion == 166) {
3758 // Version 166: add default values for hush gesture used and manual ringer
3759 // toggle
3760 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3761 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3762 Secure.HUSH_GESTURE_USED);
3763 if (currentHushUsedSetting.isNull()) {
3764 secureSettings.insertSettingLocked(
3765 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
3766 SettingsState.SYSTEM_PACKAGE_NAME);
3767 }
3768
3769 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
3770 Secure.MANUAL_RINGER_TOGGLE_COUNT);
3771 if (currentRingerToggleCountSetting.isNull()) {
3772 secureSettings.insertSettingLocked(
3773 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
3774 SettingsState.SYSTEM_PACKAGE_NAME);
3775 }
3776 currentVersion = 167;
3777 }
3778
Beverly155c9d22018-05-23 18:03:23 -04003779 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04003780 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
3781 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04003782 currentVersion = 168;
3783 }
3784
Michael Wright0e9eeee2018-05-26 00:31:20 +01003785 if (currentVersion == 168) {
3786 // Version 168: by default, vibrate for phone calls
3787 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3788 final Setting currentSetting = systemSettings.getSettingLocked(
3789 Settings.System.VIBRATE_WHEN_RINGING);
3790 if (currentSetting.isNull()) {
3791 systemSettings.insertSettingLocked(
3792 Settings.System.VIBRATE_WHEN_RINGING,
3793 getContext().getResources().getBoolean(
3794 R.bool.def_vibrate_when_ringing) ? "1" : "0",
3795 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3796 }
3797 currentVersion = 169;
3798 }
3799
Nadav Barf9f115d2018-06-24 10:06:50 +03003800 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04003801 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
3802 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
3803 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03003804
Beverly91d0a632018-07-02 16:45:00 -04003805 final SettingsState globalSettings = getGlobalSettingsLocked();
3806 final Setting globalZenDuration = globalSettings.getSettingLocked(
3807 Global.ZEN_DURATION);
3808
3809 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3810 final Setting secureZenDuration = secureSettings.getSettingLocked(
3811 Secure.ZEN_DURATION);
3812
3813 // ZEN_DURATION
3814 if (!globalZenDuration.isNull()) {
3815 secureSettings.insertSettingLocked(
3816 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
3817 SettingsState.SYSTEM_PACKAGE_NAME);
3818
3819 // set global zen duration setting to null since it's deprecated
3820 globalSettings.insertSettingLocked(
3821 Global.ZEN_DURATION, null, null, true,
3822 SettingsState.SYSTEM_PACKAGE_NAME);
3823 } else if (secureZenDuration.isNull()) {
3824 String defaultZenDuration = Integer.toString(getContext()
3825 .getResources().getInteger(R.integer.def_zen_duration));
3826 secureSettings.insertSettingLocked(
3827 Secure.ZEN_DURATION, defaultZenDuration, null, true,
3828 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03003829 }
Beverly91d0a632018-07-02 16:45:00 -04003830
3831 // SHOW_ZEN_SETTINGS_SUGGESTION
3832 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
3833 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
3834 if (currentShowZenSettingSuggestion.isNull()) {
3835 secureSettings.insertSettingLocked(
3836 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
3837 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3838 }
3839
3840 // ZEN_SETTINGS_UPDATED
3841 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
3842 Secure.ZEN_SETTINGS_UPDATED);
3843 if (currentUpdatedSetting.isNull()) {
3844 secureSettings.insertSettingLocked(
3845 Secure.ZEN_SETTINGS_UPDATED, "0",
3846 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3847 }
3848
3849 // ZEN_SETTINGS_SUGGESTION_VIEWED
3850 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
3851 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
3852 if (currentSettingSuggestionViewed.isNull()) {
3853 secureSettings.insertSettingLocked(
3854 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
3855 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3856 }
3857
Nadav Barf9f115d2018-06-24 10:06:50 +03003858 currentVersion = 170;
3859 }
3860
Beverly91d0a632018-07-02 16:45:00 -04003861 if (currentVersion == 170) {
3862 // Version 170: Set the default value for Secure Settings:
3863 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
3864
3865 final SettingsState globalSettings = getGlobalSettingsLocked();
3866 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3867
3868 // CHARGING_SOUNDS_ENABLED
3869 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
3870 Global.CHARGING_SOUNDS_ENABLED);
3871 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
3872 Secure.CHARGING_SOUNDS_ENABLED);
3873
3874 if (!globalChargingSoundEnabled.isNull()) {
3875 secureSettings.insertSettingLocked(
3876 Secure.CHARGING_SOUNDS_ENABLED,
3877 globalChargingSoundEnabled.getValue(), null, false,
3878 SettingsState.SYSTEM_PACKAGE_NAME);
3879
3880 // set global charging_sounds_enabled setting to null since it's deprecated
3881 globalSettings.insertSettingLocked(
3882 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
3883 SettingsState.SYSTEM_PACKAGE_NAME);
3884 } else if (secureChargingSoundsEnabled.isNull()) {
3885 String defChargingSoundsEnabled = getContext().getResources()
3886 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
3887 secureSettings.insertSettingLocked(
3888 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
3889 true, SettingsState.SYSTEM_PACKAGE_NAME);
3890 }
3891
3892 // CHARGING_VIBRATION_ENABLED
3893 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
3894 Secure.CHARGING_VIBRATION_ENABLED);
3895
3896 if (secureChargingVibrationEnabled.isNull()) {
3897 String defChargingVibrationEnabled = getContext().getResources()
3898 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
3899 secureSettings.insertSettingLocked(
3900 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
3901 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3902 }
3903
3904 currentVersion = 171;
3905 }
3906
Felipe Lemeff355092017-04-03 12:55:02 -07003907 // vXXX: Add new settings above this point.
3908
Dan Sandler71f85e92016-07-20 13:46:05 -04003909 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003910 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003911 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003912 + currentVersion +
3913 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3914 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003915 if (DEBUG) {
3916 throw new RuntimeException("db upgrade error");
3917 }
3918 }
3919
Jeff Brown503cffc2015-03-26 18:08:51 -07003920 // Return the current version.
3921 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003922 }
3923 }
Svet Ganov13701552017-02-23 12:45:17 -08003924
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003925 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3926 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003927 List<String> names = settings.getSettingNamesLocked();
3928 final int nameCount = names.size();
3929 for (int i = 0; i < nameCount; i++) {
3930 String name = names.get(i);
3931 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003932
3933 // In the upgrade case we pretend the call is made from the app
3934 // that made the last change to the setting to properly determine
3935 // whether the call has been made by a system component.
3936 int callingUid = -1;
3937 try {
3938 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3939 } catch (RemoteException e) {
3940 /* ignore - handled below */
3941 }
3942 if (callingUid < 0) {
3943 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3944 continue;
3945 }
3946 try {
3947 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3948 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003949 if (systemSet) {
3950 settings.insertSettingLocked(name, setting.getValue(),
3951 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003952 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3953 // We had a bug where changes by non-system packages were marked
3954 // as system made and as a result set as the default. Therefore, if
3955 // the package changed the setting last is not a system one but the
3956 // setting is marked as its default coming from the system we clear
3957 // the default and clear the system set flag.
3958 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003959 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003960 } catch (IllegalStateException e) {
3961 // If the package goes over its quota during the upgrade, don't
3962 // crash but just log the error as the system does the upgrade.
3963 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3964
Svet Ganov13701552017-02-23 12:45:17 -08003965 }
3966 }
3967 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003968 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003969}