blob: 290a4f83a40a764780f82ac0c8933d19c7c23e5e [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)
873 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700874 final long identity = Binder.clearCallingIdentity();
875 try {
876 synchronized (mLock) {
877 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800878 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700879 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800880 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700881 }
882 } finally {
883 Binder.restoreCallingIdentity(identity);
884 }
885 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800886 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
887 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700888 final long identity = Binder.clearCallingIdentity();
889 try {
890 synchronized (mLock) {
891 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800892 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700893 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800894 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700895 }
896 } finally {
897 Binder.restoreCallingIdentity(identity);
898 }
899 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800900 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
901 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700902 final long identity = Binder.clearCallingIdentity();
903 try {
904 synchronized (mLock) {
905 Setting enable = getGlobalSetting(
906 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800907 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700908 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800909 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700910 Setting include = getGlobalSetting(
911 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800912 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700913 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800914 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700915 }
916 } finally {
917 Binder.restoreCallingIdentity(identity);
918 }
919 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800920 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
921 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700922 final long identity = Binder.clearCallingIdentity();
923 try {
924 synchronized (mLock) {
925 Setting setting = getGlobalSetting(
926 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800927 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700928 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700930 }
931 } finally {
932 Binder.restoreCallingIdentity(identity);
933 }
934 }
935 });
936 }
937
Svetoslav7ec28e82015-05-20 17:01:10 -0700938 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800939 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700940 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800941 }
942
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 synchronized (mLock) {
944 // Get the settings.
945 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700946 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800947
Chad Brubaker97bccee2017-01-05 15:51:41 -0800948 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
949 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800950
Svetoslav7ec28e82015-05-20 17:01:10 -0700951 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800952
Svetoslav7ec28e82015-05-20 17:01:10 -0700953 String[] normalizedProjection = normalizeProjection(projection);
954 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800955
Svetoslav7ec28e82015-05-20 17:01:10 -0700956 // Anyone can get the global settings, so no security checks.
957 for (int i = 0; i < nameCount; i++) {
958 String name = names.get(i);
959 Setting setting = settingsState.getSettingLocked(name);
960 appendSettingToCursor(result, setting);
961 }
962
963 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800964 }
Svetoslav683914b2015-01-15 14:22:26 -0800965 }
966
Svetoslav7ec28e82015-05-20 17:01:10 -0700967 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800968 if (DEBUG) {
969 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
970 }
971
Chad Brubakera6830e72017-04-28 17:34:36 -0700972 // Ensure the caller can access the setting.
973 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
974
Svetoslav683914b2015-01-15 14:22:26 -0800975 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700976 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700977 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700978 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800979 }
Svetoslav683914b2015-01-15 14:22:26 -0800980 }
981
Svetoslav Ganove080da92016-12-21 17:10:35 -0800982 private boolean updateGlobalSetting(String name, String value, String tag,
983 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800984 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800985 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
986 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
987 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800988 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800989 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
990 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800991 }
992
Svetoslav Ganove080da92016-12-21 17:10:35 -0800993 private boolean insertGlobalSetting(String name, String value, String tag,
994 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700995 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800996 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
997 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
998 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700999 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1001 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001002 }
1003
Svet Ganov53a441c2016-04-19 19:38:00 -07001004 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001005 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001006 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1007 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001008 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001009 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1010 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001011 }
1012
Svetoslav Ganove080da92016-12-21 17:10:35 -08001013 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1014 if (DEBUG) {
1015 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1016 + mode + ", " + tag + ")");
1017 }
1018 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1019 MUTATION_OPERATION_RESET, false, mode);
1020 }
1021
1022 private boolean mutateGlobalSetting(String name, String value, String tag,
1023 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1024 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001025 // Make sure the caller can change the settings - treated as secure.
1026 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1027
Svetoslav683914b2015-01-15 14:22:26 -08001028 // Resolve the userId on whose behalf the call is made.
1029 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1030
Makoto Onuki28da2e32015-11-20 11:30:44 -08001031 // If this is a setting that is currently restricted for this user, do not allow
1032 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001033 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1034 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001035 return false;
1036 }
1037
1038 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 synchronized (mLock) {
1040 switch (operation) {
1041 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001042 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1043 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001044 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001045 }
Svetoslav683914b2015-01-15 14:22:26 -08001046
Svetoslav7ec28e82015-05-20 17:01:10 -07001047 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001048 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001049 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001050 }
Svetoslav683914b2015-01-15 14:22:26 -08001051
Svetoslav7ec28e82015-05-20 17:01:10 -07001052 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001053 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1054 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001055 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001056 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001057
1058 case MUTATION_OPERATION_RESET: {
1059 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1060 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1061 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001062 }
1063 }
1064
1065 return false;
1066 }
1067
Christopher Tateb218e762017-04-05 16:34:07 -07001068 private PackageInfo getCallingPackageInfo(int userId) {
1069 try {
1070 return mPackageManager.getPackageInfo(getCallingPackage(),
1071 PackageManager.GET_SIGNATURES, userId);
1072 } catch (RemoteException e) {
1073 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1074 }
1075 }
1076
Svetoslav7ec28e82015-05-20 17:01:10 -07001077 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001078 if (DEBUG) {
1079 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1080 }
1081
1082 // Resolve the userId on whose behalf the call is made.
1083 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1084
Christopher Tateb218e762017-04-05 16:34:07 -07001085 // The relevant "calling package" userId will be the owning userId for some
1086 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1087 // up front who the effective "new SSAID" user ID for that settings name will be.
1088 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1089 Settings.Secure.ANDROID_ID);
1090 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1091
Svetoslav7ec28e82015-05-20 17:01:10 -07001092 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001093 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001094
Svetoslav7ec28e82015-05-20 17:01:10 -07001095 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001096
Svetoslav7ec28e82015-05-20 17:01:10 -07001097 String[] normalizedProjection = normalizeProjection(projection);
1098 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001099
Svetoslav7ec28e82015-05-20 17:01:10 -07001100 for (int i = 0; i < nameCount; i++) {
1101 String name = names.get(i);
1102 // Determine the owning user as some profile settings are cloned from the parent.
1103 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1104 name);
Svetoslav683914b2015-01-15 14:22:26 -08001105
Alex Klyubin1991f572017-03-03 14:08:36 -08001106 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1107 // This caller is not permitted to access this setting. Pretend the setting
1108 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001109 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001110 }
Svetoslav683914b2015-01-15 14:22:26 -08001111
Mark Rathjen7599f132017-01-23 14:15:54 -08001112 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001113 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1114 final Setting setting;
1115 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001116 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001117 } else {
1118 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1119 name);
1120 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001121 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001122 }
1123
Svetoslav7ec28e82015-05-20 17:01:10 -07001124 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001125 }
Svetoslav683914b2015-01-15 14:22:26 -08001126 }
1127
Svetoslav7ec28e82015-05-20 17:01:10 -07001128 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001129 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1130 }
1131
1132 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001133 if (DEBUG) {
1134 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1135 }
1136
1137 // Resolve the userId on whose behalf the call is made.
1138 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1139
Chad Brubakera6830e72017-04-28 17:34:36 -07001140 // Ensure the caller can access the setting.
1141 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1142
Svetoslav683914b2015-01-15 14:22:26 -08001143 // Determine the owning user as some profile settings are cloned from the parent.
1144 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1145
Alex Klyubin1991f572017-03-03 14:08:36 -08001146 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1147 // This caller is not permitted to access this setting. Pretend the setting doesn't
1148 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001149 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1150 owningUserId);
1151 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001152 }
1153
Christopher Tateb218e762017-04-05 16:34:07 -07001154 // As of Android O, the SSAID is read from an app-specific entry in table
1155 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1156 if (isNewSsaidSetting(name)) {
1157 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1158 synchronized (mLock) {
1159 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001160 }
Christopher Tateb218e762017-04-05 16:34:07 -07001161 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001162 if (enableOverride) {
1163 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1164 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1165 if (overridden != null) {
1166 return overridden;
1167 }
1168 }
1169 }
Mark Rathjend891f012017-01-19 04:10:37 +00001170
Christopher Tateb218e762017-04-05 16:34:07 -07001171 // Not the SSAID; do a straight lookup
1172 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001173 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001174 owningUserId, name);
1175 }
Svetoslav683914b2015-01-15 14:22:26 -08001176 }
1177
Mark Rathjend891f012017-01-19 04:10:37 +00001178 private boolean isNewSsaidSetting(String name) {
1179 return Settings.Secure.ANDROID_ID.equals(name)
1180 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1181 }
1182
Andreas Gampeb58893072018-09-05 16:52:31 -07001183 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001184 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001185 // Get uid of caller (key) used to store ssaid value
1186 String name = Integer.toString(
1187 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1188
1189 if (DEBUG) {
1190 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1191 }
1192
1193 // Retrieve the ssaid from the table if present.
1194 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1195 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001196 // If the app is an Instant App use its stored SSAID instead of our own.
1197 final String instantSsaid;
1198 final long token = Binder.clearCallingIdentity();
1199 try {
1200 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1201 owningUserId);
1202 } catch (RemoteException e) {
1203 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1204 return null;
1205 } finally {
1206 Binder.restoreCallingIdentity(token);
1207 }
Svet Ganov96c99462017-05-05 14:27:13 -07001208
1209 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1210 SETTINGS_TYPE_SSAID, owningUserId);
1211
Chad Brubaker0d277a72017-04-12 16:56:53 -07001212 if (instantSsaid != null) {
1213 // Use the stored value if it is still valid.
1214 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001215 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001216 }
1217 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001218 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1219 true, callingPkg.packageName);
1220 if (!success) {
1221 throw new IllegalStateException("Failed to update instant app android id");
1222 }
Svet Ganov96c99462017-05-05 14:27:13 -07001223 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1224 owningUserId, name);
1225 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001226 }
Mark Rathjend891f012017-01-19 04:10:37 +00001227
1228 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001229 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001230 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1231 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001232 }
1233
Svet Ganov96c99462017-05-05 14:27:13 -07001234 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1235 }
1236
1237 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1238 // SSAID settings are located in a dedicated table for internal bookkeeping
1239 // but for the world they reside in the secure table, so adjust the key here.
1240 // We have a special name when looking it up but want the world to see it as
1241 // "android_id".
1242 if (ssaidSetting != null) {
1243 return settingsState.new Setting(ssaidSetting) {
1244 @Override
1245 public int getKey() {
1246 final int userId = getUserIdFromKey(super.getKey());
1247 return makeKey(SETTINGS_TYPE_SECURE, userId);
1248 }
1249
1250 @Override
1251 public String getName() {
1252 return Settings.Secure.ANDROID_ID;
1253 }
1254 };
1255 }
1256 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001257 }
1258
Makoto Onuki0000d322017-11-28 16:31:47 -08001259 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1260 synchronized (mLock) {
1261 final Setting setting = getGlobalSetting(
1262 Global.LOCATION_GLOBAL_KILL_SWITCH);
1263 if (!"1".equals(setting.getValue())) {
1264 return null;
1265 }
1266 // Global kill-switch is enabled. Return an empty value.
1267 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1268 SETTINGS_TYPE_SECURE, owningUserId);
1269 return settingsState.new Setting(
1270 Secure.LOCATION_PROVIDERS_ALLOWED,
1271 "", // value
1272 "", // tag
1273 "", // default value
1274 "", // package name
1275 false, // from system
1276 "0" // id
1277 ) {
1278 @Override
1279 public boolean update(String value, boolean setDefault, String packageName,
1280 String tag, boolean forceNonSystemPackage) {
1281 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1282 return false;
1283 }
1284 };
1285 }
1286 }
1287
Svetoslav Ganove080da92016-12-21 17:10:35 -08001288 private boolean insertSecureSetting(String name, String value, String tag,
1289 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001290 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001291 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001292 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1293 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001294 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001295 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1296 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001297 }
1298
Svet Ganov53a441c2016-04-19 19:38:00 -07001299 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001300 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001301 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1302 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001303 }
1304
Svetoslav Ganove080da92016-12-21 17:10:35 -08001305 return mutateSecureSetting(name, null, null, false, requestingUserId,
1306 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001307 }
1308
Svetoslav Ganove080da92016-12-21 17:10:35 -08001309 private boolean updateSecureSetting(String name, String value, String tag,
1310 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001311 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001312 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001313 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1314 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001315 }
1316
Svetoslav Ganove080da92016-12-21 17:10:35 -08001317 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1318 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001319 }
1320
Svetoslav Ganove080da92016-12-21 17:10:35 -08001321 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1322 if (DEBUG) {
1323 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1324 + mode + ", " + tag + ")");
1325 }
1326
1327 mutateSecureSetting(null, null, tag, false, requestingUserId,
1328 MUTATION_OPERATION_RESET, false, mode);
1329 }
1330
1331 private boolean mutateSecureSetting(String name, String value, String tag,
1332 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1333 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001334 // Make sure the caller can change the settings.
1335 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1336
Svetoslav683914b2015-01-15 14:22:26 -08001337 // Resolve the userId on whose behalf the call is made.
1338 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1339
Makoto Onuki28da2e32015-11-20 11:30:44 -08001340 // If this is a setting that is currently restricted for this user, do not allow
1341 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001342 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1343 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001344 return false;
1345 }
1346
1347 // Determine the owning user as some profile settings are cloned from the parent.
1348 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1349
1350 // Only the owning user can change the setting.
1351 if (owningUserId != callingUserId) {
1352 return false;
1353 }
1354
1355 // Special cases for location providers (sigh).
1356 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001357 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1358 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001359 }
1360
1361 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001362 synchronized (mLock) {
1363 switch (operation) {
1364 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001365 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001366 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001367 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001368 }
Svetoslav683914b2015-01-15 14:22:26 -08001369
Svetoslav7ec28e82015-05-20 17:01:10 -07001370 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001371 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001372 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001373 }
Svetoslav683914b2015-01-15 14:22:26 -08001374
Svetoslav7ec28e82015-05-20 17:01:10 -07001375 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001376 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001377 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001378 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001379 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001380
1381 case MUTATION_OPERATION_RESET: {
1382 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1383 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1384 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001385 }
1386 }
1387
1388 return false;
1389 }
1390
Svetoslav7ec28e82015-05-20 17:01:10 -07001391 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001392 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001393 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001394 }
1395
1396 // Resolve the userId on whose behalf the call is made.
1397 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1398
Svetoslav7ec28e82015-05-20 17:01:10 -07001399 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001400 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001401
Svetoslav7ec28e82015-05-20 17:01:10 -07001402 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001403
Svetoslav7ec28e82015-05-20 17:01:10 -07001404 String[] normalizedProjection = normalizeProjection(projection);
1405 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001406
Svetoslav7ec28e82015-05-20 17:01:10 -07001407 for (int i = 0; i < nameCount; i++) {
1408 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001409
Svetoslav7ec28e82015-05-20 17:01:10 -07001410 // Determine the owning user as some profile settings are cloned from the parent.
1411 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1412 name);
Svetoslav683914b2015-01-15 14:22:26 -08001413
Svetoslav7ec28e82015-05-20 17:01:10 -07001414 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001415 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001416 appendSettingToCursor(result, setting);
1417 }
1418
1419 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001420 }
Svetoslav683914b2015-01-15 14:22:26 -08001421 }
1422
Svetoslav7ec28e82015-05-20 17:01:10 -07001423 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001424 if (DEBUG) {
1425 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1426 }
1427
1428 // Resolve the userId on whose behalf the call is made.
1429 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1430
Chad Brubakera6830e72017-04-28 17:34:36 -07001431 // Ensure the caller can access the setting.
1432 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001433
Svetoslav683914b2015-01-15 14:22:26 -08001434 // Determine the owning user as some profile settings are cloned from the parent.
1435 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1436
1437 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001438 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001439 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001440 }
Svetoslav683914b2015-01-15 14:22:26 -08001441 }
1442
Svetoslav7ec28e82015-05-20 17:01:10 -07001443 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001444 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001445 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001446 + requestingUserId + ")");
1447 }
1448
Svetoslav7ec28e82015-05-20 17:01:10 -07001449 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001450 }
1451
Svetoslav7ec28e82015-05-20 17:01:10 -07001452 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001453 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001454 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001455 }
1456
Svetoslav7ec28e82015-05-20 17:01:10 -07001457 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001458 }
1459
Svetoslav7ec28e82015-05-20 17:01:10 -07001460 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001461 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001462 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001463 + requestingUserId + ")");
1464 }
1465
Svetoslav7ec28e82015-05-20 17:01:10 -07001466 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001467 }
1468
Svetoslav7ec28e82015-05-20 17:01:10 -07001469 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001470 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001471 if (!hasWriteSecureSettingsPermission()) {
1472 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1473 // operation is allowed for the calling package through appops.
1474 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1475 Binder.getCallingUid(), getCallingPackage(), true)) {
1476 return false;
1477 }
Svetoslav683914b2015-01-15 14:22:26 -08001478 }
1479
Svetoslav683914b2015-01-15 14:22:26 -08001480 // Resolve the userId on whose behalf the call is made.
1481 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1482
yuemingw1d13eae2018-01-30 17:27:54 +00001483 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1484 name, callingUserId, value, Binder.getCallingUid())) {
1485 return false;
1486 }
1487
Svetoslavd8d25e02015-11-20 13:09:26 -08001488 // Enforce what the calling package can mutate the system settings.
1489 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1490
Svetoslav683914b2015-01-15 14:22:26 -08001491 // Determine the owning user as some profile settings are cloned from the parent.
1492 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1493
1494 // Only the owning user id can change the setting.
1495 if (owningUserId != callingUserId) {
1496 return false;
1497 }
1498
Jeff Sharkey413573a2016-02-22 17:52:45 -07001499 // Invalidate any relevant cache files
1500 String cacheName = null;
1501 if (Settings.System.RINGTONE.equals(name)) {
1502 cacheName = Settings.System.RINGTONE_CACHE;
1503 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1504 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1505 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1506 cacheName = Settings.System.ALARM_ALERT_CACHE;
1507 }
1508 if (cacheName != null) {
1509 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001510 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001511 cacheFile.delete();
1512 }
1513
Svetoslav683914b2015-01-15 14:22:26 -08001514 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001515 synchronized (mLock) {
1516 switch (operation) {
1517 case MUTATION_OPERATION_INSERT: {
1518 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001519 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001520 owningUserId, name, value, null, false, getCallingPackage(),
1521 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001522 }
1523
1524 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001525 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001526 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001527 }
1528
1529 case MUTATION_OPERATION_UPDATE: {
1530 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001531 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001532 owningUserId, name, value, null, false, getCallingPackage(),
1533 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001534 }
Svetoslav683914b2015-01-15 14:22:26 -08001535 }
1536
Svetoslav7ec28e82015-05-20 17:01:10 -07001537 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001538 }
Svetoslav683914b2015-01-15 14:22:26 -08001539 }
1540
Billy Lau6ad2d662015-07-18 00:26:58 +01001541 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001542 // Write secure settings is a more protected permission. If caller has it we are good.
1543 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1544 == PackageManager.PERMISSION_GRANTED) {
1545 return true;
1546 }
1547
Svetoslavf41334b2015-06-23 12:06:03 -07001548 return false;
1549 }
1550
Svetoslav683914b2015-01-15 14:22:26 -08001551 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001552 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001553 if (validator != null && !validator.validate(value)) {
1554 throw new IllegalArgumentException("Invalid value: " + value
1555 + " for setting: " + name);
1556 }
1557 }
1558
Alex Klyubin1991f572017-03-03 14:08:36 -08001559 /**
1560 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1561 */
1562 private boolean isSecureSettingAccessible(String name, int callingUserId,
1563 int owningUserId) {
1564 // Special case for location (sigh).
1565 // This check is not inside the name-based checks below because this method performs checks
1566 // only if the calling user ID is not the same as the owning user ID.
1567 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1568 return false;
1569 }
1570
1571 switch (name) {
1572 case "bluetooth_address":
1573 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1574 // address in this secure setting. Secure settings can normally be read by any app,
1575 // which thus enables them to bypass the recently introduced restrictions on access
1576 // to device identifiers.
1577 // To mitigate this we make this setting available only to callers privileged to see
1578 // this device's MAC addresses, same as through public API
1579 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1580 return getContext().checkCallingOrSelfPermission(
1581 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1582 default:
1583 return true;
1584 }
1585 }
1586
Svetoslav683914b2015-01-15 14:22:26 -08001587 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1588 int owningUserId) {
1589 // Optimization - location providers are restricted only for managed profiles.
1590 if (callingUserId == owningUserId) {
1591 return false;
1592 }
1593 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1594 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1595 new UserHandle(callingUserId))) {
1596 return true;
1597 }
1598 return false;
1599 }
1600
Svetoslav683914b2015-01-15 14:22:26 -08001601 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1602 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1603 }
1604
1605 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001606 final int parentId;
1607 // Resolves dependency if setting has a dependency and the calling user has a parent
1608 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1609 && (parentId = getGroupParentLocked(userId)) != userId) {
1610 // The setting has a dependency and the profile has a parent
1611 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001612 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1613 final long token = Binder.clearCallingIdentity();
1614 try {
1615 Setting settingObj = getSecureSetting(dependency, userId);
1616 if (settingObj != null && settingObj.getValue().equals("1")) {
1617 return parentId;
1618 }
1619 } finally {
1620 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001621 }
1622 }
Svetoslav683914b2015-01-15 14:22:26 -08001623 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1624 }
1625
1626 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1627 final int parentId = getGroupParentLocked(userId);
1628 if (parentId != userId && keys.contains(name)) {
1629 return parentId;
1630 }
1631 return userId;
1632 }
1633
Svetoslavf41334b2015-06-23 12:06:03 -07001634 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001635 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001636 // System/root/shell can mutate whatever secure settings they want.
1637 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001638 final int appId = UserHandle.getAppId(callingUid);
1639 if (appId == android.os.Process.SYSTEM_UID
1640 || appId == Process.SHELL_UID
1641 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001642 return;
1643 }
1644
1645 switch (operation) {
1646 case MUTATION_OPERATION_INSERT:
1647 // Insert updates.
1648 case MUTATION_OPERATION_UPDATE: {
1649 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1650 return;
1651 }
1652
1653 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001654 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001655
1656 // Privileged apps can do whatever they want.
1657 if ((packageInfo.applicationInfo.privateFlags
1658 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1659 return;
1660 }
1661
1662 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1663 packageInfo.applicationInfo.targetSdkVersion, name);
1664 } break;
1665
1666 case MUTATION_OPERATION_DELETE: {
1667 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1668 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1669 throw new IllegalArgumentException("You cannot delete system defined"
1670 + " secure settings.");
1671 }
1672
1673 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001674 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001675
1676 // Privileged apps can do whatever they want.
1677 if ((packageInfo.applicationInfo.privateFlags &
1678 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1679 return;
1680 }
1681
1682 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1683 packageInfo.applicationInfo.targetSdkVersion, name);
1684 } break;
1685 }
1686 }
1687
Todd Kennedybe0b8892017-02-15 14:13:52 -08001688 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001689 switch (settingsType) {
1690 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001691 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001692 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001693 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001694 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001695 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001696 default:
1697 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1698 }
1699 }
1700
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001701 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1702 switch (settingsType) {
1703 case SETTINGS_TYPE_GLOBAL:
1704 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1705 case SETTINGS_TYPE_SYSTEM:
1706 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1707 case SETTINGS_TYPE_SECURE:
1708 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1709 default:
1710 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1711 }
1712 }
1713
Andreas Gampeb58893072018-09-05 16:52:31 -07001714 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001715 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001716 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1717 // in the current form.
1718 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001719 }
1720
Chad Brubakera6830e72017-04-28 17:34:36 -07001721 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001722 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1723 return;
1724 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001725 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001726 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001727 return;
1728 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001729 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1730 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001731 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1732 // breakage in the current form.
1733 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1734 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001735 }
1736 }
1737
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001738 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1739 // We always use the callingUid for this lookup. This means that if hypothetically an
1740 // app was installed in user A with cross user and in user B as an Instant App
1741 // the app in A would be able to see all the settings in user B. However since cross
1742 // user is a system permission and the app must be uninstalled in B and then installed as
1743 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001744 ApplicationInfo ai = null;
1745 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001746 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1747 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001748 } catch (RemoteException ignored) {
1749 }
1750 if (ai == null) {
1751 throw new IllegalStateException("Failed to lookup info for package "
1752 + getCallingPackage());
1753 }
1754 return ai;
1755 }
1756
Xiaohui Chen43765b72015-08-31 10:57:33 -07001757 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001758 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001759 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1760 getCallingPackage(), 0, userId);
1761 if (packageInfo != null) {
1762 return packageInfo;
1763 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001764 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001765 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001766 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001767 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001768 }
1769
1770 private int getGroupParentLocked(int userId) {
1771 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001772 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001773 return userId;
1774 }
1775 // We are in the same process with the user manager and the returned
1776 // user info is a cached instance, so just look up instead of cache.
1777 final long identity = Binder.clearCallingIdentity();
1778 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001779 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001780 UserInfo userInfo = mUserManager.getProfileParent(userId);
1781 return (userInfo != null) ? userInfo.id : userId;
1782 } finally {
1783 Binder.restoreCallingIdentity(identity);
1784 }
1785 }
1786
Svetoslav683914b2015-01-15 14:22:26 -08001787 private void enforceWritePermission(String permission) {
1788 if (getContext().checkCallingOrSelfPermission(permission)
1789 != PackageManager.PERMISSION_GRANTED) {
1790 throw new SecurityException("Permission denial: writing to settings requires:"
1791 + permission);
1792 }
1793 }
1794
1795 /*
1796 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1797 * This setting contains a list of the currently enabled location providers.
1798 * But helper functions in android.providers.Settings can enable or disable
1799 * a single provider by using a "+" or "-" prefix before the provider name.
1800 *
yuemingw1d13eae2018-01-30 17:27:54 +00001801 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1802 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1803 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001804 *
Svetoslav683914b2015-01-15 14:22:26 -08001805 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001806 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001807 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001808 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1809 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001810 if (TextUtils.isEmpty(value)) {
1811 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001812 }
Maggie83e03f52018-03-16 12:22:20 -07001813 Setting oldSetting = getSecureSetting(
1814 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1815 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001816 return false;
1817 }
Maggie83e03f52018-03-16 12:22:20 -07001818 String oldProviders = oldSetting.getValue();
1819 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1820 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1821 Set<String> newProvidersSet = new ArraySet<>();
1822 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08001823
Maggie83e03f52018-03-16 12:22:20 -07001824 String[] providerUpdates = value.split(",");
1825 boolean inputError = false;
1826 for (String provider : providerUpdates) {
1827 // do not update location_providers_allowed when input is invalid
1828 if (TextUtils.isEmpty(provider)) {
1829 inputError = true;
1830 break;
Svetoslav683914b2015-01-15 14:22:26 -08001831 }
Maggie83e03f52018-03-16 12:22:20 -07001832 final char prefix = provider.charAt(0);
1833 // do not update location_providers_allowed when input is invalid
1834 if (prefix != '+' && prefix != '-') {
1835 inputError = true;
1836 break;
Svetoslav683914b2015-01-15 14:22:26 -08001837 }
Maggie83e03f52018-03-16 12:22:20 -07001838 // skip prefix
1839 provider = provider.substring(1);
1840 if (prefix == '+') {
1841 newProvidersSet.add(provider);
1842 } else if (prefix == '-') {
1843 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08001844 }
Maggie83e03f52018-03-16 12:22:20 -07001845 }
1846 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
1847 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08001848 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001849 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07001850 mSettingsRegistry.notifyForSettingsChange(
1851 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07001852 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1853 }
Svetoslav683914b2015-01-15 14:22:26 -08001854 return false;
1855 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001856 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07001857 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
1858 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001859 }
1860
Svetoslav683914b2015-01-15 14:22:26 -08001861 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1862 int targetSdkVersion, String name) {
1863 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1864 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1865 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1866 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1867 + " This will soon become an error.");
1868 } else {
1869 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1870 + " This will soon become an error.");
1871 }
1872 } else {
1873 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1874 throw new IllegalArgumentException("You cannot change private secure settings.");
1875 } else {
1876 throw new IllegalArgumentException("You cannot keep your settings in"
1877 + " the secure settings.");
1878 }
1879 }
1880 }
1881
1882 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1883 if (requestingUserId == UserHandle.getCallingUserId()) {
1884 return requestingUserId;
1885 }
1886 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1887 Binder.getCallingUid(), requestingUserId, false, true,
1888 "get/set setting for user", null);
1889 }
1890
Svet Ganov53a441c2016-04-19 19:38:00 -07001891 private Bundle packageValueForCallResult(Setting setting,
1892 boolean trackingGeneration) {
1893 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001894 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001895 return NULL_SETTING_BUNDLE;
1896 }
1897 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001898 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001899 Bundle result = new Bundle();
1900 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001901 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001902
Svetoslav Ganove080da92016-12-21 17:10:35 -08001903 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001904 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001905 }
1906
1907 private static int getRequestingUserId(Bundle args) {
1908 final int callingUserId = UserHandle.getCallingUserId();
1909 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1910 : callingUserId;
1911 }
1912
Svet Ganov53a441c2016-04-19 19:38:00 -07001913 private boolean isTrackingGeneration(Bundle args) {
1914 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1915 }
1916
Svetoslav683914b2015-01-15 14:22:26 -08001917 private static String getSettingValue(Bundle args) {
1918 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1919 }
1920
Svetoslav Ganove080da92016-12-21 17:10:35 -08001921 private static String getSettingTag(Bundle args) {
1922 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1923 }
1924
1925 private static boolean getSettingMakeDefault(Bundle args) {
1926 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1927 }
1928
1929 private static int getResetModeEnforcingPermission(Bundle args) {
1930 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1931 switch (mode) {
1932 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1933 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1934 throw new SecurityException("Only system, shell/root on a "
1935 + "debuggable build can reset to untrusted defaults");
1936 }
1937 return mode;
1938 }
1939 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1940 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1941 throw new SecurityException("Only system, shell/root on a "
1942 + "debuggable build can reset untrusted changes");
1943 }
1944 return mode;
1945 }
1946 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1947 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1948 throw new SecurityException("Only system, shell/root on a "
1949 + "debuggable build can reset to trusted defaults");
1950 }
1951 return mode;
1952 }
1953 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1954 return mode;
1955 }
1956 }
1957 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1958 }
1959
1960 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1961 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1962 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1963 && (appId == SHELL_UID || appId == ROOT_UID));
1964 }
1965
Svetoslav683914b2015-01-15 14:22:26 -08001966 private static String getValidTableOrThrow(Uri uri) {
1967 if (uri.getPathSegments().size() > 0) {
1968 String table = uri.getPathSegments().get(0);
1969 if (DatabaseHelper.isValidTable(table)) {
1970 return table;
1971 }
1972 throw new IllegalArgumentException("Bad root path: " + table);
1973 }
1974 throw new IllegalArgumentException("Invalid URI:" + uri);
1975 }
1976
1977 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001978 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001979 return new MatrixCursor(projection, 0);
1980 }
1981 MatrixCursor cursor = new MatrixCursor(projection, 1);
1982 appendSettingToCursor(cursor, setting);
1983 return cursor;
1984 }
1985
1986 private static String[] normalizeProjection(String[] projection) {
1987 if (projection == null) {
1988 return ALL_COLUMNS;
1989 }
1990
1991 final int columnCount = projection.length;
1992 for (int i = 0; i < columnCount; i++) {
1993 String column = projection[i];
1994 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1995 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001996 }
1997 }
1998
Svetoslav683914b2015-01-15 14:22:26 -08001999 return projection;
2000 }
2001
2002 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002003 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002004 return;
2005 }
Svetoslav683914b2015-01-15 14:22:26 -08002006 final int columnCount = cursor.getColumnCount();
2007
2008 String[] values = new String[columnCount];
2009
2010 for (int i = 0; i < columnCount; i++) {
2011 String column = cursor.getColumnName(i);
2012
2013 switch (column) {
2014 case Settings.NameValueTable._ID: {
2015 values[i] = setting.getId();
2016 } break;
2017
2018 case Settings.NameValueTable.NAME: {
2019 values[i] = setting.getName();
2020 } break;
2021
2022 case Settings.NameValueTable.VALUE: {
2023 values[i] = setting.getValue();
2024 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002025 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002026 }
2027
Svetoslav683914b2015-01-15 14:22:26 -08002028 cursor.addRow(values);
2029 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002030
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002031 private static boolean isKeyValid(String key) {
2032 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2033 }
2034
Svetoslav683914b2015-01-15 14:22:26 -08002035 private static final class Arguments {
2036 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2037 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2038
2039 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2040 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2041
2042 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2043 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2044
2045 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2046 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2047
2048 public final String table;
2049 public final String name;
2050
2051 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2052 final int segmentSize = uri.getPathSegments().size();
2053 switch (segmentSize) {
2054 case 1: {
2055 if (where != null
2056 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2057 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2058 && whereArgs.length == 1) {
2059 name = whereArgs[0];
2060 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002061 return;
Svetoslav683914b2015-01-15 14:22:26 -08002062 } else if (where != null
2063 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2064 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2065 final int startIndex = Math.max(where.indexOf("'"),
2066 where.indexOf("\"")) + 1;
2067 final int endIndex = Math.max(where.lastIndexOf("'"),
2068 where.lastIndexOf("\""));
2069 name = where.substring(startIndex, endIndex);
2070 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002071 return;
Svetoslav683914b2015-01-15 14:22:26 -08002072 } else if (supportAll && where == null && whereArgs == null) {
2073 name = null;
2074 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002075 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002076 }
Svetoslav683914b2015-01-15 14:22:26 -08002077 } break;
2078
Svetoslav28494652015-02-12 14:11:42 -08002079 case 2: {
2080 if (where == null && whereArgs == null) {
2081 name = uri.getPathSegments().get(1);
2082 table = computeTableForSetting(uri, name);
2083 return;
2084 }
2085 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002086 }
Svetoslav28494652015-02-12 14:11:42 -08002087
2088 EventLogTags.writeUnsupportedSettingsQuery(
2089 uri.toSafeString(), where, Arrays.toString(whereArgs));
2090 String message = String.format( "Supported SQL:\n"
2091 + " uri content://some_table/some_property with null where and where args\n"
2092 + " uri content://some_table with query name=? and single name as arg\n"
2093 + " uri content://some_table with query name=some_name and null args\n"
2094 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2095 Arrays.toString(whereArgs));
2096 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002097 }
2098
Svetoslav28494652015-02-12 14:11:42 -08002099 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002100 String table = getValidTableOrThrow(uri);
2101
2102 if (name != null) {
2103 if (sSystemMovedToSecureSettings.contains(name)) {
2104 table = TABLE_SECURE;
2105 }
2106
2107 if (sSystemMovedToGlobalSettings.contains(name)) {
2108 table = TABLE_GLOBAL;
2109 }
2110
2111 if (sSecureMovedToGlobalSettings.contains(name)) {
2112 table = TABLE_GLOBAL;
2113 }
2114
2115 if (sGlobalMovedToSecureSettings.contains(name)) {
2116 table = TABLE_SECURE;
2117 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002118 }
Svetoslav683914b2015-01-15 14:22:26 -08002119
2120 return table;
2121 }
2122 }
2123
2124 final class SettingsRegistry {
2125 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2126
Svetoslav683914b2015-01-15 14:22:26 -08002127 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2128 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2129 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002130 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2131
2132 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002133
2134 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2135
Svet Ganov53a441c2016-04-19 19:38:00 -07002136 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002137
Svetoslav7e0683b2015-08-03 16:02:52 -07002138 private final Handler mHandler;
2139
Svet Ganov53a441c2016-04-19 19:38:00 -07002140 private final BackupManager mBackupManager;
2141
Amith Yamasani39452022017-03-21 15:23:47 -07002142 private String mSettingsCreationBuildId;
2143
Svetoslav683914b2015-01-15 14:22:26 -08002144 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002145 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002146 mGenerationRegistry = new GenerationRegistry(mLock);
2147 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002148 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002149 syncSsaidTableOnStart();
2150 }
2151
2152 private void generateUserKeyLocked(int userId) {
2153 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002154 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002155 final SecureRandom rand = new SecureRandom();
2156 rand.nextBytes(keyBytes);
2157
2158 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002159 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002160
2161 // Store the key in the ssaid table.
2162 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2163 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2164 true, SettingsState.SYSTEM_PACKAGE_NAME);
2165
2166 if (!success) {
2167 throw new IllegalStateException("Ssaid settings not accessible");
2168 }
2169 }
2170
Mark Rathjen7599f132017-01-23 14:15:54 -08002171 private byte[] getLengthPrefix(byte[] data) {
2172 return ByteBuffer.allocate(4).putInt(data.length).array();
2173 }
2174
Christopher Tateb218e762017-04-05 16:34:07 -07002175 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002176 // Read the user's key from the ssaid table.
2177 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002178 if (userKeySetting == null || userKeySetting.isNull()
2179 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002180 // Lazy initialize and store the user key.
2181 generateUserKeyLocked(userId);
2182 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002183 if (userKeySetting == null || userKeySetting.isNull()
2184 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002185 throw new IllegalStateException("User key not accessible");
2186 }
2187 }
2188 final String userKey = userKeySetting.getValue();
2189
2190 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002191 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2192
2193 // Validate that the key is of expected length.
2194 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2195 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002196 throw new IllegalStateException("User key invalid");
2197 }
2198
Mark Rathjen7599f132017-01-23 14:15:54 -08002199 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002200 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002201 m = Mac.getInstance("HmacSHA256");
2202 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002203 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002204 throw new IllegalStateException("HmacSHA256 is not available", e);
2205 } catch (InvalidKeyException e) {
2206 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002207 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002208
Mark Rathjenf42dd912017-06-05 19:04:34 -07002209 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002210 for (int i = 0; i < callingPkg.signatures.length; i++) {
2211 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002212 m.update(getLengthPrefix(sig), 0, 4);
2213 m.update(sig);
2214 }
Mark Rathjend891f012017-01-19 04:10:37 +00002215
2216 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002217 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2218 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002219
2220 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002221 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002222 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2223 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002224 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002225
2226 if (!success) {
2227 throw new IllegalStateException("Ssaid settings not accessible");
2228 }
2229
2230 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2231 }
2232
2233 public void syncSsaidTableOnStart() {
2234 synchronized (mLock) {
2235 // Verify that each user's packages and ssaid's are in sync.
2236 for (UserInfo user : mUserManager.getUsers(true)) {
2237 // Get all uids for the user's packages.
2238 final List<PackageInfo> packages;
2239 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002240 packages = mPackageManager.getInstalledPackages(
2241 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2242 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002243 } catch (RemoteException e) {
2244 throw new IllegalStateException("Package manager not available");
2245 }
2246 final Set<String> appUids = new HashSet<>();
2247 for (PackageInfo info : packages) {
2248 appUids.add(Integer.toString(info.applicationInfo.uid));
2249 }
2250
2251 // Get all uids currently stored in the user's ssaid table.
2252 final Set<String> ssaidUids = new HashSet<>(
2253 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2254 ssaidUids.remove(SSAID_USER_KEY);
2255
2256 // Perform a set difference for the appUids and ssaidUids.
2257 ssaidUids.removeAll(appUids);
2258
2259 // If there are ssaidUids left over they need to be removed from the table.
2260 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2261 user.id);
2262 for (String uid : ssaidUids) {
2263 ssaidSettings.deleteSettingLocked(uid);
2264 }
2265 }
2266 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002267 }
2268
Svetoslav683914b2015-01-15 14:22:26 -08002269 public List<String> getSettingsNamesLocked(int type, int userId) {
2270 final int key = makeKey(type, userId);
2271 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002272 if (settingsState == null) {
2273 return new ArrayList<String>();
2274 }
Svetoslav683914b2015-01-15 14:22:26 -08002275 return settingsState.getSettingNamesLocked();
2276 }
2277
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002278 public SparseBooleanArray getKnownUsersLocked() {
2279 SparseBooleanArray users = new SparseBooleanArray();
2280 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2281 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2282 }
2283 return users;
2284 }
2285
Kweku Adamsb0886f32017-10-31 15:32:09 -07002286 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002287 public SettingsState getSettingsLocked(int type, int userId) {
2288 final int key = makeKey(type, userId);
2289 return peekSettingsStateLocked(key);
2290 }
2291
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002292 public boolean ensureSettingsForUserLocked(int userId) {
2293 // First make sure this user actually exists.
2294 if (mUserManager.getUserInfo(userId) == null) {
2295 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2296 return false;
2297 }
2298
Svetoslav683914b2015-01-15 14:22:26 -08002299 // Migrate the setting for this user if needed.
2300 migrateLegacySettingsForUserIfNeededLocked(userId);
2301
2302 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002303 if (userId == UserHandle.USER_SYSTEM) {
2304 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002305 ensureSettingsStateLocked(globalKey);
2306 }
2307
2308 // Ensure secure settings loaded.
2309 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2310 ensureSettingsStateLocked(secureKey);
2311
2312 // Make sure the secure settings have an Android id set.
2313 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2314 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2315
2316 // Ensure system settings loaded.
2317 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2318 ensureSettingsStateLocked(systemKey);
2319
Mark Rathjend891f012017-01-19 04:10:37 +00002320 // Ensure secure settings loaded.
2321 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2322 ensureSettingsStateLocked(ssaidKey);
2323
Svetoslav683914b2015-01-15 14:22:26 -08002324 // Upgrade the settings to the latest version.
2325 UpgradeController upgrader = new UpgradeController(userId);
2326 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002327 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002328 }
2329
2330 private void ensureSettingsStateLocked(int key) {
2331 if (mSettingsStates.get(key) == null) {
2332 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002333 SettingsState settingsState = new SettingsState(getContext(), mLock,
2334 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002335 mSettingsStates.put(key, settingsState);
2336 }
2337 }
2338
2339 public void removeUserStateLocked(int userId, boolean permanently) {
2340 // We always keep the global settings in memory.
2341
2342 // Nuke system settings.
2343 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2344 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2345 if (systemSettingsState != null) {
2346 if (permanently) {
2347 mSettingsStates.remove(systemKey);
2348 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002349 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002350 systemSettingsState.destroyLocked(new Runnable() {
2351 @Override
2352 public void run() {
2353 mSettingsStates.remove(systemKey);
2354 }
2355 });
2356 }
2357 }
2358
2359 // Nuke secure settings.
2360 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2361 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2362 if (secureSettingsState != null) {
2363 if (permanently) {
2364 mSettingsStates.remove(secureKey);
2365 secureSettingsState.destroyLocked(null);
2366 } else {
2367 secureSettingsState.destroyLocked(new Runnable() {
2368 @Override
2369 public void run() {
2370 mSettingsStates.remove(secureKey);
2371 }
2372 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002373 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002374 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002375
Mark Rathjend891f012017-01-19 04:10:37 +00002376 // Nuke ssaid settings.
2377 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2378 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2379 if (ssaidSettingsState != null) {
2380 if (permanently) {
2381 mSettingsStates.remove(ssaidKey);
2382 ssaidSettingsState.destroyLocked(null);
2383 } else {
2384 ssaidSettingsState.destroyLocked(new Runnable() {
2385 @Override
2386 public void run() {
2387 mSettingsStates.remove(ssaidKey);
2388 }
2389 });
2390 }
2391 }
2392
Svet Ganov53a441c2016-04-19 19:38:00 -07002393 // Nuke generation tracking data
2394 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002395 }
2396
Svetoslav683914b2015-01-15 14:22:26 -08002397 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002398 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2399 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002400 final int key = makeKey(type, userId);
2401
Svetoslav Ganove080da92016-12-21 17:10:35 -08002402 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002403 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002404 if (settingsState != null) {
2405 success = settingsState.insertSettingLocked(name, value,
2406 tag, makeDefault, packageName);
2407 }
Svetoslav683914b2015-01-15 14:22:26 -08002408
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002409 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2410 settingsState.persistSyncLocked();
2411 }
2412
Svet Ganov53a441c2016-04-19 19:38:00 -07002413 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002414 notifyForSettingsChange(key, name);
2415 }
2416 return success;
2417 }
2418
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002419 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2420 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002421 final int key = makeKey(type, userId);
2422
Svetoslav Ganove080da92016-12-21 17:10:35 -08002423 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002424 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002425 if (settingsState != null) {
2426 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002427 }
Svetoslav683914b2015-01-15 14:22:26 -08002428
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002429 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2430 settingsState.persistSyncLocked();
2431 }
2432
Svet Ganov53a441c2016-04-19 19:38:00 -07002433 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002434 notifyForSettingsChange(key, name);
2435 }
2436 return success;
2437 }
2438
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002439 public boolean updateSettingLocked(int type, int userId, String name, String value,
2440 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2441 Set<String> criticalSettings) {
2442 final int key = makeKey(type, userId);
2443
2444 boolean success = false;
2445 SettingsState settingsState = peekSettingsStateLocked(key);
2446 if (settingsState != null) {
2447 success = settingsState.updateSettingLocked(name, value, tag,
2448 makeDefault, packageName);
2449 }
2450
2451 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2452 settingsState.persistSyncLocked();
2453 }
2454
2455 if (forceNotify || success) {
2456 notifyForSettingsChange(key, name);
2457 }
2458
2459 return success;
2460 }
2461
Svetoslav683914b2015-01-15 14:22:26 -08002462 public Setting getSettingLocked(int type, int userId, String name) {
2463 final int key = makeKey(type, userId);
2464
2465 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002466 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002467 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002468 }
Mark Rathjend891f012017-01-19 04:10:37 +00002469
2470 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002471 return settingsState.getSettingLocked(name);
2472 }
2473
Svetoslav Ganove080da92016-12-21 17:10:35 -08002474 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2475 String tag) {
2476 final int key = makeKey(type, userId);
2477 SettingsState settingsState = peekSettingsStateLocked(key);
2478 if (settingsState == null) {
2479 return;
2480 }
2481
2482 switch (mode) {
2483 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2484 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002485 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002486 Setting setting = settingsState.getSettingLocked(name);
2487 if (packageName.equals(setting.getPackageName())) {
2488 if (tag != null && !tag.equals(setting.getTag())) {
2489 continue;
2490 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002491 if (settingsState.resetSettingLocked(name)) {
2492 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002493 notifyForSettingsChange(key, name);
2494 }
2495 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002496 if (someSettingChanged) {
2497 settingsState.persistSyncLocked();
2498 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002499 }
2500 } break;
2501
2502 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2503 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002504 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002505 Setting setting = settingsState.getSettingLocked(name);
2506 if (!SettingsState.isSystemPackage(getContext(),
2507 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002508 if (settingsState.resetSettingLocked(name)) {
2509 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002510 notifyForSettingsChange(key, name);
2511 }
2512 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002513 if (someSettingChanged) {
2514 settingsState.persistSyncLocked();
2515 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002516 }
2517 } break;
2518
2519 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2520 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002521 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002522 Setting setting = settingsState.getSettingLocked(name);
2523 if (!SettingsState.isSystemPackage(getContext(),
2524 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002525 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002526 if (settingsState.resetSettingLocked(name)) {
2527 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002528 notifyForSettingsChange(key, name);
2529 }
2530 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002531 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002532 notifyForSettingsChange(key, name);
2533 }
2534 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002535 if (someSettingChanged) {
2536 settingsState.persistSyncLocked();
2537 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002538 }
2539 } break;
2540
2541 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2542 for (String name : settingsState.getSettingNamesLocked()) {
2543 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002544 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002545 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002546 if (settingsState.resetSettingLocked(name)) {
2547 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002548 notifyForSettingsChange(key, name);
2549 }
2550 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002551 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002552 notifyForSettingsChange(key, name);
2553 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002554 if (someSettingChanged) {
2555 settingsState.persistSyncLocked();
2556 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002557 }
2558 } break;
2559 }
2560 }
2561
Zimuzoc56192c2018-07-25 10:40:01 +01002562 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002563 // Global and secure settings are signature protected. Apps signed
2564 // by the platform certificate are generally not uninstalled and
2565 // the main exception is tests. We trust components signed
2566 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002567
2568 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2569 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002570 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002571 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002572 }
Svetoslav683914b2015-01-15 14:22:26 -08002573 }
2574
Mark Rathjend891f012017-01-19 04:10:37 +00002575 public void onUidRemovedLocked(int uid) {
2576 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2577 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002578 if (ssaidSettings != null) {
2579 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2580 }
Mark Rathjend891f012017-01-19 04:10:37 +00002581 }
2582
Kweku Adamsb0886f32017-10-31 15:32:09 -07002583 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002584 private SettingsState peekSettingsStateLocked(int key) {
2585 SettingsState settingsState = mSettingsStates.get(key);
2586 if (settingsState != null) {
2587 return settingsState;
2588 }
2589
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002590 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2591 return null;
2592 }
Svetoslav683914b2015-01-15 14:22:26 -08002593 return mSettingsStates.get(key);
2594 }
2595
2596 private void migrateAllLegacySettingsIfNeeded() {
2597 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002598 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002599 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002600 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002601 return;
2602 }
2603
Amith Yamasani39452022017-03-21 15:23:47 -07002604 mSettingsCreationBuildId = Build.ID;
2605
Svetoslav683914b2015-01-15 14:22:26 -08002606 final long identity = Binder.clearCallingIdentity();
2607 try {
2608 List<UserInfo> users = mUserManager.getUsers(true);
2609
2610 final int userCount = users.size();
2611 for (int i = 0; i < userCount; i++) {
2612 final int userId = users.get(i).id;
2613
2614 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2615 SQLiteDatabase database = dbHelper.getWritableDatabase();
2616 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2617
2618 // Upgrade to the latest version.
2619 UpgradeController upgrader = new UpgradeController(userId);
2620 upgrader.upgradeIfNeededLocked();
2621
2622 // Drop from memory if not a running user.
2623 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2624 removeUserStateLocked(userId, false);
2625 }
2626 }
2627 } finally {
2628 Binder.restoreCallingIdentity(identity);
2629 }
2630 }
2631 }
2632
2633 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2634 // Every user has secure settings and if no file we need to migrate.
2635 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2636 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002637 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002638 return;
2639 }
2640
2641 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2642 SQLiteDatabase database = dbHelper.getWritableDatabase();
2643
2644 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2645 }
2646
2647 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2648 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002649 // Move over the system settings.
2650 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2651 ensureSettingsStateLocked(systemKey);
2652 SettingsState systemSettings = mSettingsStates.get(systemKey);
2653 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2654 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002655
2656 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002657 // Do this after System settings, since this is the first thing we check when deciding
2658 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002659 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2660 ensureSettingsStateLocked(secureKey);
2661 SettingsState secureSettings = mSettingsStates.get(secureKey);
2662 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2663 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2664 secureSettings.persistSyncLocked();
2665
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002666 // Move over the global settings if owner.
2667 // Do this last, since this is the first thing we check when deciding
2668 // to skip over migration from db to xml for owner user.
2669 if (userId == UserHandle.USER_SYSTEM) {
2670 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2671 ensureSettingsStateLocked(globalKey);
2672 SettingsState globalSettings = mSettingsStates.get(globalKey);
2673 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002674 // If this was just created
2675 if (mSettingsCreationBuildId != null) {
2676 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2677 mSettingsCreationBuildId, null, true,
2678 SettingsState.SYSTEM_PACKAGE_NAME);
2679 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002680 globalSettings.persistSyncLocked();
2681 }
Svetoslav683914b2015-01-15 14:22:26 -08002682
2683 // Drop the database as now all is moved and persisted.
2684 if (DROP_DATABASE_ON_MIGRATION) {
2685 dbHelper.dropDatabase();
2686 } else {
2687 dbHelper.backupDatabase();
2688 }
2689 }
2690
2691 private void migrateLegacySettingsLocked(SettingsState settingsState,
2692 SQLiteDatabase database, String table) {
2693 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2694 queryBuilder.setTables(table);
2695
2696 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2697 null, null, null, null, null);
2698
2699 if (cursor == null) {
2700 return;
2701 }
2702
2703 try {
2704 if (!cursor.moveToFirst()) {
2705 return;
2706 }
2707
2708 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2709 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2710
2711 settingsState.setVersionLocked(database.getVersion());
2712
2713 while (!cursor.isAfterLast()) {
2714 String name = cursor.getString(nameColumnIdx);
2715 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002716 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002717 SettingsState.SYSTEM_PACKAGE_NAME);
2718 cursor.moveToNext();
2719 }
2720 } finally {
2721 cursor.close();
2722 }
2723 }
2724
Andreas Gampeb58893072018-09-05 16:52:31 -07002725 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002726 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2727 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2728
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002729 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002730 return;
2731 }
2732
2733 final int userId = getUserIdFromKey(secureSettings.mKey);
2734
2735 final UserInfo user;
2736 final long identity = Binder.clearCallingIdentity();
2737 try {
2738 user = mUserManager.getUserInfo(userId);
2739 } finally {
2740 Binder.restoreCallingIdentity(identity);
2741 }
2742 if (user == null) {
2743 // Can happen due to races when deleting users - treat as benign.
2744 return;
2745 }
2746
2747 String androidId = Long.toHexString(new SecureRandom().nextLong());
2748 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002749 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002750
2751 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2752 + "] for user " + userId);
2753
2754 // Write a drop box entry if it's a restricted profile
2755 if (user.isRestricted()) {
2756 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2757 Context.DROPBOX_SERVICE);
2758 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2759 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2760 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2761 }
2762 }
2763 }
2764
2765 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07002766 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07002767 mGenerationRegistry.incrementGeneration(key);
2768
Svet Ganov945864c2018-03-22 21:49:10 -07002769 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06002770 final long token = Binder.clearCallingIdentity();
2771 try {
2772 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2773 // When the global kill switch is updated, send the
2774 // change notification for the location setting.
2775 notifyLocationChangeForRunningUsers();
2776 }
2777 notifyGlobalSettingChangeForRunningUsers(key, name);
2778 } finally {
2779 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07002780 }
Svet Ganov945864c2018-03-22 21:49:10 -07002781 } else {
2782 final int userId = getUserIdFromKey(key);
2783 final Uri uri = getNotificationUriFor(key, name);
2784 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2785 userId, 0, uri).sendToTarget();
2786 if (isSecureSettingsKey(key)) {
2787 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2788 sSecureCloneToManagedSettings);
2789 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2790 sSystemCloneFromParentOnDependency.values());
2791 } else if (isSystemSettingsKey(key)) {
2792 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2793 sSystemCloneToManagedSettings);
2794 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002795 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002796
Svet Ganov945864c2018-03-22 21:49:10 -07002797 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07002798 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002799 }
2800
Svet Ganov53a441c2016-04-19 19:38:00 -07002801 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002802 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002803 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002804 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002805 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002806 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07002807 final int key = makeKey(type, profileId);
2808 // Increment the generation first, so observers always see the new value
2809 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07002810 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002811 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002812 }
2813 }
2814 }
Svetoslav683914b2015-01-15 14:22:26 -08002815 }
2816
Svet Ganov945864c2018-03-22 21:49:10 -07002817 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
2818 // Important: No need to update generation for each user as there
2819 // is a singleton generation entry for the global settings which
2820 // is already incremented be the caller.
2821 final Uri uri = getNotificationUriFor(key, name);
2822 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
2823 for (int i = 0; i < users.size(); i++) {
2824 final int userId = users.get(i).id;
2825 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
2826 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2827 userId, 0, uri).sendToTarget();
2828 }
2829 }
2830 }
2831
Makoto Onuki0000d322017-11-28 16:31:47 -08002832 private void notifyLocationChangeForRunningUsers() {
2833 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2834
2835 for (int i = 0; i < users.size(); i++) {
2836 final int userId = users.get(i).id;
2837
2838 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2839 continue;
2840 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002841
Svet Ganov945864c2018-03-22 21:49:10 -07002842 // Increment the generation first, so observers always see the new value
2843 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2844 mGenerationRegistry.incrementGeneration(key);
2845
2846 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08002847 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2848 userId, 0, uri).sendToTarget();
2849 }
2850 }
2851
Svetoslav683914b2015-01-15 14:22:26 -08002852 private boolean isGlobalSettingsKey(int key) {
2853 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2854 }
2855
2856 private boolean isSystemSettingsKey(int key) {
2857 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2858 }
2859
2860 private boolean isSecureSettingsKey(int key) {
2861 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2862 }
2863
Mark Rathjend891f012017-01-19 04:10:37 +00002864 private boolean isSsaidSettingsKey(int key) {
2865 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2866 }
2867
Svetoslav683914b2015-01-15 14:22:26 -08002868 private File getSettingsFile(int key) {
2869 if (isGlobalSettingsKey(key)) {
2870 final int userId = getUserIdFromKey(key);
2871 return new File(Environment.getUserSystemDirectory(userId),
2872 SETTINGS_FILE_GLOBAL);
2873 } else if (isSystemSettingsKey(key)) {
2874 final int userId = getUserIdFromKey(key);
2875 return new File(Environment.getUserSystemDirectory(userId),
2876 SETTINGS_FILE_SYSTEM);
2877 } else if (isSecureSettingsKey(key)) {
2878 final int userId = getUserIdFromKey(key);
2879 return new File(Environment.getUserSystemDirectory(userId),
2880 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002881 } else if (isSsaidSettingsKey(key)) {
2882 final int userId = getUserIdFromKey(key);
2883 return new File(Environment.getUserSystemDirectory(userId),
2884 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002885 } else {
2886 throw new IllegalArgumentException("Invalid settings key:" + key);
2887 }
2888 }
2889
2890 private Uri getNotificationUriFor(int key, String name) {
2891 if (isGlobalSettingsKey(key)) {
2892 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2893 : Settings.Global.CONTENT_URI;
2894 } else if (isSecureSettingsKey(key)) {
2895 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2896 : Settings.Secure.CONTENT_URI;
2897 } else if (isSystemSettingsKey(key)) {
2898 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2899 : Settings.System.CONTENT_URI;
2900 } else {
2901 throw new IllegalArgumentException("Invalid settings key:" + key);
2902 }
2903 }
2904
2905 private int getMaxBytesPerPackageForType(int type) {
2906 switch (type) {
2907 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002908 case SETTINGS_TYPE_SECURE:
2909 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002910 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2911 }
2912
2913 default: {
2914 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2915 }
2916 }
2917 }
2918
Svetoslav7e0683b2015-08-03 16:02:52 -07002919 private final class MyHandler extends Handler {
2920 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2921 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2922
2923 public MyHandler(Looper looper) {
2924 super(looper);
2925 }
2926
2927 @Override
2928 public void handleMessage(Message msg) {
2929 switch (msg.what) {
2930 case MSG_NOTIFY_URI_CHANGED: {
2931 final int userId = msg.arg1;
2932 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002933 try {
2934 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2935 } catch (SecurityException e) {
2936 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2937 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002938 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002939 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2940 }
2941 } break;
2942
2943 case MSG_NOTIFY_DATA_CHANGED: {
2944 mBackupManager.dataChanged();
2945 } break;
2946 }
2947 }
2948 }
2949
Svetoslav683914b2015-01-15 14:22:26 -08002950 private final class UpgradeController {
Beverly91d0a632018-07-02 16:45:00 -04002951 private static final int SETTINGS_VERSION = 171;
Svetoslav683914b2015-01-15 14:22:26 -08002952
2953 private final int mUserId;
2954
2955 public UpgradeController(int userId) {
2956 mUserId = userId;
2957 }
2958
2959 public void upgradeIfNeededLocked() {
2960 // The version of all settings for a user is the same (all users have secure).
2961 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002962 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002963
2964 // Try an update from the current state.
2965 final int oldVersion = secureSettings.getVersionLocked();
2966 final int newVersion = SETTINGS_VERSION;
2967
Svet Ganovc9755bc2015-03-28 13:21:22 -07002968 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002969 if (oldVersion == newVersion) {
2970 return;
2971 }
2972
2973 // Try to upgrade.
2974 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2975
2976 // If upgrade failed start from scratch and upgrade.
2977 if (curVersion != newVersion) {
2978 // Drop state we have for this user.
2979 removeUserStateLocked(mUserId, true);
2980
2981 // Recreate the database.
2982 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2983 SQLiteDatabase database = dbHelper.getWritableDatabase();
2984 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2985
2986 // Migrate the settings for this user.
2987 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2988
2989 // Now upgrade should work fine.
2990 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002991
2992 // Make a note what happened, so we don't wonder why data was lost
2993 String reason = "Settings rebuilt! Current version: "
2994 + curVersion + " while expected: " + newVersion;
2995 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002996 Settings.Global.DATABASE_DOWNGRADE_REASON,
2997 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002998 }
2999
3000 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003001 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003002 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003003 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003004 globalSettings.setVersionLocked(newVersion);
3005 }
3006
3007 // Set the secure settings version.
3008 secureSettings.setVersionLocked(newVersion);
3009
3010 // Set the system settings version.
3011 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003012 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003013 systemSettings.setVersionLocked(newVersion);
3014 }
3015
3016 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003017 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003018 }
3019
3020 private SettingsState getSecureSettingsLocked(int userId) {
3021 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3022 }
3023
Mark Rathjend891f012017-01-19 04:10:37 +00003024 private SettingsState getSsaidSettingsLocked(int userId) {
3025 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3026 }
3027
Svetoslav683914b2015-01-15 14:22:26 -08003028 private SettingsState getSystemSettingsLocked(int userId) {
3029 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3030 }
3031
Jeff Brown503cffc2015-03-26 18:08:51 -07003032 /**
3033 * You must perform all necessary mutations to bring the settings
3034 * for this user from the old to the new version. When you add a new
3035 * upgrade step you *must* update SETTINGS_VERSION.
3036 *
3037 * This is an example of moving a setting from secure to global.
3038 *
3039 * // v119: Example settings changes.
3040 * if (currentVersion == 118) {
3041 * if (userId == UserHandle.USER_OWNER) {
3042 * // Remove from the secure settings.
3043 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3044 * String name = "example_setting_to_move";
3045 * String value = secureSettings.getSetting(name);
3046 * secureSettings.deleteSetting(name);
3047 *
3048 * // Add to the global settings.
3049 * SettingsState globalSettings = getGlobalSettingsLocked();
3050 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3051 * }
3052 *
3053 * // Update the current version.
3054 * currentVersion = 119;
3055 * }
3056 */
Svetoslav683914b2015-01-15 14:22:26 -08003057 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3058 if (DEBUG) {
3059 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3060 + oldVersion + " to version: " + newVersion);
3061 }
3062
Jeff Brown503cffc2015-03-26 18:08:51 -07003063 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003064
John Spurlocke11ae112015-05-11 16:09:03 -04003065 // v119: Reset zen + ringer mode.
3066 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003067 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003068 final SettingsState globalSettings = getGlobalSettingsLocked();
3069 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003070 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3071 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003072 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003073 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3074 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003075 }
3076 currentVersion = 119;
3077 }
3078
Jason Monk27bbb2d2015-03-31 16:46:39 -04003079 // v120: Add double tap to wake setting.
3080 if (currentVersion == 119) {
3081 SettingsState secureSettings = getSecureSettingsLocked(userId);
3082 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3083 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003084 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003085 SettingsState.SYSTEM_PACKAGE_NAME);
3086
3087 currentVersion = 120;
3088 }
3089
Svetoslav7e0683b2015-08-03 16:02:52 -07003090 if (currentVersion == 120) {
3091 // Before 121, we used a different string encoding logic. We just bump the
3092 // version here; SettingsState knows how to handle pre-version 120 files.
3093 currentVersion = 121;
3094 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003095
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003096 if (currentVersion == 121) {
3097 // Version 122: allow OEMs to set a default payment component in resources.
3098 // Note that we only write the default if no default has been set;
3099 // if there is, we just leave the default at whatever it currently is.
3100 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3101 String defaultComponent = (getContext().getResources().getString(
3102 R.string.def_nfc_payment_component));
3103 Setting currentSetting = secureSettings.getSettingLocked(
3104 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3105 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003106 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003107 secureSettings.insertSettingLocked(
3108 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003109 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003110 }
3111 currentVersion = 122;
3112 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003113
3114 if (currentVersion == 122) {
3115 // Version 123: Adding a default value for the ability to add a user from
3116 // the lock screen.
3117 if (userId == UserHandle.USER_SYSTEM) {
3118 final SettingsState globalSettings = getGlobalSettingsLocked();
3119 Setting currentSetting = globalSettings.getSettingLocked(
3120 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003121 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003122 globalSettings.insertSettingLocked(
3123 Settings.Global.ADD_USERS_WHEN_LOCKED,
3124 getContext().getResources().getBoolean(
3125 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003126 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003127 }
3128 }
3129 currentVersion = 123;
3130 }
Bryce Leebd179282015-12-17 19:01:37 -08003131
3132 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003133 final SettingsState globalSettings = getGlobalSettingsLocked();
3134 String defaultDisabledProfiles = (getContext().getResources().getString(
3135 R.string.def_bluetooth_disabled_profiles));
3136 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003137 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003138 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003139 }
3140
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003141 if (currentVersion == 124) {
3142 // Version 124: allow OEMs to set a default value for whether IME should be
3143 // shown when a physical keyboard is connected.
3144 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3145 Setting currentSetting = secureSettings.getSettingLocked(
3146 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003147 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003148 secureSettings.insertSettingLocked(
3149 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3150 getContext().getResources().getBoolean(
3151 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003152 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003153 }
3154 currentVersion = 125;
3155 }
3156
Ruben Brunk98576cf2016-03-07 18:54:28 -08003157 if (currentVersion == 125) {
3158 // Version 125: Allow OEMs to set the default VR service.
3159 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3160
3161 Setting currentSetting = secureSettings.getSettingLocked(
3162 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003163 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003164 ArraySet<ComponentName> l =
3165 SystemConfig.getInstance().getDefaultVrComponents();
3166
3167 if (l != null && !l.isEmpty()) {
3168 StringBuilder b = new StringBuilder();
3169 boolean start = true;
3170 for (ComponentName c : l) {
3171 if (!start) {
3172 b.append(':');
3173 }
3174 b.append(c.flattenToString());
3175 start = false;
3176 }
3177 secureSettings.insertSettingLocked(
3178 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003179 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003180 }
3181
3182 }
3183 currentVersion = 126;
3184 }
3185
Daniel U02ba6122016-04-01 18:41:42 +01003186 if (currentVersion == 126) {
3187 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3188 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3189 if (mUserManager.isManagedProfile(userId)) {
3190 final SettingsState systemSecureSettings =
3191 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3192
3193 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3194 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003195 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003196 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3197 secureSettings.insertSettingLocked(
3198 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003199 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003200 SettingsState.SYSTEM_PACKAGE_NAME);
3201 }
3202
3203 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3204 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003205 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003206 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3207 secureSettings.insertSettingLocked(
3208 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003209 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003210 SettingsState.SYSTEM_PACKAGE_NAME);
3211 }
3212 }
3213 currentVersion = 127;
3214 }
3215
Steven Ngdc20ba62016-04-26 18:19:04 +01003216 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003217 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003218 currentVersion = 128;
3219 }
3220
Julia Reynolds1f721e12016-07-11 08:50:58 -04003221 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003222 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003223 currentVersion = 129;
3224 }
3225
Dan Sandler71f85e92016-07-20 13:46:05 -04003226 if (currentVersion == 129) {
3227 // default longpress timeout changed from 500 to 400. If unchanged from the old
3228 // default, update to the new default.
3229 final SettingsState systemSecureSettings =
3230 getSecureSettingsLocked(userId);
3231 final String oldValue = systemSecureSettings.getSettingLocked(
3232 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3233 if (TextUtils.equals("500", oldValue)) {
3234 systemSecureSettings.insertSettingLocked(
3235 Settings.Secure.LONG_PRESS_TIMEOUT,
3236 String.valueOf(getContext().getResources().getInteger(
3237 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003238 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003239 }
3240 currentVersion = 130;
3241 }
3242
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003243 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003244 // Split Ambient settings
3245 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3246 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3247 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3248
3249 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003250 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003251 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003252 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003253 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003254 }
3255 currentVersion = 131;
3256 }
3257
3258 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003259 // Initialize new multi-press timeout to default value
3260 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3261 final String oldValue = systemSecureSettings.getSettingLocked(
3262 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3263 if (TextUtils.equals(null, oldValue)) {
3264 systemSecureSettings.insertSettingLocked(
3265 Settings.Secure.MULTI_PRESS_TIMEOUT,
3266 String.valueOf(getContext().getResources().getInteger(
3267 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003268 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003269 }
3270
Adrian Roos69741a22016-10-21 14:49:17 -07003271 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003272 }
3273
Adrian Roos69741a22016-10-21 14:49:17 -07003274 if (currentVersion == 132) {
3275 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003276 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3277 String defaultSyncParentSounds = (getContext().getResources()
3278 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3279 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003280 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3281 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003282 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003283 }
3284
Adrian Roos69741a22016-10-21 14:49:17 -07003285 if (currentVersion == 133) {
3286 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003287 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3288 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3289 null) {
3290 String defaultEndButtonBehavior = Integer.toString(getContext()
3291 .getResources().getInteger(R.integer.def_end_button_behavior));
3292 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003293 defaultEndButtonBehavior, null, true,
3294 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003295 }
Adrian Roos69741a22016-10-21 14:49:17 -07003296 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003297 }
3298
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003299 if (currentVersion == 134) {
3300 // Remove setting that specifies if magnification values should be preserved.
3301 // This setting defaulted to true and never has a UI.
3302 getSecureSettingsLocked(userId).deleteSettingLocked(
3303 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3304 currentVersion = 135;
3305 }
3306
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003307 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003308 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003309 currentVersion = 136;
3310 }
3311
Mark Rathjend891f012017-01-19 04:10:37 +00003312 if (currentVersion == 136) {
3313 // Version 136: Store legacy SSAID for all apps currently installed on the
3314 // device as first step in migrating SSAID to be unique per application.
3315
3316 final boolean isUpgrade;
3317 try {
3318 isUpgrade = mPackageManager.isUpgrade();
3319 } catch (RemoteException e) {
3320 throw new IllegalStateException("Package manager not available");
3321 }
3322 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3323 // user data or first boot on a new device should use new ssaid generation.
3324 if (isUpgrade) {
3325 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003326 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3327 userId, Settings.Secure.ANDROID_ID);
3328 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3329 || legacySsaidSetting.getValue() == null) {
3330 throw new IllegalStateException("Legacy ssaid not accessible");
3331 }
3332 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003333
3334 // Fill each uid with the legacy ssaid to be backwards compatible.
3335 final List<PackageInfo> packages;
3336 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003337 packages = mPackageManager.getInstalledPackages(
3338 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3339 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003340 } catch (RemoteException e) {
3341 throw new IllegalStateException("Package manager not available");
3342 }
3343
3344 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3345 for (PackageInfo info : packages) {
3346 // Check if the UID already has an entry in the table.
3347 final String uid = Integer.toString(info.applicationInfo.uid);
3348 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3349
3350 if (ssaid.isNull() || ssaid.getValue() == null) {
3351 // Android Id doesn't exist for this package so create it.
3352 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3353 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003354 if (DEBUG) {
3355 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3356 }
Mark Rathjend891f012017-01-19 04:10:37 +00003357 }
3358 }
3359 }
3360
3361 currentVersion = 137;
3362 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003363 if (currentVersion == 137) {
3364 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3365 // default value set to 1. The user can no longer change the value of this
3366 // setting through the UI.
3367 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3368 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003369 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3370 && secureSetting.getSettingLocked(
3371 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3372
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003373 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3374 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003375 // For managed profiles with profile owners, DevicePolicyManagerService
3376 // may want to set the user restriction in this case
3377 secureSetting.insertSettingLocked(
3378 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3379 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003380 }
3381 currentVersion = 138;
3382 }
Mark Rathjend891f012017-01-19 04:10:37 +00003383
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003384 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003385 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003386 currentVersion = 139;
3387 }
3388
Phil Weaver385912e2017-02-10 10:06:56 -08003389 if (currentVersion == 139) {
3390 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3391 // the user can no longer change the value of this setting through the UI.
3392 // Force to true.
3393 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3394 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3395 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3396 currentVersion = 140;
3397 }
3398
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003399 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003400 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003401 currentVersion = 141;
3402 }
3403
Svet Ganov13701552017-02-23 12:45:17 -08003404 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003405 // This implementation was incorrectly setting the current value of
3406 // settings changed by non-system packages as the default which default
3407 // is set by the system. We add a new upgrade step at the end to properly
3408 // handle this case which would also fix incorrect changes made by the
3409 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003410 currentVersion = 142;
3411 }
3412
Stephen Chen5d0922f2017-03-27 10:28:04 -07003413 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003414 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003415 if (userId == UserHandle.USER_SYSTEM) {
3416 final SettingsState globalSettings = getGlobalSettingsLocked();
3417 Setting currentSetting = globalSettings.getSettingLocked(
3418 Settings.Global.WIFI_WAKEUP_ENABLED);
3419 if (currentSetting.isNull()) {
3420 globalSettings.insertSettingLocked(
3421 Settings.Global.WIFI_WAKEUP_ENABLED,
3422 getContext().getResources().getBoolean(
3423 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3424 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3425 }
3426 }
3427
3428 currentVersion = 143;
3429 }
3430
Felipe Lemeff355092017-04-03 12:55:02 -07003431 if (currentVersion == 143) {
3432 // Version 144: Set a default value for Autofill service.
3433 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3434 final Setting currentSetting = secureSettings
3435 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3436 if (currentSetting.isNull()) {
3437 final String defaultValue = getContext().getResources().getString(
3438 com.android.internal.R.string.config_defaultAutofillService);
3439 if (defaultValue != null) {
3440 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3441 + "for user " + userId);
3442 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3443 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3444 }
3445 }
3446
3447 currentVersion = 144;
3448 }
3449
Jeremy Joslin45caa252017-05-04 11:22:46 -07003450 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003451 // Version 145: Removed
3452 currentVersion = 145;
3453 }
3454
3455 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003456 // Version 146: In step 142 we had a bug where incorrectly
3457 // some settings were considered system set and as a result
3458 // made the default and marked as the default being set by
3459 // the system. Here reevaluate the default and default system
3460 // set flags. This would both fix corruption by the old impl
3461 // of step 142 and also properly handle devices which never
3462 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003463 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003464 SettingsState globalSettings = getGlobalSettingsLocked();
3465 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3466 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003467 }
3468
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003469 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3470 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3471 secureSettings.persistSyncLocked();
3472
3473 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3474 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3475 systemSettings.persistSyncLocked();
3476
Amin Shaikh86367962017-06-07 08:58:22 -07003477 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003478 }
3479
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003480 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003481 // Version 147: Removed. (This version previously allowed showing the
3482 // "wifi_wakeup_available" setting).
3483 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003484 currentVersion = 147;
3485 }
3486
3487 if (currentVersion == 147) {
3488 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003489 if (userId == UserHandle.USER_SYSTEM) {
3490 final SettingsState globalSettings = getGlobalSettingsLocked();
3491 final Setting currentSetting = globalSettings.getSettingLocked(
3492 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3493 if (currentSetting.isNull()) {
3494 globalSettings.insertSettingLocked(
3495 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3496 getContext().getResources().getBoolean(
3497 R.bool.def_restrict_background_data) ? "1" : "0",
3498 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3499 }
3500 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003501 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003502 }
3503
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003504 if (currentVersion == 148) {
3505 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3506 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3507 final String oldValue = systemSecureSettings.getSettingLocked(
3508 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3509 if (TextUtils.equals(null, oldValue)) {
3510 final String defaultValue = getContext().getResources().getString(
3511 R.string.def_backup_manager_constants);
3512 if (!TextUtils.isEmpty(defaultValue)) {
3513 systemSecureSettings.insertSettingLocked(
3514 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3515 true, SettingsState.SYSTEM_PACKAGE_NAME);
3516 }
3517 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003518 currentVersion = 149;
3519 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003520
3521 if (currentVersion == 149) {
3522 // Version 150: Set a default value for mobile data always on
3523 final SettingsState globalSettings = getGlobalSettingsLocked();
3524 final Setting currentSetting = globalSettings.getSettingLocked(
3525 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3526 if (currentSetting.isNull()) {
3527 globalSettings.insertSettingLocked(
3528 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3529 getContext().getResources().getBoolean(
3530 R.bool.def_mobile_data_always_on) ? "1" : "0",
3531 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3532 }
3533
3534 currentVersion = 150;
3535 }
3536
Mike Digman4af4a6f2018-01-16 14:49:38 -08003537 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003538 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003539 currentVersion = 151;
3540 }
3541
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003542 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003543 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3544 // by default but it is now no longer configurable).
3545 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003546 currentVersion = 152;
3547 }
3548
Joe LaPenna250d7842018-01-25 10:19:42 -08003549 if (currentVersion == 152) {
3550 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3551 currentVersion = 153;
3552 }
3553
Ben Linb4df8bc2018-01-29 11:48:20 -08003554 if (currentVersion == 153) {
3555 // Version 154: Read notification badge configuration from config.
3556 // If user has already set the value, don't do anything.
3557 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3558 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3559 Settings.Secure.NOTIFICATION_BADGING);
3560 if (showNotificationBadges.isNull()) {
3561 final boolean defaultValue = getContext().getResources().getBoolean(
3562 com.android.internal.R.bool.config_notificationBadging);
3563 systemSecureSettings.insertSettingLocked(
3564 Secure.NOTIFICATION_BADGING,
3565 defaultValue ? "1" : "0",
3566 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3567 }
3568 currentVersion = 154;
3569 }
3570
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003571 if (currentVersion == 154) {
3572 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3573 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3574 final String oldValue = systemSecureSettings.getSettingLocked(
3575 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3576 if (TextUtils.equals(null, oldValue)) {
3577 final String defaultValue = getContext().getResources().getString(
3578 R.string.def_backup_local_transport_parameters);
3579 if (!TextUtils.isEmpty(defaultValue)) {
3580 systemSecureSettings.insertSettingLocked(
3581 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3582 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3583 }
3584
3585 }
3586 currentVersion = 155;
3587 }
3588
Beverlyda904812018-03-02 09:55:30 -05003589 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003590 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003591 final SettingsState globalSettings = getGlobalSettingsLocked();
3592 final String oldValue = globalSettings.getSettingLocked(
3593 Global.CHARGING_STARTED_SOUND).getValue();
3594 final String oldDefault = getContext().getResources().getString(
3595 R.string.def_wireless_charging_started_sound);
3596 if (TextUtils.equals(null, oldValue)
3597 || TextUtils.equals(oldValue, oldDefault)) {
3598 final String defaultValue = getContext().getResources().getString(
3599 R.string.def_charging_started_sound);
3600 if (!TextUtils.isEmpty(defaultValue)) {
3601 globalSettings.insertSettingLocked(
3602 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3603 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3604 }
3605
3606 }
3607 currentVersion = 156;
3608 }
3609
Beverly09da25f2018-02-26 09:17:07 -05003610 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003611 // Version 157: Set a default value for zen duration,
3612 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003613 final SettingsState globalSettings = getGlobalSettingsLocked();
3614 final Setting currentSetting = globalSettings.getSettingLocked(
3615 Global.ZEN_DURATION);
3616 if (currentSetting.isNull()) {
3617 String defaultZenDuration = Integer.toString(getContext()
3618 .getResources().getInteger(R.integer.def_zen_duration));
3619 globalSettings.insertSettingLocked(
3620 Global.ZEN_DURATION, defaultZenDuration,
3621 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3622 }
Beverly09da25f2018-02-26 09:17:07 -05003623 currentVersion = 157;
3624 }
Annie Mengd069a882018-03-13 15:31:40 +00003625
3626 if (currentVersion == 157) {
3627 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3628 final SettingsState globalSettings = getGlobalSettingsLocked();
3629 final String oldValue = globalSettings.getSettingLocked(
3630 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3631 if (TextUtils.equals(null, oldValue)) {
3632 final String defaultValue = getContext().getResources().getString(
3633 R.string.def_backup_agent_timeout_parameters);
3634 if (!TextUtils.isEmpty(defaultValue)) {
3635 globalSettings.insertSettingLocked(
3636 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3637 null, true,
3638 SettingsState.SYSTEM_PACKAGE_NAME);
3639 }
3640 }
3641 currentVersion = 158;
3642 }
Roshan Pius9c396672018-03-02 14:54:13 -08003643
3644 if (currentVersion == 158) {
3645 // Remove setting that specifies wifi bgscan throttling params
3646 getGlobalSettingsLocked().deleteSettingLocked(
3647 "wifi_scan_background_throttle_interval_ms");
3648 getGlobalSettingsLocked().deleteSettingLocked(
3649 "wifi_scan_background_throttle_package_whitelist");
3650 currentVersion = 159;
3651 }
3652
Pavel Grafovc5c97302018-03-19 13:37:15 +00003653 if (currentVersion == 159) {
3654 // Version 160: Hiding notifications from the lockscreen is only available as
3655 // primary user option, profiles can only make them redacted. If a profile was
3656 // configured to not show lockscreen notifications, ensure that at the very
3657 // least these will be come hidden.
3658 if (mUserManager.isManagedProfile(userId)) {
3659 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3660 Setting showNotifications = secureSettings.getSettingLocked(
3661 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3662 // The default value is "1", check if user has turned it off.
3663 if ("0".equals(showNotifications.getValue())) {
3664 secureSettings.insertSettingLocked(
3665 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3666 null /* tag */, false /* makeDefault */,
3667 SettingsState.SYSTEM_PACKAGE_NAME);
3668 }
3669 // The setting is no longer valid for managed profiles, it should be
3670 // treated as if it was set to "1".
3671 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3672 }
3673 currentVersion = 160;
3674 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003675
3676 if (currentVersion == 160) {
3677 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003678 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003679 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3680 final SettingsState globalSettings = getGlobalSettingsLocked();
3681
3682 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003683 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3684 if (TextUtils.equals(null, oldValue)) {
3685 globalSettings.insertSettingLocked(
3686 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3687 Integer.toString(getContext().getResources().getInteger(
3688 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3689 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3690 }
3691
3692 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003693 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3694 if (TextUtils.equals(null, oldValue)) {
3695 globalSettings.insertSettingLocked(
3696 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3697 Integer.toString(getContext().getResources().getInteger(
3698 R.integer.def_sound_trigger_detection_service_op_timeout)),
3699 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3700 }
3701 currentVersion = 161;
3702 }
3703
Mike Digman55272862018-02-20 14:35:17 -08003704 if (currentVersion == 161) {
3705 // Version 161: Add a gesture for silencing phones
3706 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3707 final Setting currentSetting = secureSettings.getSettingLocked(
3708 Secure.VOLUME_HUSH_GESTURE);
3709 if (currentSetting.isNull()) {
3710 secureSettings.insertSettingLocked(
3711 Secure.VOLUME_HUSH_GESTURE,
3712 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3713 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3714 }
3715
3716 currentVersion = 162;
3717 }
3718
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003719 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003720 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003721 currentVersion = 163;
3722 }
3723
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003724 if (currentVersion == 163) {
3725 // Version 163: Update default value of
3726 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3727 final SettingsState settings = getGlobalSettingsLocked();
3728 final Setting currentSetting = settings.getSettingLocked(
3729 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3730 if (currentSetting.isDefaultFromSystem()) {
3731 settings.insertSettingLocked(
3732 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3733 Integer.toString(getContext().getResources().getInteger(
3734 R.integer
3735 .def_max_sound_trigger_detection_service_ops_per_day)),
3736 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3737 }
3738
3739 currentVersion = 164;
3740 }
3741
Julia Reynolds76bfa602018-04-23 09:38:47 -04003742 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003743 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003744 currentVersion = 165;
3745 }
3746
Beverly301e92a2018-04-27 09:43:05 -04003747 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003748 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3749 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003750 currentVersion = 166;
3751 }
3752
Beverly38fcfd02018-05-18 17:33:40 -04003753 if (currentVersion == 166) {
3754 // Version 166: add default values for hush gesture used and manual ringer
3755 // toggle
3756 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3757 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3758 Secure.HUSH_GESTURE_USED);
3759 if (currentHushUsedSetting.isNull()) {
3760 secureSettings.insertSettingLocked(
3761 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
3762 SettingsState.SYSTEM_PACKAGE_NAME);
3763 }
3764
3765 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
3766 Secure.MANUAL_RINGER_TOGGLE_COUNT);
3767 if (currentRingerToggleCountSetting.isNull()) {
3768 secureSettings.insertSettingLocked(
3769 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
3770 SettingsState.SYSTEM_PACKAGE_NAME);
3771 }
3772 currentVersion = 167;
3773 }
3774
Beverly155c9d22018-05-23 18:03:23 -04003775 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04003776 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
3777 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04003778 currentVersion = 168;
3779 }
3780
Michael Wright0e9eeee2018-05-26 00:31:20 +01003781 if (currentVersion == 168) {
3782 // Version 168: by default, vibrate for phone calls
3783 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3784 final Setting currentSetting = systemSettings.getSettingLocked(
3785 Settings.System.VIBRATE_WHEN_RINGING);
3786 if (currentSetting.isNull()) {
3787 systemSettings.insertSettingLocked(
3788 Settings.System.VIBRATE_WHEN_RINGING,
3789 getContext().getResources().getBoolean(
3790 R.bool.def_vibrate_when_ringing) ? "1" : "0",
3791 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3792 }
3793 currentVersion = 169;
3794 }
3795
Nadav Barf9f115d2018-06-24 10:06:50 +03003796 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04003797 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
3798 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
3799 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03003800
Beverly91d0a632018-07-02 16:45:00 -04003801 final SettingsState globalSettings = getGlobalSettingsLocked();
3802 final Setting globalZenDuration = globalSettings.getSettingLocked(
3803 Global.ZEN_DURATION);
3804
3805 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3806 final Setting secureZenDuration = secureSettings.getSettingLocked(
3807 Secure.ZEN_DURATION);
3808
3809 // ZEN_DURATION
3810 if (!globalZenDuration.isNull()) {
3811 secureSettings.insertSettingLocked(
3812 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
3813 SettingsState.SYSTEM_PACKAGE_NAME);
3814
3815 // set global zen duration setting to null since it's deprecated
3816 globalSettings.insertSettingLocked(
3817 Global.ZEN_DURATION, null, null, true,
3818 SettingsState.SYSTEM_PACKAGE_NAME);
3819 } else if (secureZenDuration.isNull()) {
3820 String defaultZenDuration = Integer.toString(getContext()
3821 .getResources().getInteger(R.integer.def_zen_duration));
3822 secureSettings.insertSettingLocked(
3823 Secure.ZEN_DURATION, defaultZenDuration, null, true,
3824 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03003825 }
Beverly91d0a632018-07-02 16:45:00 -04003826
3827 // SHOW_ZEN_SETTINGS_SUGGESTION
3828 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
3829 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
3830 if (currentShowZenSettingSuggestion.isNull()) {
3831 secureSettings.insertSettingLocked(
3832 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
3833 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3834 }
3835
3836 // ZEN_SETTINGS_UPDATED
3837 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
3838 Secure.ZEN_SETTINGS_UPDATED);
3839 if (currentUpdatedSetting.isNull()) {
3840 secureSettings.insertSettingLocked(
3841 Secure.ZEN_SETTINGS_UPDATED, "0",
3842 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3843 }
3844
3845 // ZEN_SETTINGS_SUGGESTION_VIEWED
3846 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
3847 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
3848 if (currentSettingSuggestionViewed.isNull()) {
3849 secureSettings.insertSettingLocked(
3850 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
3851 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3852 }
3853
Nadav Barf9f115d2018-06-24 10:06:50 +03003854 currentVersion = 170;
3855 }
3856
Beverly91d0a632018-07-02 16:45:00 -04003857 if (currentVersion == 170) {
3858 // Version 170: Set the default value for Secure Settings:
3859 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
3860
3861 final SettingsState globalSettings = getGlobalSettingsLocked();
3862 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3863
3864 // CHARGING_SOUNDS_ENABLED
3865 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
3866 Global.CHARGING_SOUNDS_ENABLED);
3867 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
3868 Secure.CHARGING_SOUNDS_ENABLED);
3869
3870 if (!globalChargingSoundEnabled.isNull()) {
3871 secureSettings.insertSettingLocked(
3872 Secure.CHARGING_SOUNDS_ENABLED,
3873 globalChargingSoundEnabled.getValue(), null, false,
3874 SettingsState.SYSTEM_PACKAGE_NAME);
3875
3876 // set global charging_sounds_enabled setting to null since it's deprecated
3877 globalSettings.insertSettingLocked(
3878 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
3879 SettingsState.SYSTEM_PACKAGE_NAME);
3880 } else if (secureChargingSoundsEnabled.isNull()) {
3881 String defChargingSoundsEnabled = getContext().getResources()
3882 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
3883 secureSettings.insertSettingLocked(
3884 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
3885 true, SettingsState.SYSTEM_PACKAGE_NAME);
3886 }
3887
3888 // CHARGING_VIBRATION_ENABLED
3889 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
3890 Secure.CHARGING_VIBRATION_ENABLED);
3891
3892 if (secureChargingVibrationEnabled.isNull()) {
3893 String defChargingVibrationEnabled = getContext().getResources()
3894 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
3895 secureSettings.insertSettingLocked(
3896 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
3897 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3898 }
3899
3900 currentVersion = 171;
3901 }
3902
Felipe Lemeff355092017-04-03 12:55:02 -07003903 // vXXX: Add new settings above this point.
3904
Dan Sandler71f85e92016-07-20 13:46:05 -04003905 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003906 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003907 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003908 + currentVersion +
3909 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3910 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003911 if (DEBUG) {
3912 throw new RuntimeException("db upgrade error");
3913 }
3914 }
3915
Jeff Brown503cffc2015-03-26 18:08:51 -07003916 // Return the current version.
3917 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003918 }
3919 }
Svet Ganov13701552017-02-23 12:45:17 -08003920
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003921 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3922 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003923 List<String> names = settings.getSettingNamesLocked();
3924 final int nameCount = names.size();
3925 for (int i = 0; i < nameCount; i++) {
3926 String name = names.get(i);
3927 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003928
3929 // In the upgrade case we pretend the call is made from the app
3930 // that made the last change to the setting to properly determine
3931 // whether the call has been made by a system component.
3932 int callingUid = -1;
3933 try {
3934 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3935 } catch (RemoteException e) {
3936 /* ignore - handled below */
3937 }
3938 if (callingUid < 0) {
3939 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3940 continue;
3941 }
3942 try {
3943 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3944 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003945 if (systemSet) {
3946 settings.insertSettingLocked(name, setting.getValue(),
3947 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003948 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3949 // We had a bug where changes by non-system packages were marked
3950 // as system made and as a result set as the default. Therefore, if
3951 // the package changed the setting last is not a system one but the
3952 // setting is marked as its default coming from the system we clear
3953 // the default and clear the system set flag.
3954 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003955 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003956 } catch (IllegalStateException e) {
3957 // If the package goes over its quota during the upgrade, don't
3958 // crash but just log the error as the system does the upgrade.
3959 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3960
Svet Ganov13701552017-02-23 12:45:17 -08003961 }
3962 }
3963 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003964 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003965}