blob: 500199f7a521d32c430b3b1006ea57e47deedec4 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010067import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080068import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000069import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010071import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080072import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000073import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070076import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080077import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import com.android.internal.annotations.GuardedBy;
80import com.android.internal.content.PackageMonitor;
81import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080082import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070083import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080084import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040085
Svetoslav683914b2015-01-15 14:22:26 -080086import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080087import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080089import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080090import java.nio.ByteBuffer;
91import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070094import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000096import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000097import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080098import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100100import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800101import java.util.Set;
102import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000103
Mark Rathjen7599f132017-01-23 14:15:54 -0800104import javax.crypto.Mac;
105import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
Svetoslav Ganove080da92016-12-21 17:10:35 -0800107
Svetoslav683914b2015-01-15 14:22:26 -0800108/**
109 * <p>
110 * This class is a content provider that publishes the system settings.
111 * It can be accessed via the content provider APIs or via custom call
112 * commands. The latter is a bit faster and is the preferred way to access
113 * the platform settings.
114 * </p>
115 * <p>
116 * There are three settings types, global (with signature level protection
117 * and shared across users), secure (with signature permission level
118 * protection and per user), and system (with dangerous permission level
119 * protection and per user). Global settings are stored under the device owner.
120 * Each of these settings is represented by a {@link
121 * com.android.providers.settings.SettingsState} object mapped to an integer
122 * key derived from the setting type in the most significant bits and user
123 * id in the least significant bits. Settings are synchronously loaded on
124 * instantiation of a SettingsState and asynchronously persisted on mutation.
125 * Settings are stored in the user specific system directory.
126 * </p>
127 * <p>
128 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
129 * and get a warning. Targeting higher API version prohibits this as the
130 * system settings are not a place for apps to save their state. When a package
131 * is removed the settings it added are deleted. Apps cannot delete system
132 * settings added by the platform. System settings values are validated to
133 * ensure the clients do not put bad values. Global and secure settings are
134 * changed only by trusted parties, therefore no validation is performed. Also
135 * there is a limit on the amount of app specific settings that can be added
136 * to prevent unlimited growth of the system process memory footprint.
137 * </p>
138 */
139@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700141 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700143 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800144
145 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700146
Christopher Tate06efb532012-08-24 15:29:27 -0700147 private static final String TABLE_SYSTEM = "system";
148 private static final String TABLE_SECURE = "secure";
149 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800150
151 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final String TABLE_FAVORITES = "favorites";
153 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800154 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
155 private static final String TABLE_BOOKMARKS = "bookmarks";
156 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Svetoslav683914b2015-01-15 14:22:26 -0800158 // The set of removed legacy tables.
159 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700160 static {
Svetoslav683914b2015-01-15 14:22:26 -0800161 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
162 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
163 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
164 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
165 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
166 }
Christopher Tate06efb532012-08-24 15:29:27 -0700167
Svetoslav683914b2015-01-15 14:22:26 -0800168 private static final int MUTATION_OPERATION_INSERT = 1;
169 private static final int MUTATION_OPERATION_DELETE = 2;
170 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800171 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400172
Svetoslav683914b2015-01-15 14:22:26 -0800173 private static final String[] ALL_COLUMNS = new String[] {
174 Settings.NameValueTable._ID,
175 Settings.NameValueTable.NAME,
176 Settings.NameValueTable.VALUE
177 };
178
Makoto Onuki53f0e022017-11-29 13:51:01 -0800179 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
180 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
181 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
182 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Svet Ganov53a441c2016-04-19 19:38:00 -0700183
184 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
185 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700186
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700187 // Overlay specified settings whitelisted for Instant Apps
188 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
189 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
190 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
191
192 static {
193 for (String name : Resources.getSystem().getStringArray(
194 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
195 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
196 }
197 for (String name : Resources.getSystem().getStringArray(
198 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
199 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
200 }
201 for (String name : Resources.getSystem().getStringArray(
202 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
203 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
204 }
205 }
206
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800207 // Changes to these global settings are synchronously persisted
208 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
209 static {
210 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
211 }
212
213 // Changes to these secure settings are synchronously persisted
214 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
215 static {
216 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
217 }
218
Svetoslav683914b2015-01-15 14:22:26 -0800219 // Per user secure settings that moved to the for all users global settings.
220 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
221 static {
222 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700223 }
224
Svetoslav683914b2015-01-15 14:22:26 -0800225 // Per user system settings that moved to the for all users global settings.
226 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
227 static {
228 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229 }
230
Svetoslav683914b2015-01-15 14:22:26 -0800231 // Per user system settings that moved to the per user secure settings.
232 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
233 static {
234 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700235 }
236
Svetoslav683914b2015-01-15 14:22:26 -0800237 // Per all users global settings that moved to the per user secure settings.
238 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
239 static {
240 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700241 }
242
Svetoslav683914b2015-01-15 14:22:26 -0800243 // Per user secure settings that are cloned for the managed profiles of the user.
244 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
245 static {
246 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247 }
248
Svetoslav683914b2015-01-15 14:22:26 -0800249 // Per user system settings that are cloned for the managed profiles of the user.
250 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
251 static {
252 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400253 }
254
Andre Lago3fa139c2016-08-04 13:53:44 +0100255 // Per user system settings that are cloned from the profile's parent when a dependency
256 // in {@link Settings.Secure} is set to "1".
257 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
258 static {
259 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
260 }
261
Svetoslav683914b2015-01-15 14:22:26 -0800262 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700263
Svetoslav683914b2015-01-15 14:22:26 -0800264 @GuardedBy("mLock")
265 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700266
Svet Ganova8f90262016-05-10 08:44:48 -0700267 @GuardedBy("mLock")
268 private HandlerThread mHandlerThread;
269
Makoto Onuki73360ab2017-03-17 11:50:13 -0700270 @GuardedBy("mLock")
271 private Handler mHandler;
272
Svetoslav7ec28e82015-05-20 17:01:10 -0700273 // We have to call in the user manager with no lock held,
274 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800275
yuemingw1d13eae2018-01-30 17:27:54 +0000276 private UserManagerInternal mUserManagerInternal;
277
Svetoslav7ec28e82015-05-20 17:01:10 -0700278 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700279 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700280
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800282 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700283 }
284
285 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800286 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700287 }
288
289 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800290 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 }
292
293 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800294 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700295 }
296
297 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800298 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700299 }
300
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700301 @Override
302 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800303 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000304
305 // fail to boot if there're any backed up settings that don't have a non-null validator
306 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000307 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000308 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000309
Svetoslav683914b2015-01-15 14:22:26 -0800310 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700311 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000312 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700313 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700314 mHandlerThread = new HandlerThread(LOG_TAG,
315 Process.THREAD_PRIORITY_BACKGROUND);
316 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700317 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800318 mSettingsRegistry = new SettingsRegistry();
319 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700320 mHandler.post(() -> {
321 registerBroadcastReceivers();
322 startWatchingUserRestrictionChanges();
323 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700324 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325 return true;
326 }
327
Michal Karpinski2c37b082018-01-18 16:14:27 +0000328 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000329 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
330 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000331
332 failToBootIfOffendersPresent(offenders, "Settings.System");
333 }
334
335 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000336 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
337 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000338
339 failToBootIfOffendersPresent(offenders, "Settings.Global");
340 }
341
Michal Karpinski964943a2018-01-19 16:28:26 +0000342 private void ensureAllBackedUpSecureSettingsHaveValidators() {
343 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
344 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
345
346 failToBootIfOffendersPresent(offenders, "Settings.Secure");
347 }
348
Michal Karpinski5db1e432018-01-18 20:10:24 +0000349 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
350 if (offenders.length() > 0) {
351 throw new RuntimeException("All " + settingsType + " settings that are backed up"
352 + " have to have a non-null validator, but those don't: " + offenders);
353 }
354 }
355
356 private String getOffenders(String[] settingsToBackup, Map<String,
357 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000358 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000359 for (String setting : settingsToBackup) {
360 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000361 offenders.append(setting).append(" ");
362 }
363 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000364 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000365 }
366
Michal Karpinski964943a2018-01-19 16:28:26 +0000367 private final String[] concat(String[] first, String[] second) {
368 if (second == null || second.length == 0) {
369 return first;
370 }
371 final int firstLen = first.length;
372 final int secondLen = second.length;
373 String[] both = new String[firstLen + secondLen];
374 System.arraycopy(first, 0, both, 0, firstLen);
375 System.arraycopy(second, 0, both, firstLen, secondLen);
376 return both;
377 }
378
Svetoslav683914b2015-01-15 14:22:26 -0800379 @Override
380 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700381 final int requestingUserId = getRequestingUserId(args);
382 switch (method) {
383 case Settings.CALL_METHOD_GET_GLOBAL: {
384 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700385 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800386 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700387
388 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800389 Setting setting = getSecureSetting(name, requestingUserId,
390 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700391 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700392 }
393
394 case Settings.CALL_METHOD_GET_SYSTEM: {
395 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700396 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700397 }
398
399 case Settings.CALL_METHOD_PUT_GLOBAL: {
400 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800401 String tag = getSettingTag(args);
402 final boolean makeDefault = getSettingMakeDefault(args);
403 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700404 break;
405 }
406
407 case Settings.CALL_METHOD_PUT_SECURE: {
408 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800409 String tag = getSettingTag(args);
410 final boolean makeDefault = getSettingMakeDefault(args);
411 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700412 break;
413 }
414
415 case Settings.CALL_METHOD_PUT_SYSTEM: {
416 String value = getSettingValue(args);
417 insertSystemSetting(name, value, requestingUserId);
418 break;
419 }
420
Svetoslav Ganove080da92016-12-21 17:10:35 -0800421 case Settings.CALL_METHOD_RESET_GLOBAL: {
422 final int mode = getResetModeEnforcingPermission(args);
423 String tag = getSettingTag(args);
424 resetGlobalSetting(requestingUserId, mode, tag);
425 break;
426 }
427
428 case Settings.CALL_METHOD_RESET_SECURE: {
429 final int mode = getResetModeEnforcingPermission(args);
430 String tag = getSettingTag(args);
431 resetSecureSetting(requestingUserId, mode, tag);
432 break;
433 }
434
Svetoslav7ec28e82015-05-20 17:01:10 -0700435 default: {
436 Slog.w(LOG_TAG, "call() with invalid method: " + method);
437 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700438 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700439
Christopher Tate06efb532012-08-24 15:29:27 -0700440 return null;
441 }
442
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800443 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800444 public String getType(Uri uri) {
445 Arguments args = new Arguments(uri, null, null, true);
446 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700447 return "vnd.android.cursor.dir/" + args.table;
448 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700449 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700450 }
451 }
452
453 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800454 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
455 String order) {
456 if (DEBUG) {
457 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700458 }
459
Svetoslav683914b2015-01-15 14:22:26 -0800460 Arguments args = new Arguments(uri, where, whereArgs, true);
461 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700462
Svetoslav683914b2015-01-15 14:22:26 -0800463 // If a legacy table that is gone, done.
464 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
465 return new MatrixCursor(normalizedProjection, 0);
466 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700467
Svetoslav7ec28e82015-05-20 17:01:10 -0700468 switch (args.table) {
469 case TABLE_GLOBAL: {
470 if (args.name != null) {
471 Setting setting = getGlobalSetting(args.name);
472 return packageSettingForQuery(setting, normalizedProjection);
473 } else {
474 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700475 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700476 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700477
Svetoslav7ec28e82015-05-20 17:01:10 -0700478 case TABLE_SECURE: {
479 final int userId = UserHandle.getCallingUserId();
480 if (args.name != null) {
481 Setting setting = getSecureSetting(args.name, userId);
482 return packageSettingForQuery(setting, normalizedProjection);
483 } else {
484 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800485 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700486 }
Svetoslav683914b2015-01-15 14:22:26 -0800487
Svetoslav7ec28e82015-05-20 17:01:10 -0700488 case TABLE_SYSTEM: {
489 final int userId = UserHandle.getCallingUserId();
490 if (args.name != null) {
491 Setting setting = getSystemSetting(args.name, userId);
492 return packageSettingForQuery(setting, normalizedProjection);
493 } else {
494 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800495 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 }
Svetoslav683914b2015-01-15 14:22:26 -0800497
Svetoslav7ec28e82015-05-20 17:01:10 -0700498 default: {
499 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700500 }
501 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700502 }
503
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700504 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800505 public Uri insert(Uri uri, ContentValues values) {
506 if (DEBUG) {
507 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700508 }
509
Svetoslav683914b2015-01-15 14:22:26 -0800510 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700511
Svetoslav683914b2015-01-15 14:22:26 -0800512 // If a legacy table that is gone, done.
513 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 return null;
515 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516
Svetoslav683914b2015-01-15 14:22:26 -0800517 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700518 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800519 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700520 }
521
Svetoslav683914b2015-01-15 14:22:26 -0800522 String value = values.getAsString(Settings.Secure.VALUE);
523
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 switch (table) {
525 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800526 if (insertGlobalSetting(name, value, null, false,
527 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700528 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700529 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700530 } break;
531
532 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800533 if (insertSecureSetting(name, value, null, false,
534 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700535 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
536 }
537 } break;
538
539 case TABLE_SYSTEM: {
540 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
541 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
542 }
543 } break;
544
545 default: {
546 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700547 }
548 }
549
Svetoslav683914b2015-01-15 14:22:26 -0800550 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700551 }
552
553 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800554 public int bulkInsert(Uri uri, ContentValues[] allValues) {
555 if (DEBUG) {
556 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700558
Svetoslav683914b2015-01-15 14:22:26 -0800559 int insertionCount = 0;
560 final int valuesCount = allValues.length;
561 for (int i = 0; i < valuesCount; i++) {
562 ContentValues values = allValues[i];
563 if (insert(uri, values) != null) {
564 insertionCount++;
565 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700566 }
Svetoslav683914b2015-01-15 14:22:26 -0800567
568 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700569 }
570
571 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800572 public int delete(Uri uri, String where, String[] whereArgs) {
573 if (DEBUG) {
574 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700576
Svetoslav683914b2015-01-15 14:22:26 -0800577 Arguments args = new Arguments(uri, where, whereArgs, false);
578
579 // If a legacy table that is gone, done.
580 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
581 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700582 }
Svetoslav683914b2015-01-15 14:22:26 -0800583
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700584 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800585 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700586 }
Svetoslav683914b2015-01-15 14:22:26 -0800587
Svetoslav7ec28e82015-05-20 17:01:10 -0700588 switch (args.table) {
589 case TABLE_GLOBAL: {
590 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700591 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700592 }
Svetoslav683914b2015-01-15 14:22:26 -0800593
Svetoslav7ec28e82015-05-20 17:01:10 -0700594 case TABLE_SECURE: {
595 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700596 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700597 }
Svetoslav683914b2015-01-15 14:22:26 -0800598
Svetoslav7ec28e82015-05-20 17:01:10 -0700599 case TABLE_SYSTEM: {
600 final int userId = UserHandle.getCallingUserId();
601 return deleteSystemSetting(args.name, userId) ? 1 : 0;
602 }
603
604 default: {
605 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800606 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700607 }
Svetoslav683914b2015-01-15 14:22:26 -0800608 }
609
610 @Override
611 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
612 if (DEBUG) {
613 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700614 }
Svetoslav683914b2015-01-15 14:22:26 -0800615
616 Arguments args = new Arguments(uri, where, whereArgs, false);
617
618 // If a legacy table that is gone, done.
619 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
620 return 0;
621 }
622
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700623 String name = values.getAsString(Settings.Secure.NAME);
624 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800625 return 0;
626 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700627 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800628
Svetoslav7ec28e82015-05-20 17:01:10 -0700629 switch (args.table) {
630 case TABLE_GLOBAL: {
631 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800632 return updateGlobalSetting(args.name, value, null, false,
633 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700634 }
Svetoslav683914b2015-01-15 14:22:26 -0800635
Svetoslav7ec28e82015-05-20 17:01:10 -0700636 case TABLE_SECURE: {
637 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800638 return updateSecureSetting(args.name, value, null, false,
639 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700640 }
Svetoslav683914b2015-01-15 14:22:26 -0800641
Svetoslav7ec28e82015-05-20 17:01:10 -0700642 case TABLE_SYSTEM: {
643 final int userId = UserHandle.getCallingUserId();
644 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
645 }
Svetoslav683914b2015-01-15 14:22:26 -0800646
Svetoslav7ec28e82015-05-20 17:01:10 -0700647 default: {
648 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800649 }
650 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651 }
652
653 @Override
654 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100655 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
656 if (userId != UserHandle.getCallingUserId()) {
657 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
658 "Access files from the settings of another user");
659 }
660 uri = ContentProvider.getUriWithoutUserId(uri);
661
Andre Lago3fa139c2016-08-04 13:53:44 +0100662 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700663 final String cacheName;
664 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100665 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700666 cacheName = Settings.System.RINGTONE_CACHE;
667 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100668 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700669 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
670 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100671 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700672 cacheName = Settings.System.ALARM_ALERT_CACHE;
673 } else {
674 throw new FileNotFoundException("Direct file access no longer supported; "
675 + "ringtone playback is available through android.media.Ringtone");
676 }
677
Andre Lago3fa139c2016-08-04 13:53:44 +0100678 int actualCacheOwner;
679 // Redirect cache to parent if ringtone setting is owned by profile parent
680 synchronized (mLock) {
681 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
682 cacheRingtoneSetting);
683 }
684 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700685 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
686 }
687
688 private File getRingtoneCacheDir(int userId) {
689 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
690 cacheDir.mkdir();
691 SELinux.restorecon(cacheDir);
692 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700693 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800694
Eugene Suslad72c3972016-12-27 15:49:30 -0800695 /**
696 * Dump all settings as a proto buf.
697 *
698 * @param fd The file to dump to
699 */
700 void dumpProto(@NonNull FileDescriptor fd) {
701 ProtoOutputStream proto = new ProtoOutputStream(fd);
702
703 synchronized (mLock) {
704 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800705 }
706
707 proto.flush();
708 }
709
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700710 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800711 synchronized (mLock) {
712 final long identity = Binder.clearCallingIdentity();
713 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700714 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800715 final int userCount = users.size();
716 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700717 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800718 }
719 } finally {
720 Binder.restoreCallingIdentity(identity);
721 }
722 }
723 }
724
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700725 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700726 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800727 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700728 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
729 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700730 if (globalSettings != null) {
731 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800732 pw.println();
733 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700734 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800735 }
736
737 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700738 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
739 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700740 if (secureSettings != null) {
741 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800742 pw.println();
743 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700744 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700745
Svetoslavb505ccc2015-02-17 12:41:04 -0800746 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700747 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
748 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700749 if (systemSettings != null) {
750 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800751 pw.println();
752 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700753 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800754 }
755
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700756 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
757 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800758
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700759 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800760
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700761 for (int i = 0; i < nameCount; i++) {
762 String name = names.get(i);
763 Setting setting = settingsState.getSettingLocked(name);
764 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
765 pw.print(" name:"); pw.print(toDumpString(name));
766 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800767 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700768 }
769 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800770 if (setting.getDefaultValue() != null) {
771 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800772 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800773 }
774 if (setting.getTag() != null) {
775 pw.print(" tag:"); pw.print(setting.getTag());
776 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800777 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700778 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800779 }
780
Svetoslav7e0683b2015-08-03 16:02:52 -0700781 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700782 if (s != null) {
783 return s;
784 }
785 return "{null}";
786 }
787
Svetoslav683914b2015-01-15 14:22:26 -0800788 private void registerBroadcastReceivers() {
789 IntentFilter userFilter = new IntentFilter();
790 userFilter.addAction(Intent.ACTION_USER_REMOVED);
791 userFilter.addAction(Intent.ACTION_USER_STOPPED);
792
793 getContext().registerReceiver(new BroadcastReceiver() {
794 @Override
795 public void onReceive(Context context, Intent intent) {
796 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700797 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800798
799 switch (intent.getAction()) {
800 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700801 synchronized (mLock) {
802 mSettingsRegistry.removeUserStateLocked(userId, true);
803 }
Svetoslav683914b2015-01-15 14:22:26 -0800804 } break;
805
806 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700807 synchronized (mLock) {
808 mSettingsRegistry.removeUserStateLocked(userId, false);
809 }
Svetoslav683914b2015-01-15 14:22:26 -0800810 } break;
811 }
812 }
813 }, userFilter);
814
815 PackageMonitor monitor = new PackageMonitor() {
816 @Override
817 public void onPackageRemoved(String packageName, int uid) {
818 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100819 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800820 UserHandle.getUserId(uid));
821 }
822 }
Mark Rathjend891f012017-01-19 04:10:37 +0000823
824 @Override
825 public void onUidRemoved(int uid) {
826 synchronized (mLock) {
827 mSettingsRegistry.onUidRemovedLocked(uid);
828 }
829 }
Zimuzoc56192c2018-07-25 10:40:01 +0100830
831 @Override
832 public void onPackageDataCleared(String packageName, int uid) {
833 synchronized (mLock) {
834 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
835 UserHandle.getUserId(uid));
836 }
837 }
Svetoslav683914b2015-01-15 14:22:26 -0800838 };
839
840 // package changes
841 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
842 UserHandle.ALL, true);
843 }
844
Svet Ganov53a441c2016-04-19 19:38:00 -0700845 private void startWatchingUserRestrictionChanges() {
846 // TODO: The current design of settings looking different based on user restrictions
847 // should be reworked to keep them separate and system code should check the setting
848 // first followed by checking the user restriction before performing an operation.
849 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
850 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
851 Bundle prevRestrictions) -> {
852 // We are changing the settings affected by restrictions to their current
853 // value with a forced update to ensure that all cross profile dependencies
854 // are taken into account. Also make sure the settings update to.. the same
855 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
857 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700858 final long identity = Binder.clearCallingIdentity();
859 try {
860 synchronized (mLock) {
861 Setting setting = getSecureSetting(
862 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
863 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800864 setting != null ? setting.getValue() : null, null,
865 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700866 }
867 } finally {
868 Binder.restoreCallingIdentity(identity);
869 }
870 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800871 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
872 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700873 final long identity = Binder.clearCallingIdentity();
874 try {
875 synchronized (mLock) {
876 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800877 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700878 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800879 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700880 }
881 } finally {
882 Binder.restoreCallingIdentity(identity);
883 }
884 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800885 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
886 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700887 final long identity = Binder.clearCallingIdentity();
888 try {
889 synchronized (mLock) {
890 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800891 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700892 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800893 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700894 }
895 } finally {
896 Binder.restoreCallingIdentity(identity);
897 }
898 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800899 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
900 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700901 final long identity = Binder.clearCallingIdentity();
902 try {
903 synchronized (mLock) {
904 Setting enable = getGlobalSetting(
905 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800906 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700907 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800908 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700909 Setting include = getGlobalSetting(
910 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700912 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800913 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700914 }
915 } finally {
916 Binder.restoreCallingIdentity(identity);
917 }
918 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800919 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
920 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700921 final long identity = Binder.clearCallingIdentity();
922 try {
923 synchronized (mLock) {
924 Setting setting = getGlobalSetting(
925 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800926 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700927 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800928 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700929 }
930 } finally {
931 Binder.restoreCallingIdentity(identity);
932 }
933 }
934 });
935 }
936
Svetoslav7ec28e82015-05-20 17:01:10 -0700937 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800938 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700939 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800940 }
941
Svetoslav7ec28e82015-05-20 17:01:10 -0700942 synchronized (mLock) {
943 // Get the settings.
944 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700945 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800946
Chad Brubaker97bccee2017-01-05 15:51:41 -0800947 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
948 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800949
Svetoslav7ec28e82015-05-20 17:01:10 -0700950 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800951
Svetoslav7ec28e82015-05-20 17:01:10 -0700952 String[] normalizedProjection = normalizeProjection(projection);
953 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800954
Svetoslav7ec28e82015-05-20 17:01:10 -0700955 // Anyone can get the global settings, so no security checks.
956 for (int i = 0; i < nameCount; i++) {
957 String name = names.get(i);
958 Setting setting = settingsState.getSettingLocked(name);
959 appendSettingToCursor(result, setting);
960 }
961
962 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800963 }
Svetoslav683914b2015-01-15 14:22:26 -0800964 }
965
Svetoslav7ec28e82015-05-20 17:01:10 -0700966 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800967 if (DEBUG) {
968 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
969 }
970
Chad Brubakera6830e72017-04-28 17:34:36 -0700971 // Ensure the caller can access the setting.
972 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
973
Svetoslav683914b2015-01-15 14:22:26 -0800974 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700975 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700976 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700977 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800978 }
Svetoslav683914b2015-01-15 14:22:26 -0800979 }
980
Svetoslav Ganove080da92016-12-21 17:10:35 -0800981 private boolean updateGlobalSetting(String name, String value, String tag,
982 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800983 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800984 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
985 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
986 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800987 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800988 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
989 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800990 }
991
Svetoslav Ganove080da92016-12-21 17:10:35 -0800992 private boolean insertGlobalSetting(String name, String value, String tag,
993 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700994 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800995 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
996 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
997 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700998 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800999 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1000 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001001 }
1002
Svet Ganov53a441c2016-04-19 19:38:00 -07001003 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001004 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001005 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1006 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001007 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001008 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1009 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001010 }
1011
Svetoslav Ganove080da92016-12-21 17:10:35 -08001012 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1013 if (DEBUG) {
1014 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1015 + mode + ", " + tag + ")");
1016 }
1017 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1018 MUTATION_OPERATION_RESET, false, mode);
1019 }
1020
1021 private boolean mutateGlobalSetting(String name, String value, String tag,
1022 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1023 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001024 // Make sure the caller can change the settings - treated as secure.
1025 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1026
Svetoslav683914b2015-01-15 14:22:26 -08001027 // Resolve the userId on whose behalf the call is made.
1028 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1029
Makoto Onuki28da2e32015-11-20 11:30:44 -08001030 // If this is a setting that is currently restricted for this user, do not allow
1031 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001032 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1033 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001034 return false;
1035 }
1036
1037 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 synchronized (mLock) {
1039 switch (operation) {
1040 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001041 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1042 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001043 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001044 }
Svetoslav683914b2015-01-15 14:22:26 -08001045
Svetoslav7ec28e82015-05-20 17:01:10 -07001046 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001047 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001048 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001049 }
Svetoslav683914b2015-01-15 14:22:26 -08001050
Svetoslav7ec28e82015-05-20 17:01:10 -07001051 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001052 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1053 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001054 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001055 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001056
1057 case MUTATION_OPERATION_RESET: {
1058 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1059 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1060 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001061 }
1062 }
1063
1064 return false;
1065 }
1066
Christopher Tateb218e762017-04-05 16:34:07 -07001067 private PackageInfo getCallingPackageInfo(int userId) {
1068 try {
1069 return mPackageManager.getPackageInfo(getCallingPackage(),
1070 PackageManager.GET_SIGNATURES, userId);
1071 } catch (RemoteException e) {
1072 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1073 }
1074 }
1075
Svetoslav7ec28e82015-05-20 17:01:10 -07001076 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001077 if (DEBUG) {
1078 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1079 }
1080
1081 // Resolve the userId on whose behalf the call is made.
1082 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1083
Christopher Tateb218e762017-04-05 16:34:07 -07001084 // The relevant "calling package" userId will be the owning userId for some
1085 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1086 // up front who the effective "new SSAID" user ID for that settings name will be.
1087 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1088 Settings.Secure.ANDROID_ID);
1089 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1090
Svetoslav7ec28e82015-05-20 17:01:10 -07001091 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001092 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001093
Svetoslav7ec28e82015-05-20 17:01:10 -07001094 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001095
Svetoslav7ec28e82015-05-20 17:01:10 -07001096 String[] normalizedProjection = normalizeProjection(projection);
1097 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001098
Svetoslav7ec28e82015-05-20 17:01:10 -07001099 for (int i = 0; i < nameCount; i++) {
1100 String name = names.get(i);
1101 // Determine the owning user as some profile settings are cloned from the parent.
1102 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1103 name);
Svetoslav683914b2015-01-15 14:22:26 -08001104
Alex Klyubin1991f572017-03-03 14:08:36 -08001105 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1106 // This caller is not permitted to access this setting. Pretend the setting
1107 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001108 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001109 }
Svetoslav683914b2015-01-15 14:22:26 -08001110
Mark Rathjen7599f132017-01-23 14:15:54 -08001111 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001112 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1113 final Setting setting;
1114 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001115 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001116 } else {
1117 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1118 name);
1119 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001120 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001121 }
1122
Svetoslav7ec28e82015-05-20 17:01:10 -07001123 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001124 }
Svetoslav683914b2015-01-15 14:22:26 -08001125 }
1126
Svetoslav7ec28e82015-05-20 17:01:10 -07001127 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001128 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1129 }
1130
1131 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001132 if (DEBUG) {
1133 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1134 }
1135
1136 // Resolve the userId on whose behalf the call is made.
1137 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1138
Chad Brubakera6830e72017-04-28 17:34:36 -07001139 // Ensure the caller can access the setting.
1140 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1141
Svetoslav683914b2015-01-15 14:22:26 -08001142 // Determine the owning user as some profile settings are cloned from the parent.
1143 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1144
Alex Klyubin1991f572017-03-03 14:08:36 -08001145 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1146 // This caller is not permitted to access this setting. Pretend the setting doesn't
1147 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001148 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1149 owningUserId);
1150 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001151 }
1152
Christopher Tateb218e762017-04-05 16:34:07 -07001153 // As of Android O, the SSAID is read from an app-specific entry in table
1154 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1155 if (isNewSsaidSetting(name)) {
1156 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1157 synchronized (mLock) {
1158 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001159 }
Christopher Tateb218e762017-04-05 16:34:07 -07001160 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001161 if (enableOverride) {
1162 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1163 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1164 if (overridden != null) {
1165 return overridden;
1166 }
1167 }
1168 }
Mark Rathjend891f012017-01-19 04:10:37 +00001169
Christopher Tateb218e762017-04-05 16:34:07 -07001170 // Not the SSAID; do a straight lookup
1171 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001172 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001173 owningUserId, name);
1174 }
Svetoslav683914b2015-01-15 14:22:26 -08001175 }
1176
Mark Rathjend891f012017-01-19 04:10:37 +00001177 private boolean isNewSsaidSetting(String name) {
1178 return Settings.Secure.ANDROID_ID.equals(name)
1179 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1180 }
1181
Christopher Tateb218e762017-04-05 16:34:07 -07001182 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001183 // Get uid of caller (key) used to store ssaid value
1184 String name = Integer.toString(
1185 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1186
1187 if (DEBUG) {
1188 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1189 }
1190
1191 // Retrieve the ssaid from the table if present.
1192 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1193 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001194 // If the app is an Instant App use its stored SSAID instead of our own.
1195 final String instantSsaid;
1196 final long token = Binder.clearCallingIdentity();
1197 try {
1198 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1199 owningUserId);
1200 } catch (RemoteException e) {
1201 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1202 return null;
1203 } finally {
1204 Binder.restoreCallingIdentity(token);
1205 }
Svet Ganov96c99462017-05-05 14:27:13 -07001206
1207 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1208 SETTINGS_TYPE_SSAID, owningUserId);
1209
Chad Brubaker0d277a72017-04-12 16:56:53 -07001210 if (instantSsaid != null) {
1211 // Use the stored value if it is still valid.
1212 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001213 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001214 }
1215 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001216 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1217 true, callingPkg.packageName);
1218 if (!success) {
1219 throw new IllegalStateException("Failed to update instant app android id");
1220 }
Svet Ganov96c99462017-05-05 14:27:13 -07001221 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1222 owningUserId, name);
1223 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001224 }
Mark Rathjend891f012017-01-19 04:10:37 +00001225
1226 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001227 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001228 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1229 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001230 }
1231
Svet Ganov96c99462017-05-05 14:27:13 -07001232 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1233 }
1234
1235 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1236 // SSAID settings are located in a dedicated table for internal bookkeeping
1237 // but for the world they reside in the secure table, so adjust the key here.
1238 // We have a special name when looking it up but want the world to see it as
1239 // "android_id".
1240 if (ssaidSetting != null) {
1241 return settingsState.new Setting(ssaidSetting) {
1242 @Override
1243 public int getKey() {
1244 final int userId = getUserIdFromKey(super.getKey());
1245 return makeKey(SETTINGS_TYPE_SECURE, userId);
1246 }
1247
1248 @Override
1249 public String getName() {
1250 return Settings.Secure.ANDROID_ID;
1251 }
1252 };
1253 }
1254 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001255 }
1256
Makoto Onuki0000d322017-11-28 16:31:47 -08001257 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1258 synchronized (mLock) {
1259 final Setting setting = getGlobalSetting(
1260 Global.LOCATION_GLOBAL_KILL_SWITCH);
1261 if (!"1".equals(setting.getValue())) {
1262 return null;
1263 }
1264 // Global kill-switch is enabled. Return an empty value.
1265 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1266 SETTINGS_TYPE_SECURE, owningUserId);
1267 return settingsState.new Setting(
1268 Secure.LOCATION_PROVIDERS_ALLOWED,
1269 "", // value
1270 "", // tag
1271 "", // default value
1272 "", // package name
1273 false, // from system
1274 "0" // id
1275 ) {
1276 @Override
1277 public boolean update(String value, boolean setDefault, String packageName,
1278 String tag, boolean forceNonSystemPackage) {
1279 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1280 return false;
1281 }
1282 };
1283 }
1284 }
1285
Svetoslav Ganove080da92016-12-21 17:10:35 -08001286 private boolean insertSecureSetting(String name, String value, String tag,
1287 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001288 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001289 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001290 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1291 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001292 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001293 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1294 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001295 }
1296
Svet Ganov53a441c2016-04-19 19:38:00 -07001297 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001298 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001299 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1300 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001301 }
1302
Svetoslav Ganove080da92016-12-21 17:10:35 -08001303 return mutateSecureSetting(name, null, null, false, requestingUserId,
1304 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001305 }
1306
Svetoslav Ganove080da92016-12-21 17:10:35 -08001307 private boolean updateSecureSetting(String name, String value, String tag,
1308 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001309 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001310 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001311 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1312 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001313 }
1314
Svetoslav Ganove080da92016-12-21 17:10:35 -08001315 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1316 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001317 }
1318
Svetoslav Ganove080da92016-12-21 17:10:35 -08001319 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1320 if (DEBUG) {
1321 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1322 + mode + ", " + tag + ")");
1323 }
1324
1325 mutateSecureSetting(null, null, tag, false, requestingUserId,
1326 MUTATION_OPERATION_RESET, false, mode);
1327 }
1328
1329 private boolean mutateSecureSetting(String name, String value, String tag,
1330 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1331 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001332 // Make sure the caller can change the settings.
1333 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1334
Svetoslav683914b2015-01-15 14:22:26 -08001335 // Resolve the userId on whose behalf the call is made.
1336 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1337
Makoto Onuki28da2e32015-11-20 11:30:44 -08001338 // If this is a setting that is currently restricted for this user, do not allow
1339 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001340 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1341 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001342 return false;
1343 }
1344
1345 // Determine the owning user as some profile settings are cloned from the parent.
1346 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1347
1348 // Only the owning user can change the setting.
1349 if (owningUserId != callingUserId) {
1350 return false;
1351 }
1352
1353 // Special cases for location providers (sigh).
1354 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001355 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1356 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001357 }
1358
1359 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001360 synchronized (mLock) {
1361 switch (operation) {
1362 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001363 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001364 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001365 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001366 }
Svetoslav683914b2015-01-15 14:22:26 -08001367
Svetoslav7ec28e82015-05-20 17:01:10 -07001368 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001369 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001370 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001371 }
Svetoslav683914b2015-01-15 14:22:26 -08001372
Svetoslav7ec28e82015-05-20 17:01:10 -07001373 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001374 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001375 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001376 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001377 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001378
1379 case MUTATION_OPERATION_RESET: {
1380 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1381 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1382 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001383 }
1384 }
1385
1386 return false;
1387 }
1388
Svetoslav7ec28e82015-05-20 17:01:10 -07001389 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001390 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001391 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001392 }
1393
1394 // Resolve the userId on whose behalf the call is made.
1395 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1396
Svetoslav7ec28e82015-05-20 17:01:10 -07001397 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001398 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001399
Svetoslav7ec28e82015-05-20 17:01:10 -07001400 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001401
Svetoslav7ec28e82015-05-20 17:01:10 -07001402 String[] normalizedProjection = normalizeProjection(projection);
1403 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001404
Svetoslav7ec28e82015-05-20 17:01:10 -07001405 for (int i = 0; i < nameCount; i++) {
1406 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001407
Svetoslav7ec28e82015-05-20 17:01:10 -07001408 // Determine the owning user as some profile settings are cloned from the parent.
1409 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1410 name);
Svetoslav683914b2015-01-15 14:22:26 -08001411
Svetoslav7ec28e82015-05-20 17:01:10 -07001412 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001413 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001414 appendSettingToCursor(result, setting);
1415 }
1416
1417 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001418 }
Svetoslav683914b2015-01-15 14:22:26 -08001419 }
1420
Svetoslav7ec28e82015-05-20 17:01:10 -07001421 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001422 if (DEBUG) {
1423 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1424 }
1425
1426 // Resolve the userId on whose behalf the call is made.
1427 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1428
Chad Brubakera6830e72017-04-28 17:34:36 -07001429 // Ensure the caller can access the setting.
1430 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001431
Svetoslav683914b2015-01-15 14:22:26 -08001432 // Determine the owning user as some profile settings are cloned from the parent.
1433 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1434
1435 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001436 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001437 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001438 }
Svetoslav683914b2015-01-15 14:22:26 -08001439 }
1440
Svetoslav7ec28e82015-05-20 17:01:10 -07001441 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001442 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001443 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001444 + requestingUserId + ")");
1445 }
1446
Svetoslav7ec28e82015-05-20 17:01:10 -07001447 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001448 }
1449
Svetoslav7ec28e82015-05-20 17:01:10 -07001450 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001451 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001452 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001453 }
1454
Svetoslav7ec28e82015-05-20 17:01:10 -07001455 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001456 }
1457
Svetoslav7ec28e82015-05-20 17:01:10 -07001458 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001459 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001460 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001461 + requestingUserId + ")");
1462 }
1463
Svetoslav7ec28e82015-05-20 17:01:10 -07001464 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001465 }
1466
Svetoslav7ec28e82015-05-20 17:01:10 -07001467 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001468 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001469 if (!hasWriteSecureSettingsPermission()) {
1470 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1471 // operation is allowed for the calling package through appops.
1472 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1473 Binder.getCallingUid(), getCallingPackage(), true)) {
1474 return false;
1475 }
Svetoslav683914b2015-01-15 14:22:26 -08001476 }
1477
Svetoslav683914b2015-01-15 14:22:26 -08001478 // Resolve the userId on whose behalf the call is made.
1479 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1480
yuemingw1d13eae2018-01-30 17:27:54 +00001481 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1482 name, callingUserId, value, Binder.getCallingUid())) {
1483 return false;
1484 }
1485
Svetoslavd8d25e02015-11-20 13:09:26 -08001486 // Enforce what the calling package can mutate the system settings.
1487 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1488
Svetoslav683914b2015-01-15 14:22:26 -08001489 // Determine the owning user as some profile settings are cloned from the parent.
1490 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1491
1492 // Only the owning user id can change the setting.
1493 if (owningUserId != callingUserId) {
1494 return false;
1495 }
1496
Jeff Sharkey413573a2016-02-22 17:52:45 -07001497 // Invalidate any relevant cache files
1498 String cacheName = null;
1499 if (Settings.System.RINGTONE.equals(name)) {
1500 cacheName = Settings.System.RINGTONE_CACHE;
1501 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1502 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1503 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1504 cacheName = Settings.System.ALARM_ALERT_CACHE;
1505 }
1506 if (cacheName != null) {
1507 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001508 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001509 cacheFile.delete();
1510 }
1511
Svetoslav683914b2015-01-15 14:22:26 -08001512 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001513 synchronized (mLock) {
1514 switch (operation) {
1515 case MUTATION_OPERATION_INSERT: {
1516 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001517 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001518 owningUserId, name, value, null, false, getCallingPackage(),
1519 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001520 }
1521
1522 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001523 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001524 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001525 }
1526
1527 case MUTATION_OPERATION_UPDATE: {
1528 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001529 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001530 owningUserId, name, value, null, false, getCallingPackage(),
1531 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001532 }
Svetoslav683914b2015-01-15 14:22:26 -08001533 }
1534
Svetoslav7ec28e82015-05-20 17:01:10 -07001535 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001536 }
Svetoslav683914b2015-01-15 14:22:26 -08001537 }
1538
Billy Lau6ad2d662015-07-18 00:26:58 +01001539 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001540 // Write secure settings is a more protected permission. If caller has it we are good.
1541 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1542 == PackageManager.PERMISSION_GRANTED) {
1543 return true;
1544 }
1545
Svetoslavf41334b2015-06-23 12:06:03 -07001546 return false;
1547 }
1548
Svetoslav683914b2015-01-15 14:22:26 -08001549 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001550 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001551 if (validator != null && !validator.validate(value)) {
1552 throw new IllegalArgumentException("Invalid value: " + value
1553 + " for setting: " + name);
1554 }
1555 }
1556
Alex Klyubin1991f572017-03-03 14:08:36 -08001557 /**
1558 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1559 */
1560 private boolean isSecureSettingAccessible(String name, int callingUserId,
1561 int owningUserId) {
1562 // Special case for location (sigh).
1563 // This check is not inside the name-based checks below because this method performs checks
1564 // only if the calling user ID is not the same as the owning user ID.
1565 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1566 return false;
1567 }
1568
1569 switch (name) {
1570 case "bluetooth_address":
1571 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1572 // address in this secure setting. Secure settings can normally be read by any app,
1573 // which thus enables them to bypass the recently introduced restrictions on access
1574 // to device identifiers.
1575 // To mitigate this we make this setting available only to callers privileged to see
1576 // this device's MAC addresses, same as through public API
1577 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1578 return getContext().checkCallingOrSelfPermission(
1579 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1580 default:
1581 return true;
1582 }
1583 }
1584
Svetoslav683914b2015-01-15 14:22:26 -08001585 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1586 int owningUserId) {
1587 // Optimization - location providers are restricted only for managed profiles.
1588 if (callingUserId == owningUserId) {
1589 return false;
1590 }
1591 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1592 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1593 new UserHandle(callingUserId))) {
1594 return true;
1595 }
1596 return false;
1597 }
1598
Svetoslav683914b2015-01-15 14:22:26 -08001599 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1600 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1601 }
1602
1603 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001604 final int parentId;
1605 // Resolves dependency if setting has a dependency and the calling user has a parent
1606 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1607 && (parentId = getGroupParentLocked(userId)) != userId) {
1608 // The setting has a dependency and the profile has a parent
1609 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001610 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1611 final long token = Binder.clearCallingIdentity();
1612 try {
1613 Setting settingObj = getSecureSetting(dependency, userId);
1614 if (settingObj != null && settingObj.getValue().equals("1")) {
1615 return parentId;
1616 }
1617 } finally {
1618 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001619 }
1620 }
Svetoslav683914b2015-01-15 14:22:26 -08001621 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1622 }
1623
1624 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1625 final int parentId = getGroupParentLocked(userId);
1626 if (parentId != userId && keys.contains(name)) {
1627 return parentId;
1628 }
1629 return userId;
1630 }
1631
Svetoslavf41334b2015-06-23 12:06:03 -07001632 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001633 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001634 // System/root/shell can mutate whatever secure settings they want.
1635 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001636 final int appId = UserHandle.getAppId(callingUid);
1637 if (appId == android.os.Process.SYSTEM_UID
1638 || appId == Process.SHELL_UID
1639 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001640 return;
1641 }
1642
1643 switch (operation) {
1644 case MUTATION_OPERATION_INSERT:
1645 // Insert updates.
1646 case MUTATION_OPERATION_UPDATE: {
1647 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1648 return;
1649 }
1650
1651 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001652 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001653
1654 // Privileged apps can do whatever they want.
1655 if ((packageInfo.applicationInfo.privateFlags
1656 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1657 return;
1658 }
1659
1660 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1661 packageInfo.applicationInfo.targetSdkVersion, name);
1662 } break;
1663
1664 case MUTATION_OPERATION_DELETE: {
1665 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1666 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1667 throw new IllegalArgumentException("You cannot delete system defined"
1668 + " secure settings.");
1669 }
1670
1671 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001672 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001673
1674 // Privileged apps can do whatever they want.
1675 if ((packageInfo.applicationInfo.privateFlags &
1676 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1677 return;
1678 }
1679
1680 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1681 packageInfo.applicationInfo.targetSdkVersion, name);
1682 } break;
1683 }
1684 }
1685
Todd Kennedybe0b8892017-02-15 14:13:52 -08001686 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001687 switch (settingsType) {
1688 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001689 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001690 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001691 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001692 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001693 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001694 default:
1695 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1696 }
1697 }
1698
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001699 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1700 switch (settingsType) {
1701 case SETTINGS_TYPE_GLOBAL:
1702 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1703 case SETTINGS_TYPE_SYSTEM:
1704 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1705 case SETTINGS_TYPE_SECURE:
1706 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1707 default:
1708 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1709 }
1710 }
1711
Chad Brubaker97bccee2017-01-05 15:51:41 -08001712 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001713 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1714 // in the current form.
1715 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001716 }
1717
Chad Brubakera6830e72017-04-28 17:34:36 -07001718 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001719 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1720 return;
1721 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001722 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001723 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001724 return;
1725 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001726 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1727 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001728 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1729 // breakage in the current form.
1730 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1731 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001732 }
1733 }
1734
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001735 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1736 // We always use the callingUid for this lookup. This means that if hypothetically an
1737 // app was installed in user A with cross user and in user B as an Instant App
1738 // the app in A would be able to see all the settings in user B. However since cross
1739 // user is a system permission and the app must be uninstalled in B and then installed as
1740 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001741 ApplicationInfo ai = null;
1742 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001743 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1744 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001745 } catch (RemoteException ignored) {
1746 }
1747 if (ai == null) {
1748 throw new IllegalStateException("Failed to lookup info for package "
1749 + getCallingPackage());
1750 }
1751 return ai;
1752 }
1753
Xiaohui Chen43765b72015-08-31 10:57:33 -07001754 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001755 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001756 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1757 getCallingPackage(), 0, userId);
1758 if (packageInfo != null) {
1759 return packageInfo;
1760 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001761 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001762 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001763 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001764 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001765 }
1766
1767 private int getGroupParentLocked(int userId) {
1768 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001769 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001770 return userId;
1771 }
1772 // We are in the same process with the user manager and the returned
1773 // user info is a cached instance, so just look up instead of cache.
1774 final long identity = Binder.clearCallingIdentity();
1775 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001776 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001777 UserInfo userInfo = mUserManager.getProfileParent(userId);
1778 return (userInfo != null) ? userInfo.id : userId;
1779 } finally {
1780 Binder.restoreCallingIdentity(identity);
1781 }
1782 }
1783
Svetoslav683914b2015-01-15 14:22:26 -08001784 private void enforceWritePermission(String permission) {
1785 if (getContext().checkCallingOrSelfPermission(permission)
1786 != PackageManager.PERMISSION_GRANTED) {
1787 throw new SecurityException("Permission denial: writing to settings requires:"
1788 + permission);
1789 }
1790 }
1791
1792 /*
1793 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1794 * This setting contains a list of the currently enabled location providers.
1795 * But helper functions in android.providers.Settings can enable or disable
1796 * a single provider by using a "+" or "-" prefix before the provider name.
1797 *
yuemingw1d13eae2018-01-30 17:27:54 +00001798 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1799 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1800 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001801 *
Svetoslav683914b2015-01-15 14:22:26 -08001802 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001803 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001804 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1805 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001806 if (TextUtils.isEmpty(value)) {
1807 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001808 }
Maggie83e03f52018-03-16 12:22:20 -07001809 Setting oldSetting = getSecureSetting(
1810 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1811 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001812 return false;
1813 }
Maggie83e03f52018-03-16 12:22:20 -07001814 String oldProviders = oldSetting.getValue();
1815 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1816 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1817 Set<String> newProvidersSet = new ArraySet<>();
1818 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08001819
Maggie83e03f52018-03-16 12:22:20 -07001820 String[] providerUpdates = value.split(",");
1821 boolean inputError = false;
1822 for (String provider : providerUpdates) {
1823 // do not update location_providers_allowed when input is invalid
1824 if (TextUtils.isEmpty(provider)) {
1825 inputError = true;
1826 break;
Svetoslav683914b2015-01-15 14:22:26 -08001827 }
Maggie83e03f52018-03-16 12:22:20 -07001828 final char prefix = provider.charAt(0);
1829 // do not update location_providers_allowed when input is invalid
1830 if (prefix != '+' && prefix != '-') {
1831 inputError = true;
1832 break;
Svetoslav683914b2015-01-15 14:22:26 -08001833 }
Maggie83e03f52018-03-16 12:22:20 -07001834 // skip prefix
1835 provider = provider.substring(1);
1836 if (prefix == '+') {
1837 newProvidersSet.add(provider);
1838 } else if (prefix == '-') {
1839 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08001840 }
Maggie83e03f52018-03-16 12:22:20 -07001841 }
1842 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
1843 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08001844 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001845 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07001846 mSettingsRegistry.notifyForSettingsChange(
1847 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07001848 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1849 }
Svetoslav683914b2015-01-15 14:22:26 -08001850 return false;
1851 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001852 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07001853 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
1854 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001855 }
1856
Svetoslav683914b2015-01-15 14:22:26 -08001857 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1858 int targetSdkVersion, String name) {
1859 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1860 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1861 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1862 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1863 + " This will soon become an error.");
1864 } else {
1865 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1866 + " This will soon become an error.");
1867 }
1868 } else {
1869 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1870 throw new IllegalArgumentException("You cannot change private secure settings.");
1871 } else {
1872 throw new IllegalArgumentException("You cannot keep your settings in"
1873 + " the secure settings.");
1874 }
1875 }
1876 }
1877
1878 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1879 if (requestingUserId == UserHandle.getCallingUserId()) {
1880 return requestingUserId;
1881 }
1882 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1883 Binder.getCallingUid(), requestingUserId, false, true,
1884 "get/set setting for user", null);
1885 }
1886
Svet Ganov53a441c2016-04-19 19:38:00 -07001887 private Bundle packageValueForCallResult(Setting setting,
1888 boolean trackingGeneration) {
1889 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001890 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001891 return NULL_SETTING_BUNDLE;
1892 }
1893 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001894 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001895 Bundle result = new Bundle();
1896 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001897 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001898
Svetoslav Ganove080da92016-12-21 17:10:35 -08001899 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001900 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001901 }
1902
1903 private static int getRequestingUserId(Bundle args) {
1904 final int callingUserId = UserHandle.getCallingUserId();
1905 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1906 : callingUserId;
1907 }
1908
Svet Ganov53a441c2016-04-19 19:38:00 -07001909 private boolean isTrackingGeneration(Bundle args) {
1910 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1911 }
1912
Svetoslav683914b2015-01-15 14:22:26 -08001913 private static String getSettingValue(Bundle args) {
1914 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1915 }
1916
Svetoslav Ganove080da92016-12-21 17:10:35 -08001917 private static String getSettingTag(Bundle args) {
1918 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1919 }
1920
1921 private static boolean getSettingMakeDefault(Bundle args) {
1922 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1923 }
1924
1925 private static int getResetModeEnforcingPermission(Bundle args) {
1926 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1927 switch (mode) {
1928 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1929 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1930 throw new SecurityException("Only system, shell/root on a "
1931 + "debuggable build can reset to untrusted defaults");
1932 }
1933 return mode;
1934 }
1935 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1936 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1937 throw new SecurityException("Only system, shell/root on a "
1938 + "debuggable build can reset untrusted changes");
1939 }
1940 return mode;
1941 }
1942 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1943 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1944 throw new SecurityException("Only system, shell/root on a "
1945 + "debuggable build can reset to trusted defaults");
1946 }
1947 return mode;
1948 }
1949 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1950 return mode;
1951 }
1952 }
1953 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1954 }
1955
1956 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1957 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1958 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1959 && (appId == SHELL_UID || appId == ROOT_UID));
1960 }
1961
Svetoslav683914b2015-01-15 14:22:26 -08001962 private static String getValidTableOrThrow(Uri uri) {
1963 if (uri.getPathSegments().size() > 0) {
1964 String table = uri.getPathSegments().get(0);
1965 if (DatabaseHelper.isValidTable(table)) {
1966 return table;
1967 }
1968 throw new IllegalArgumentException("Bad root path: " + table);
1969 }
1970 throw new IllegalArgumentException("Invalid URI:" + uri);
1971 }
1972
1973 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001974 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001975 return new MatrixCursor(projection, 0);
1976 }
1977 MatrixCursor cursor = new MatrixCursor(projection, 1);
1978 appendSettingToCursor(cursor, setting);
1979 return cursor;
1980 }
1981
1982 private static String[] normalizeProjection(String[] projection) {
1983 if (projection == null) {
1984 return ALL_COLUMNS;
1985 }
1986
1987 final int columnCount = projection.length;
1988 for (int i = 0; i < columnCount; i++) {
1989 String column = projection[i];
1990 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1991 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001992 }
1993 }
1994
Svetoslav683914b2015-01-15 14:22:26 -08001995 return projection;
1996 }
1997
1998 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001999 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002000 return;
2001 }
Svetoslav683914b2015-01-15 14:22:26 -08002002 final int columnCount = cursor.getColumnCount();
2003
2004 String[] values = new String[columnCount];
2005
2006 for (int i = 0; i < columnCount; i++) {
2007 String column = cursor.getColumnName(i);
2008
2009 switch (column) {
2010 case Settings.NameValueTable._ID: {
2011 values[i] = setting.getId();
2012 } break;
2013
2014 case Settings.NameValueTable.NAME: {
2015 values[i] = setting.getName();
2016 } break;
2017
2018 case Settings.NameValueTable.VALUE: {
2019 values[i] = setting.getValue();
2020 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002021 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002022 }
2023
Svetoslav683914b2015-01-15 14:22:26 -08002024 cursor.addRow(values);
2025 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002026
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002027 private static boolean isKeyValid(String key) {
2028 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2029 }
2030
Svetoslav683914b2015-01-15 14:22:26 -08002031 private static final class Arguments {
2032 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2033 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2034
2035 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2036 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2037
2038 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2039 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2040
2041 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2042 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2043
2044 public final String table;
2045 public final String name;
2046
2047 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2048 final int segmentSize = uri.getPathSegments().size();
2049 switch (segmentSize) {
2050 case 1: {
2051 if (where != null
2052 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2053 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2054 && whereArgs.length == 1) {
2055 name = whereArgs[0];
2056 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002057 return;
Svetoslav683914b2015-01-15 14:22:26 -08002058 } else if (where != null
2059 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2060 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2061 final int startIndex = Math.max(where.indexOf("'"),
2062 where.indexOf("\"")) + 1;
2063 final int endIndex = Math.max(where.lastIndexOf("'"),
2064 where.lastIndexOf("\""));
2065 name = where.substring(startIndex, endIndex);
2066 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002067 return;
Svetoslav683914b2015-01-15 14:22:26 -08002068 } else if (supportAll && where == null && whereArgs == null) {
2069 name = null;
2070 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002071 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002072 }
Svetoslav683914b2015-01-15 14:22:26 -08002073 } break;
2074
Svetoslav28494652015-02-12 14:11:42 -08002075 case 2: {
2076 if (where == null && whereArgs == null) {
2077 name = uri.getPathSegments().get(1);
2078 table = computeTableForSetting(uri, name);
2079 return;
2080 }
2081 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002082 }
Svetoslav28494652015-02-12 14:11:42 -08002083
2084 EventLogTags.writeUnsupportedSettingsQuery(
2085 uri.toSafeString(), where, Arrays.toString(whereArgs));
2086 String message = String.format( "Supported SQL:\n"
2087 + " uri content://some_table/some_property with null where and where args\n"
2088 + " uri content://some_table with query name=? and single name as arg\n"
2089 + " uri content://some_table with query name=some_name and null args\n"
2090 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2091 Arrays.toString(whereArgs));
2092 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002093 }
2094
Svetoslav28494652015-02-12 14:11:42 -08002095 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002096 String table = getValidTableOrThrow(uri);
2097
2098 if (name != null) {
2099 if (sSystemMovedToSecureSettings.contains(name)) {
2100 table = TABLE_SECURE;
2101 }
2102
2103 if (sSystemMovedToGlobalSettings.contains(name)) {
2104 table = TABLE_GLOBAL;
2105 }
2106
2107 if (sSecureMovedToGlobalSettings.contains(name)) {
2108 table = TABLE_GLOBAL;
2109 }
2110
2111 if (sGlobalMovedToSecureSettings.contains(name)) {
2112 table = TABLE_SECURE;
2113 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002114 }
Svetoslav683914b2015-01-15 14:22:26 -08002115
2116 return table;
2117 }
2118 }
2119
2120 final class SettingsRegistry {
2121 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2122
Svetoslav683914b2015-01-15 14:22:26 -08002123 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2124 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2125 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002126 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2127
2128 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002129
2130 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2131
Svet Ganov53a441c2016-04-19 19:38:00 -07002132 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002133
Svetoslav7e0683b2015-08-03 16:02:52 -07002134 private final Handler mHandler;
2135
Svet Ganov53a441c2016-04-19 19:38:00 -07002136 private final BackupManager mBackupManager;
2137
Amith Yamasani39452022017-03-21 15:23:47 -07002138 private String mSettingsCreationBuildId;
2139
Svetoslav683914b2015-01-15 14:22:26 -08002140 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002141 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002142 mGenerationRegistry = new GenerationRegistry(mLock);
2143 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002144 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002145 syncSsaidTableOnStart();
2146 }
2147
2148 private void generateUserKeyLocked(int userId) {
2149 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002150 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002151 final SecureRandom rand = new SecureRandom();
2152 rand.nextBytes(keyBytes);
2153
2154 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002155 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002156
2157 // Store the key in the ssaid table.
2158 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2159 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2160 true, SettingsState.SYSTEM_PACKAGE_NAME);
2161
2162 if (!success) {
2163 throw new IllegalStateException("Ssaid settings not accessible");
2164 }
2165 }
2166
Mark Rathjen7599f132017-01-23 14:15:54 -08002167 private byte[] getLengthPrefix(byte[] data) {
2168 return ByteBuffer.allocate(4).putInt(data.length).array();
2169 }
2170
Christopher Tateb218e762017-04-05 16:34:07 -07002171 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002172 // Read the user's key from the ssaid table.
2173 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002174 if (userKeySetting == null || userKeySetting.isNull()
2175 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002176 // Lazy initialize and store the user key.
2177 generateUserKeyLocked(userId);
2178 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002179 if (userKeySetting == null || userKeySetting.isNull()
2180 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002181 throw new IllegalStateException("User key not accessible");
2182 }
2183 }
2184 final String userKey = userKeySetting.getValue();
2185
2186 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002187 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2188
2189 // Validate that the key is of expected length.
2190 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2191 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002192 throw new IllegalStateException("User key invalid");
2193 }
2194
Mark Rathjen7599f132017-01-23 14:15:54 -08002195 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002196 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002197 m = Mac.getInstance("HmacSHA256");
2198 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002199 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002200 throw new IllegalStateException("HmacSHA256 is not available", e);
2201 } catch (InvalidKeyException e) {
2202 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002203 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002204
Mark Rathjenf42dd912017-06-05 19:04:34 -07002205 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002206 for (int i = 0; i < callingPkg.signatures.length; i++) {
2207 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002208 m.update(getLengthPrefix(sig), 0, 4);
2209 m.update(sig);
2210 }
Mark Rathjend891f012017-01-19 04:10:37 +00002211
2212 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002213 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2214 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002215
2216 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002217 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002218 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2219 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002220 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002221
2222 if (!success) {
2223 throw new IllegalStateException("Ssaid settings not accessible");
2224 }
2225
2226 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2227 }
2228
2229 public void syncSsaidTableOnStart() {
2230 synchronized (mLock) {
2231 // Verify that each user's packages and ssaid's are in sync.
2232 for (UserInfo user : mUserManager.getUsers(true)) {
2233 // Get all uids for the user's packages.
2234 final List<PackageInfo> packages;
2235 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002236 packages = mPackageManager.getInstalledPackages(
2237 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2238 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002239 } catch (RemoteException e) {
2240 throw new IllegalStateException("Package manager not available");
2241 }
2242 final Set<String> appUids = new HashSet<>();
2243 for (PackageInfo info : packages) {
2244 appUids.add(Integer.toString(info.applicationInfo.uid));
2245 }
2246
2247 // Get all uids currently stored in the user's ssaid table.
2248 final Set<String> ssaidUids = new HashSet<>(
2249 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2250 ssaidUids.remove(SSAID_USER_KEY);
2251
2252 // Perform a set difference for the appUids and ssaidUids.
2253 ssaidUids.removeAll(appUids);
2254
2255 // If there are ssaidUids left over they need to be removed from the table.
2256 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2257 user.id);
2258 for (String uid : ssaidUids) {
2259 ssaidSettings.deleteSettingLocked(uid);
2260 }
2261 }
2262 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002263 }
2264
Svetoslav683914b2015-01-15 14:22:26 -08002265 public List<String> getSettingsNamesLocked(int type, int userId) {
2266 final int key = makeKey(type, userId);
2267 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002268 if (settingsState == null) {
2269 return new ArrayList<String>();
2270 }
Svetoslav683914b2015-01-15 14:22:26 -08002271 return settingsState.getSettingNamesLocked();
2272 }
2273
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002274 public SparseBooleanArray getKnownUsersLocked() {
2275 SparseBooleanArray users = new SparseBooleanArray();
2276 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2277 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2278 }
2279 return users;
2280 }
2281
Kweku Adamsb0886f32017-10-31 15:32:09 -07002282 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002283 public SettingsState getSettingsLocked(int type, int userId) {
2284 final int key = makeKey(type, userId);
2285 return peekSettingsStateLocked(key);
2286 }
2287
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002288 public boolean ensureSettingsForUserLocked(int userId) {
2289 // First make sure this user actually exists.
2290 if (mUserManager.getUserInfo(userId) == null) {
2291 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2292 return false;
2293 }
2294
Svetoslav683914b2015-01-15 14:22:26 -08002295 // Migrate the setting for this user if needed.
2296 migrateLegacySettingsForUserIfNeededLocked(userId);
2297
2298 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002299 if (userId == UserHandle.USER_SYSTEM) {
2300 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002301 ensureSettingsStateLocked(globalKey);
2302 }
2303
2304 // Ensure secure settings loaded.
2305 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2306 ensureSettingsStateLocked(secureKey);
2307
2308 // Make sure the secure settings have an Android id set.
2309 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2310 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2311
2312 // Ensure system settings loaded.
2313 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2314 ensureSettingsStateLocked(systemKey);
2315
Mark Rathjend891f012017-01-19 04:10:37 +00002316 // Ensure secure settings loaded.
2317 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2318 ensureSettingsStateLocked(ssaidKey);
2319
Svetoslav683914b2015-01-15 14:22:26 -08002320 // Upgrade the settings to the latest version.
2321 UpgradeController upgrader = new UpgradeController(userId);
2322 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002323 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002324 }
2325
2326 private void ensureSettingsStateLocked(int key) {
2327 if (mSettingsStates.get(key) == null) {
2328 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002329 SettingsState settingsState = new SettingsState(getContext(), mLock,
2330 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002331 mSettingsStates.put(key, settingsState);
2332 }
2333 }
2334
2335 public void removeUserStateLocked(int userId, boolean permanently) {
2336 // We always keep the global settings in memory.
2337
2338 // Nuke system settings.
2339 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2340 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2341 if (systemSettingsState != null) {
2342 if (permanently) {
2343 mSettingsStates.remove(systemKey);
2344 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002345 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002346 systemSettingsState.destroyLocked(new Runnable() {
2347 @Override
2348 public void run() {
2349 mSettingsStates.remove(systemKey);
2350 }
2351 });
2352 }
2353 }
2354
2355 // Nuke secure settings.
2356 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2357 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2358 if (secureSettingsState != null) {
2359 if (permanently) {
2360 mSettingsStates.remove(secureKey);
2361 secureSettingsState.destroyLocked(null);
2362 } else {
2363 secureSettingsState.destroyLocked(new Runnable() {
2364 @Override
2365 public void run() {
2366 mSettingsStates.remove(secureKey);
2367 }
2368 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002369 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002370 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002371
Mark Rathjend891f012017-01-19 04:10:37 +00002372 // Nuke ssaid settings.
2373 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2374 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2375 if (ssaidSettingsState != null) {
2376 if (permanently) {
2377 mSettingsStates.remove(ssaidKey);
2378 ssaidSettingsState.destroyLocked(null);
2379 } else {
2380 ssaidSettingsState.destroyLocked(new Runnable() {
2381 @Override
2382 public void run() {
2383 mSettingsStates.remove(ssaidKey);
2384 }
2385 });
2386 }
2387 }
2388
Svet Ganov53a441c2016-04-19 19:38:00 -07002389 // Nuke generation tracking data
2390 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002391 }
2392
Svetoslav683914b2015-01-15 14:22:26 -08002393 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002394 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2395 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002396 final int key = makeKey(type, userId);
2397
Svetoslav Ganove080da92016-12-21 17:10:35 -08002398 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002399 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002400 if (settingsState != null) {
2401 success = settingsState.insertSettingLocked(name, value,
2402 tag, makeDefault, packageName);
2403 }
Svetoslav683914b2015-01-15 14:22:26 -08002404
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002405 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2406 settingsState.persistSyncLocked();
2407 }
2408
Svet Ganov53a441c2016-04-19 19:38:00 -07002409 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002410 notifyForSettingsChange(key, name);
2411 }
2412 return success;
2413 }
2414
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002415 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2416 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002417 final int key = makeKey(type, userId);
2418
Svetoslav Ganove080da92016-12-21 17:10:35 -08002419 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002420 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002421 if (settingsState != null) {
2422 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002423 }
Svetoslav683914b2015-01-15 14:22:26 -08002424
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002425 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2426 settingsState.persistSyncLocked();
2427 }
2428
Svet Ganov53a441c2016-04-19 19:38:00 -07002429 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002430 notifyForSettingsChange(key, name);
2431 }
2432 return success;
2433 }
2434
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002435 public boolean updateSettingLocked(int type, int userId, String name, String value,
2436 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2437 Set<String> criticalSettings) {
2438 final int key = makeKey(type, userId);
2439
2440 boolean success = false;
2441 SettingsState settingsState = peekSettingsStateLocked(key);
2442 if (settingsState != null) {
2443 success = settingsState.updateSettingLocked(name, value, tag,
2444 makeDefault, packageName);
2445 }
2446
2447 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2448 settingsState.persistSyncLocked();
2449 }
2450
2451 if (forceNotify || success) {
2452 notifyForSettingsChange(key, name);
2453 }
2454
2455 return success;
2456 }
2457
Svetoslav683914b2015-01-15 14:22:26 -08002458 public Setting getSettingLocked(int type, int userId, String name) {
2459 final int key = makeKey(type, userId);
2460
2461 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002462 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002463 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002464 }
Mark Rathjend891f012017-01-19 04:10:37 +00002465
2466 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002467 return settingsState.getSettingLocked(name);
2468 }
2469
Svetoslav Ganove080da92016-12-21 17:10:35 -08002470 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2471 String tag) {
2472 final int key = makeKey(type, userId);
2473 SettingsState settingsState = peekSettingsStateLocked(key);
2474 if (settingsState == null) {
2475 return;
2476 }
2477
2478 switch (mode) {
2479 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2480 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002481 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002482 Setting setting = settingsState.getSettingLocked(name);
2483 if (packageName.equals(setting.getPackageName())) {
2484 if (tag != null && !tag.equals(setting.getTag())) {
2485 continue;
2486 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002487 if (settingsState.resetSettingLocked(name)) {
2488 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002489 notifyForSettingsChange(key, name);
2490 }
2491 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002492 if (someSettingChanged) {
2493 settingsState.persistSyncLocked();
2494 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002495 }
2496 } break;
2497
2498 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2499 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002500 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002501 Setting setting = settingsState.getSettingLocked(name);
2502 if (!SettingsState.isSystemPackage(getContext(),
2503 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002504 if (settingsState.resetSettingLocked(name)) {
2505 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002506 notifyForSettingsChange(key, name);
2507 }
2508 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002509 if (someSettingChanged) {
2510 settingsState.persistSyncLocked();
2511 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002512 }
2513 } break;
2514
2515 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2516 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002517 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002518 Setting setting = settingsState.getSettingLocked(name);
2519 if (!SettingsState.isSystemPackage(getContext(),
2520 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002521 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002522 if (settingsState.resetSettingLocked(name)) {
2523 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002524 notifyForSettingsChange(key, name);
2525 }
2526 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002527 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002528 notifyForSettingsChange(key, name);
2529 }
2530 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002531 if (someSettingChanged) {
2532 settingsState.persistSyncLocked();
2533 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002534 }
2535 } break;
2536
2537 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2538 for (String name : settingsState.getSettingNamesLocked()) {
2539 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002540 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002541 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002542 if (settingsState.resetSettingLocked(name)) {
2543 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002544 notifyForSettingsChange(key, name);
2545 }
2546 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002547 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002548 notifyForSettingsChange(key, name);
2549 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002550 if (someSettingChanged) {
2551 settingsState.persistSyncLocked();
2552 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002553 }
2554 } break;
2555 }
2556 }
2557
Zimuzoc56192c2018-07-25 10:40:01 +01002558 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002559 // Global and secure settings are signature protected. Apps signed
2560 // by the platform certificate are generally not uninstalled and
2561 // the main exception is tests. We trust components signed
2562 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002563
2564 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2565 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002566 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002567 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002568 }
Svetoslav683914b2015-01-15 14:22:26 -08002569 }
2570
Mark Rathjend891f012017-01-19 04:10:37 +00002571 public void onUidRemovedLocked(int uid) {
2572 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2573 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002574 if (ssaidSettings != null) {
2575 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2576 }
Mark Rathjend891f012017-01-19 04:10:37 +00002577 }
2578
Kweku Adamsb0886f32017-10-31 15:32:09 -07002579 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002580 private SettingsState peekSettingsStateLocked(int key) {
2581 SettingsState settingsState = mSettingsStates.get(key);
2582 if (settingsState != null) {
2583 return settingsState;
2584 }
2585
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002586 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2587 return null;
2588 }
Svetoslav683914b2015-01-15 14:22:26 -08002589 return mSettingsStates.get(key);
2590 }
2591
2592 private void migrateAllLegacySettingsIfNeeded() {
2593 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002594 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002595 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002596 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002597 return;
2598 }
2599
Amith Yamasani39452022017-03-21 15:23:47 -07002600 mSettingsCreationBuildId = Build.ID;
2601
Svetoslav683914b2015-01-15 14:22:26 -08002602 final long identity = Binder.clearCallingIdentity();
2603 try {
2604 List<UserInfo> users = mUserManager.getUsers(true);
2605
2606 final int userCount = users.size();
2607 for (int i = 0; i < userCount; i++) {
2608 final int userId = users.get(i).id;
2609
2610 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2611 SQLiteDatabase database = dbHelper.getWritableDatabase();
2612 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2613
2614 // Upgrade to the latest version.
2615 UpgradeController upgrader = new UpgradeController(userId);
2616 upgrader.upgradeIfNeededLocked();
2617
2618 // Drop from memory if not a running user.
2619 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2620 removeUserStateLocked(userId, false);
2621 }
2622 }
2623 } finally {
2624 Binder.restoreCallingIdentity(identity);
2625 }
2626 }
2627 }
2628
2629 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2630 // Every user has secure settings and if no file we need to migrate.
2631 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2632 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002633 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002634 return;
2635 }
2636
2637 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2638 SQLiteDatabase database = dbHelper.getWritableDatabase();
2639
2640 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2641 }
2642
2643 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2644 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002645 // Move over the system settings.
2646 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2647 ensureSettingsStateLocked(systemKey);
2648 SettingsState systemSettings = mSettingsStates.get(systemKey);
2649 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2650 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002651
2652 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002653 // Do this after System settings, since this is the first thing we check when deciding
2654 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002655 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2656 ensureSettingsStateLocked(secureKey);
2657 SettingsState secureSettings = mSettingsStates.get(secureKey);
2658 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2659 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2660 secureSettings.persistSyncLocked();
2661
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002662 // Move over the global settings if owner.
2663 // Do this last, since this is the first thing we check when deciding
2664 // to skip over migration from db to xml for owner user.
2665 if (userId == UserHandle.USER_SYSTEM) {
2666 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2667 ensureSettingsStateLocked(globalKey);
2668 SettingsState globalSettings = mSettingsStates.get(globalKey);
2669 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002670 // If this was just created
2671 if (mSettingsCreationBuildId != null) {
2672 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2673 mSettingsCreationBuildId, null, true,
2674 SettingsState.SYSTEM_PACKAGE_NAME);
2675 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002676 globalSettings.persistSyncLocked();
2677 }
Svetoslav683914b2015-01-15 14:22:26 -08002678
2679 // Drop the database as now all is moved and persisted.
2680 if (DROP_DATABASE_ON_MIGRATION) {
2681 dbHelper.dropDatabase();
2682 } else {
2683 dbHelper.backupDatabase();
2684 }
2685 }
2686
2687 private void migrateLegacySettingsLocked(SettingsState settingsState,
2688 SQLiteDatabase database, String table) {
2689 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2690 queryBuilder.setTables(table);
2691
2692 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2693 null, null, null, null, null);
2694
2695 if (cursor == null) {
2696 return;
2697 }
2698
2699 try {
2700 if (!cursor.moveToFirst()) {
2701 return;
2702 }
2703
2704 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2705 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2706
2707 settingsState.setVersionLocked(database.getVersion());
2708
2709 while (!cursor.isAfterLast()) {
2710 String name = cursor.getString(nameColumnIdx);
2711 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002712 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002713 SettingsState.SYSTEM_PACKAGE_NAME);
2714 cursor.moveToNext();
2715 }
2716 } finally {
2717 cursor.close();
2718 }
2719 }
2720
2721 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2722 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2723
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002724 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002725 return;
2726 }
2727
2728 final int userId = getUserIdFromKey(secureSettings.mKey);
2729
2730 final UserInfo user;
2731 final long identity = Binder.clearCallingIdentity();
2732 try {
2733 user = mUserManager.getUserInfo(userId);
2734 } finally {
2735 Binder.restoreCallingIdentity(identity);
2736 }
2737 if (user == null) {
2738 // Can happen due to races when deleting users - treat as benign.
2739 return;
2740 }
2741
2742 String androidId = Long.toHexString(new SecureRandom().nextLong());
2743 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002744 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002745
2746 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2747 + "] for user " + userId);
2748
2749 // Write a drop box entry if it's a restricted profile
2750 if (user.isRestricted()) {
2751 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2752 Context.DROPBOX_SERVICE);
2753 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2754 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2755 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2756 }
2757 }
2758 }
2759
2760 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07002761 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07002762 mGenerationRegistry.incrementGeneration(key);
2763
Svet Ganov945864c2018-03-22 21:49:10 -07002764 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06002765 final long token = Binder.clearCallingIdentity();
2766 try {
2767 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2768 // When the global kill switch is updated, send the
2769 // change notification for the location setting.
2770 notifyLocationChangeForRunningUsers();
2771 }
2772 notifyGlobalSettingChangeForRunningUsers(key, name);
2773 } finally {
2774 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07002775 }
Svet Ganov945864c2018-03-22 21:49:10 -07002776 } else {
2777 final int userId = getUserIdFromKey(key);
2778 final Uri uri = getNotificationUriFor(key, name);
2779 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2780 userId, 0, uri).sendToTarget();
2781 if (isSecureSettingsKey(key)) {
2782 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2783 sSecureCloneToManagedSettings);
2784 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2785 sSystemCloneFromParentOnDependency.values());
2786 } else if (isSystemSettingsKey(key)) {
2787 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2788 sSystemCloneToManagedSettings);
2789 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002790 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002791
Svet Ganov945864c2018-03-22 21:49:10 -07002792 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07002793 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002794 }
2795
Svet Ganov53a441c2016-04-19 19:38:00 -07002796 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002797 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002798 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002799 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002800 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002801 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07002802 final int key = makeKey(type, profileId);
2803 // Increment the generation first, so observers always see the new value
2804 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07002805 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002806 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002807 }
2808 }
2809 }
Svetoslav683914b2015-01-15 14:22:26 -08002810 }
2811
Svet Ganov945864c2018-03-22 21:49:10 -07002812 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
2813 // Important: No need to update generation for each user as there
2814 // is a singleton generation entry for the global settings which
2815 // is already incremented be the caller.
2816 final Uri uri = getNotificationUriFor(key, name);
2817 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
2818 for (int i = 0; i < users.size(); i++) {
2819 final int userId = users.get(i).id;
2820 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
2821 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2822 userId, 0, uri).sendToTarget();
2823 }
2824 }
2825 }
2826
Makoto Onuki0000d322017-11-28 16:31:47 -08002827 private void notifyLocationChangeForRunningUsers() {
2828 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2829
2830 for (int i = 0; i < users.size(); i++) {
2831 final int userId = users.get(i).id;
2832
2833 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2834 continue;
2835 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002836
Svet Ganov945864c2018-03-22 21:49:10 -07002837 // Increment the generation first, so observers always see the new value
2838 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2839 mGenerationRegistry.incrementGeneration(key);
2840
2841 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08002842 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2843 userId, 0, uri).sendToTarget();
2844 }
2845 }
2846
Svetoslav683914b2015-01-15 14:22:26 -08002847 private boolean isGlobalSettingsKey(int key) {
2848 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2849 }
2850
2851 private boolean isSystemSettingsKey(int key) {
2852 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2853 }
2854
2855 private boolean isSecureSettingsKey(int key) {
2856 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2857 }
2858
Mark Rathjend891f012017-01-19 04:10:37 +00002859 private boolean isSsaidSettingsKey(int key) {
2860 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2861 }
2862
Svetoslav683914b2015-01-15 14:22:26 -08002863 private File getSettingsFile(int key) {
2864 if (isGlobalSettingsKey(key)) {
2865 final int userId = getUserIdFromKey(key);
2866 return new File(Environment.getUserSystemDirectory(userId),
2867 SETTINGS_FILE_GLOBAL);
2868 } else if (isSystemSettingsKey(key)) {
2869 final int userId = getUserIdFromKey(key);
2870 return new File(Environment.getUserSystemDirectory(userId),
2871 SETTINGS_FILE_SYSTEM);
2872 } else if (isSecureSettingsKey(key)) {
2873 final int userId = getUserIdFromKey(key);
2874 return new File(Environment.getUserSystemDirectory(userId),
2875 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002876 } else if (isSsaidSettingsKey(key)) {
2877 final int userId = getUserIdFromKey(key);
2878 return new File(Environment.getUserSystemDirectory(userId),
2879 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002880 } else {
2881 throw new IllegalArgumentException("Invalid settings key:" + key);
2882 }
2883 }
2884
2885 private Uri getNotificationUriFor(int key, String name) {
2886 if (isGlobalSettingsKey(key)) {
2887 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2888 : Settings.Global.CONTENT_URI;
2889 } else if (isSecureSettingsKey(key)) {
2890 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2891 : Settings.Secure.CONTENT_URI;
2892 } else if (isSystemSettingsKey(key)) {
2893 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2894 : Settings.System.CONTENT_URI;
2895 } else {
2896 throw new IllegalArgumentException("Invalid settings key:" + key);
2897 }
2898 }
2899
2900 private int getMaxBytesPerPackageForType(int type) {
2901 switch (type) {
2902 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002903 case SETTINGS_TYPE_SECURE:
2904 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002905 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2906 }
2907
2908 default: {
2909 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2910 }
2911 }
2912 }
2913
Svetoslav7e0683b2015-08-03 16:02:52 -07002914 private final class MyHandler extends Handler {
2915 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2916 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2917
2918 public MyHandler(Looper looper) {
2919 super(looper);
2920 }
2921
2922 @Override
2923 public void handleMessage(Message msg) {
2924 switch (msg.what) {
2925 case MSG_NOTIFY_URI_CHANGED: {
2926 final int userId = msg.arg1;
2927 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002928 try {
2929 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2930 } catch (SecurityException e) {
2931 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2932 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002933 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002934 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2935 }
2936 } break;
2937
2938 case MSG_NOTIFY_DATA_CHANGED: {
2939 mBackupManager.dataChanged();
2940 } break;
2941 }
2942 }
2943 }
2944
Svetoslav683914b2015-01-15 14:22:26 -08002945 private final class UpgradeController {
Beverly91d0a632018-07-02 16:45:00 -04002946 private static final int SETTINGS_VERSION = 171;
Svetoslav683914b2015-01-15 14:22:26 -08002947
2948 private final int mUserId;
2949
2950 public UpgradeController(int userId) {
2951 mUserId = userId;
2952 }
2953
2954 public void upgradeIfNeededLocked() {
2955 // The version of all settings for a user is the same (all users have secure).
2956 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002957 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002958
2959 // Try an update from the current state.
2960 final int oldVersion = secureSettings.getVersionLocked();
2961 final int newVersion = SETTINGS_VERSION;
2962
Svet Ganovc9755bc2015-03-28 13:21:22 -07002963 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002964 if (oldVersion == newVersion) {
2965 return;
2966 }
2967
2968 // Try to upgrade.
2969 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2970
2971 // If upgrade failed start from scratch and upgrade.
2972 if (curVersion != newVersion) {
2973 // Drop state we have for this user.
2974 removeUserStateLocked(mUserId, true);
2975
2976 // Recreate the database.
2977 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2978 SQLiteDatabase database = dbHelper.getWritableDatabase();
2979 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2980
2981 // Migrate the settings for this user.
2982 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2983
2984 // Now upgrade should work fine.
2985 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002986
2987 // Make a note what happened, so we don't wonder why data was lost
2988 String reason = "Settings rebuilt! Current version: "
2989 + curVersion + " while expected: " + newVersion;
2990 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002991 Settings.Global.DATABASE_DOWNGRADE_REASON,
2992 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002993 }
2994
2995 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002996 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002997 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002998 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002999 globalSettings.setVersionLocked(newVersion);
3000 }
3001
3002 // Set the secure settings version.
3003 secureSettings.setVersionLocked(newVersion);
3004
3005 // Set the system settings version.
3006 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003007 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003008 systemSettings.setVersionLocked(newVersion);
3009 }
3010
3011 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003012 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003013 }
3014
3015 private SettingsState getSecureSettingsLocked(int userId) {
3016 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3017 }
3018
Mark Rathjend891f012017-01-19 04:10:37 +00003019 private SettingsState getSsaidSettingsLocked(int userId) {
3020 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3021 }
3022
Svetoslav683914b2015-01-15 14:22:26 -08003023 private SettingsState getSystemSettingsLocked(int userId) {
3024 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3025 }
3026
Jeff Brown503cffc2015-03-26 18:08:51 -07003027 /**
3028 * You must perform all necessary mutations to bring the settings
3029 * for this user from the old to the new version. When you add a new
3030 * upgrade step you *must* update SETTINGS_VERSION.
3031 *
3032 * This is an example of moving a setting from secure to global.
3033 *
3034 * // v119: Example settings changes.
3035 * if (currentVersion == 118) {
3036 * if (userId == UserHandle.USER_OWNER) {
3037 * // Remove from the secure settings.
3038 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3039 * String name = "example_setting_to_move";
3040 * String value = secureSettings.getSetting(name);
3041 * secureSettings.deleteSetting(name);
3042 *
3043 * // Add to the global settings.
3044 * SettingsState globalSettings = getGlobalSettingsLocked();
3045 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3046 * }
3047 *
3048 * // Update the current version.
3049 * currentVersion = 119;
3050 * }
3051 */
Svetoslav683914b2015-01-15 14:22:26 -08003052 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3053 if (DEBUG) {
3054 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3055 + oldVersion + " to version: " + newVersion);
3056 }
3057
Jeff Brown503cffc2015-03-26 18:08:51 -07003058 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003059
John Spurlocke11ae112015-05-11 16:09:03 -04003060 // v119: Reset zen + ringer mode.
3061 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003062 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003063 final SettingsState globalSettings = getGlobalSettingsLocked();
3064 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003065 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3066 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003067 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003068 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3069 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003070 }
3071 currentVersion = 119;
3072 }
3073
Jason Monk27bbb2d2015-03-31 16:46:39 -04003074 // v120: Add double tap to wake setting.
3075 if (currentVersion == 119) {
3076 SettingsState secureSettings = getSecureSettingsLocked(userId);
3077 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3078 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003079 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003080 SettingsState.SYSTEM_PACKAGE_NAME);
3081
3082 currentVersion = 120;
3083 }
3084
Svetoslav7e0683b2015-08-03 16:02:52 -07003085 if (currentVersion == 120) {
3086 // Before 121, we used a different string encoding logic. We just bump the
3087 // version here; SettingsState knows how to handle pre-version 120 files.
3088 currentVersion = 121;
3089 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003090
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003091 if (currentVersion == 121) {
3092 // Version 122: allow OEMs to set a default payment component in resources.
3093 // Note that we only write the default if no default has been set;
3094 // if there is, we just leave the default at whatever it currently is.
3095 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3096 String defaultComponent = (getContext().getResources().getString(
3097 R.string.def_nfc_payment_component));
3098 Setting currentSetting = secureSettings.getSettingLocked(
3099 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3100 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003101 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003102 secureSettings.insertSettingLocked(
3103 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003104 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003105 }
3106 currentVersion = 122;
3107 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003108
3109 if (currentVersion == 122) {
3110 // Version 123: Adding a default value for the ability to add a user from
3111 // the lock screen.
3112 if (userId == UserHandle.USER_SYSTEM) {
3113 final SettingsState globalSettings = getGlobalSettingsLocked();
3114 Setting currentSetting = globalSettings.getSettingLocked(
3115 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003116 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003117 globalSettings.insertSettingLocked(
3118 Settings.Global.ADD_USERS_WHEN_LOCKED,
3119 getContext().getResources().getBoolean(
3120 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003121 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003122 }
3123 }
3124 currentVersion = 123;
3125 }
Bryce Leebd179282015-12-17 19:01:37 -08003126
3127 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003128 final SettingsState globalSettings = getGlobalSettingsLocked();
3129 String defaultDisabledProfiles = (getContext().getResources().getString(
3130 R.string.def_bluetooth_disabled_profiles));
3131 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003132 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003133 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003134 }
3135
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003136 if (currentVersion == 124) {
3137 // Version 124: allow OEMs to set a default value for whether IME should be
3138 // shown when a physical keyboard is connected.
3139 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3140 Setting currentSetting = secureSettings.getSettingLocked(
3141 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003142 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003143 secureSettings.insertSettingLocked(
3144 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3145 getContext().getResources().getBoolean(
3146 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003147 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003148 }
3149 currentVersion = 125;
3150 }
3151
Ruben Brunk98576cf2016-03-07 18:54:28 -08003152 if (currentVersion == 125) {
3153 // Version 125: Allow OEMs to set the default VR service.
3154 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3155
3156 Setting currentSetting = secureSettings.getSettingLocked(
3157 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003158 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003159 ArraySet<ComponentName> l =
3160 SystemConfig.getInstance().getDefaultVrComponents();
3161
3162 if (l != null && !l.isEmpty()) {
3163 StringBuilder b = new StringBuilder();
3164 boolean start = true;
3165 for (ComponentName c : l) {
3166 if (!start) {
3167 b.append(':');
3168 }
3169 b.append(c.flattenToString());
3170 start = false;
3171 }
3172 secureSettings.insertSettingLocked(
3173 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003174 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003175 }
3176
3177 }
3178 currentVersion = 126;
3179 }
3180
Daniel U02ba6122016-04-01 18:41:42 +01003181 if (currentVersion == 126) {
3182 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3183 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3184 if (mUserManager.isManagedProfile(userId)) {
3185 final SettingsState systemSecureSettings =
3186 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3187
3188 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3189 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003190 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003191 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3192 secureSettings.insertSettingLocked(
3193 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003194 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003195 SettingsState.SYSTEM_PACKAGE_NAME);
3196 }
3197
3198 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3199 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003200 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003201 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3202 secureSettings.insertSettingLocked(
3203 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003204 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003205 SettingsState.SYSTEM_PACKAGE_NAME);
3206 }
3207 }
3208 currentVersion = 127;
3209 }
3210
Steven Ngdc20ba62016-04-26 18:19:04 +01003211 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003212 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003213 currentVersion = 128;
3214 }
3215
Julia Reynolds1f721e12016-07-11 08:50:58 -04003216 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003217 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003218 currentVersion = 129;
3219 }
3220
Dan Sandler71f85e92016-07-20 13:46:05 -04003221 if (currentVersion == 129) {
3222 // default longpress timeout changed from 500 to 400. If unchanged from the old
3223 // default, update to the new default.
3224 final SettingsState systemSecureSettings =
3225 getSecureSettingsLocked(userId);
3226 final String oldValue = systemSecureSettings.getSettingLocked(
3227 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3228 if (TextUtils.equals("500", oldValue)) {
3229 systemSecureSettings.insertSettingLocked(
3230 Settings.Secure.LONG_PRESS_TIMEOUT,
3231 String.valueOf(getContext().getResources().getInteger(
3232 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003233 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003234 }
3235 currentVersion = 130;
3236 }
3237
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003238 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003239 // Split Ambient settings
3240 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3241 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3242 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3243
3244 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003245 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003246 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003247 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003248 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003249 }
3250 currentVersion = 131;
3251 }
3252
3253 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003254 // Initialize new multi-press timeout to default value
3255 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3256 final String oldValue = systemSecureSettings.getSettingLocked(
3257 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3258 if (TextUtils.equals(null, oldValue)) {
3259 systemSecureSettings.insertSettingLocked(
3260 Settings.Secure.MULTI_PRESS_TIMEOUT,
3261 String.valueOf(getContext().getResources().getInteger(
3262 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003263 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003264 }
3265
Adrian Roos69741a22016-10-21 14:49:17 -07003266 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003267 }
3268
Adrian Roos69741a22016-10-21 14:49:17 -07003269 if (currentVersion == 132) {
3270 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003271 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3272 String defaultSyncParentSounds = (getContext().getResources()
3273 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3274 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003275 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3276 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003277 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003278 }
3279
Adrian Roos69741a22016-10-21 14:49:17 -07003280 if (currentVersion == 133) {
3281 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003282 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3283 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3284 null) {
3285 String defaultEndButtonBehavior = Integer.toString(getContext()
3286 .getResources().getInteger(R.integer.def_end_button_behavior));
3287 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003288 defaultEndButtonBehavior, null, true,
3289 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003290 }
Adrian Roos69741a22016-10-21 14:49:17 -07003291 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003292 }
3293
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003294 if (currentVersion == 134) {
3295 // Remove setting that specifies if magnification values should be preserved.
3296 // This setting defaulted to true and never has a UI.
3297 getSecureSettingsLocked(userId).deleteSettingLocked(
3298 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3299 currentVersion = 135;
3300 }
3301
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003302 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003303 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003304 currentVersion = 136;
3305 }
3306
Mark Rathjend891f012017-01-19 04:10:37 +00003307 if (currentVersion == 136) {
3308 // Version 136: Store legacy SSAID for all apps currently installed on the
3309 // device as first step in migrating SSAID to be unique per application.
3310
3311 final boolean isUpgrade;
3312 try {
3313 isUpgrade = mPackageManager.isUpgrade();
3314 } catch (RemoteException e) {
3315 throw new IllegalStateException("Package manager not available");
3316 }
3317 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3318 // user data or first boot on a new device should use new ssaid generation.
3319 if (isUpgrade) {
3320 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003321 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3322 userId, Settings.Secure.ANDROID_ID);
3323 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3324 || legacySsaidSetting.getValue() == null) {
3325 throw new IllegalStateException("Legacy ssaid not accessible");
3326 }
3327 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003328
3329 // Fill each uid with the legacy ssaid to be backwards compatible.
3330 final List<PackageInfo> packages;
3331 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003332 packages = mPackageManager.getInstalledPackages(
3333 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3334 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003335 } catch (RemoteException e) {
3336 throw new IllegalStateException("Package manager not available");
3337 }
3338
3339 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3340 for (PackageInfo info : packages) {
3341 // Check if the UID already has an entry in the table.
3342 final String uid = Integer.toString(info.applicationInfo.uid);
3343 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3344
3345 if (ssaid.isNull() || ssaid.getValue() == null) {
3346 // Android Id doesn't exist for this package so create it.
3347 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3348 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003349 if (DEBUG) {
3350 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3351 }
Mark Rathjend891f012017-01-19 04:10:37 +00003352 }
3353 }
3354 }
3355
3356 currentVersion = 137;
3357 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003358 if (currentVersion == 137) {
3359 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3360 // default value set to 1. The user can no longer change the value of this
3361 // setting through the UI.
3362 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3363 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003364 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3365 && secureSetting.getSettingLocked(
3366 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3367
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003368 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3369 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003370 // For managed profiles with profile owners, DevicePolicyManagerService
3371 // may want to set the user restriction in this case
3372 secureSetting.insertSettingLocked(
3373 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3374 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003375 }
3376 currentVersion = 138;
3377 }
Mark Rathjend891f012017-01-19 04:10:37 +00003378
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003379 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003380 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003381 currentVersion = 139;
3382 }
3383
Phil Weaver385912e2017-02-10 10:06:56 -08003384 if (currentVersion == 139) {
3385 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3386 // the user can no longer change the value of this setting through the UI.
3387 // Force to true.
3388 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3389 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3390 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3391 currentVersion = 140;
3392 }
3393
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003394 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003395 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003396 currentVersion = 141;
3397 }
3398
Svet Ganov13701552017-02-23 12:45:17 -08003399 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003400 // This implementation was incorrectly setting the current value of
3401 // settings changed by non-system packages as the default which default
3402 // is set by the system. We add a new upgrade step at the end to properly
3403 // handle this case which would also fix incorrect changes made by the
3404 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003405 currentVersion = 142;
3406 }
3407
Stephen Chen5d0922f2017-03-27 10:28:04 -07003408 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003409 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003410 if (userId == UserHandle.USER_SYSTEM) {
3411 final SettingsState globalSettings = getGlobalSettingsLocked();
3412 Setting currentSetting = globalSettings.getSettingLocked(
3413 Settings.Global.WIFI_WAKEUP_ENABLED);
3414 if (currentSetting.isNull()) {
3415 globalSettings.insertSettingLocked(
3416 Settings.Global.WIFI_WAKEUP_ENABLED,
3417 getContext().getResources().getBoolean(
3418 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3419 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3420 }
3421 }
3422
3423 currentVersion = 143;
3424 }
3425
Felipe Lemeff355092017-04-03 12:55:02 -07003426 if (currentVersion == 143) {
3427 // Version 144: Set a default value for Autofill service.
3428 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3429 final Setting currentSetting = secureSettings
3430 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3431 if (currentSetting.isNull()) {
3432 final String defaultValue = getContext().getResources().getString(
3433 com.android.internal.R.string.config_defaultAutofillService);
3434 if (defaultValue != null) {
3435 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3436 + "for user " + userId);
3437 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3438 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3439 }
3440 }
3441
3442 currentVersion = 144;
3443 }
3444
Jeremy Joslin45caa252017-05-04 11:22:46 -07003445 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003446 // Version 145: Removed
3447 currentVersion = 145;
3448 }
3449
3450 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003451 // Version 146: In step 142 we had a bug where incorrectly
3452 // some settings were considered system set and as a result
3453 // made the default and marked as the default being set by
3454 // the system. Here reevaluate the default and default system
3455 // set flags. This would both fix corruption by the old impl
3456 // of step 142 and also properly handle devices which never
3457 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003458 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003459 SettingsState globalSettings = getGlobalSettingsLocked();
3460 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3461 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003462 }
3463
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003464 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3465 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3466 secureSettings.persistSyncLocked();
3467
3468 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3469 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3470 systemSettings.persistSyncLocked();
3471
Amin Shaikh86367962017-06-07 08:58:22 -07003472 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003473 }
3474
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003475 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003476 // Version 147: Removed. (This version previously allowed showing the
3477 // "wifi_wakeup_available" setting).
3478 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003479 currentVersion = 147;
3480 }
3481
3482 if (currentVersion == 147) {
3483 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003484 if (userId == UserHandle.USER_SYSTEM) {
3485 final SettingsState globalSettings = getGlobalSettingsLocked();
3486 final Setting currentSetting = globalSettings.getSettingLocked(
3487 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3488 if (currentSetting.isNull()) {
3489 globalSettings.insertSettingLocked(
3490 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3491 getContext().getResources().getBoolean(
3492 R.bool.def_restrict_background_data) ? "1" : "0",
3493 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3494 }
3495 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003496 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003497 }
3498
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003499 if (currentVersion == 148) {
3500 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3501 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3502 final String oldValue = systemSecureSettings.getSettingLocked(
3503 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3504 if (TextUtils.equals(null, oldValue)) {
3505 final String defaultValue = getContext().getResources().getString(
3506 R.string.def_backup_manager_constants);
3507 if (!TextUtils.isEmpty(defaultValue)) {
3508 systemSecureSettings.insertSettingLocked(
3509 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3510 true, SettingsState.SYSTEM_PACKAGE_NAME);
3511 }
3512 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003513 currentVersion = 149;
3514 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003515
3516 if (currentVersion == 149) {
3517 // Version 150: Set a default value for mobile data always on
3518 final SettingsState globalSettings = getGlobalSettingsLocked();
3519 final Setting currentSetting = globalSettings.getSettingLocked(
3520 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3521 if (currentSetting.isNull()) {
3522 globalSettings.insertSettingLocked(
3523 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3524 getContext().getResources().getBoolean(
3525 R.bool.def_mobile_data_always_on) ? "1" : "0",
3526 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3527 }
3528
3529 currentVersion = 150;
3530 }
3531
Mike Digman4af4a6f2018-01-16 14:49:38 -08003532 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003533 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003534 currentVersion = 151;
3535 }
3536
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003537 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003538 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3539 // by default but it is now no longer configurable).
3540 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003541 currentVersion = 152;
3542 }
3543
Joe LaPenna250d7842018-01-25 10:19:42 -08003544 if (currentVersion == 152) {
3545 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3546 currentVersion = 153;
3547 }
3548
Ben Linb4df8bc2018-01-29 11:48:20 -08003549 if (currentVersion == 153) {
3550 // Version 154: Read notification badge configuration from config.
3551 // If user has already set the value, don't do anything.
3552 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3553 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3554 Settings.Secure.NOTIFICATION_BADGING);
3555 if (showNotificationBadges.isNull()) {
3556 final boolean defaultValue = getContext().getResources().getBoolean(
3557 com.android.internal.R.bool.config_notificationBadging);
3558 systemSecureSettings.insertSettingLocked(
3559 Secure.NOTIFICATION_BADGING,
3560 defaultValue ? "1" : "0",
3561 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3562 }
3563 currentVersion = 154;
3564 }
3565
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003566 if (currentVersion == 154) {
3567 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3568 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3569 final String oldValue = systemSecureSettings.getSettingLocked(
3570 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3571 if (TextUtils.equals(null, oldValue)) {
3572 final String defaultValue = getContext().getResources().getString(
3573 R.string.def_backup_local_transport_parameters);
3574 if (!TextUtils.isEmpty(defaultValue)) {
3575 systemSecureSettings.insertSettingLocked(
3576 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3577 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3578 }
3579
3580 }
3581 currentVersion = 155;
3582 }
3583
Beverlyda904812018-03-02 09:55:30 -05003584 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003585 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003586 final SettingsState globalSettings = getGlobalSettingsLocked();
3587 final String oldValue = globalSettings.getSettingLocked(
3588 Global.CHARGING_STARTED_SOUND).getValue();
3589 final String oldDefault = getContext().getResources().getString(
3590 R.string.def_wireless_charging_started_sound);
3591 if (TextUtils.equals(null, oldValue)
3592 || TextUtils.equals(oldValue, oldDefault)) {
3593 final String defaultValue = getContext().getResources().getString(
3594 R.string.def_charging_started_sound);
3595 if (!TextUtils.isEmpty(defaultValue)) {
3596 globalSettings.insertSettingLocked(
3597 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3598 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3599 }
3600
3601 }
3602 currentVersion = 156;
3603 }
3604
Beverly09da25f2018-02-26 09:17:07 -05003605 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003606 // Version 157: Set a default value for zen duration,
3607 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003608 final SettingsState globalSettings = getGlobalSettingsLocked();
3609 final Setting currentSetting = globalSettings.getSettingLocked(
3610 Global.ZEN_DURATION);
3611 if (currentSetting.isNull()) {
3612 String defaultZenDuration = Integer.toString(getContext()
3613 .getResources().getInteger(R.integer.def_zen_duration));
3614 globalSettings.insertSettingLocked(
3615 Global.ZEN_DURATION, defaultZenDuration,
3616 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3617 }
Beverly09da25f2018-02-26 09:17:07 -05003618 currentVersion = 157;
3619 }
Annie Mengd069a882018-03-13 15:31:40 +00003620
3621 if (currentVersion == 157) {
3622 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3623 final SettingsState globalSettings = getGlobalSettingsLocked();
3624 final String oldValue = globalSettings.getSettingLocked(
3625 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3626 if (TextUtils.equals(null, oldValue)) {
3627 final String defaultValue = getContext().getResources().getString(
3628 R.string.def_backup_agent_timeout_parameters);
3629 if (!TextUtils.isEmpty(defaultValue)) {
3630 globalSettings.insertSettingLocked(
3631 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3632 null, true,
3633 SettingsState.SYSTEM_PACKAGE_NAME);
3634 }
3635 }
3636 currentVersion = 158;
3637 }
Roshan Pius9c396672018-03-02 14:54:13 -08003638
3639 if (currentVersion == 158) {
3640 // Remove setting that specifies wifi bgscan throttling params
3641 getGlobalSettingsLocked().deleteSettingLocked(
3642 "wifi_scan_background_throttle_interval_ms");
3643 getGlobalSettingsLocked().deleteSettingLocked(
3644 "wifi_scan_background_throttle_package_whitelist");
3645 currentVersion = 159;
3646 }
3647
Pavel Grafovc5c97302018-03-19 13:37:15 +00003648 if (currentVersion == 159) {
3649 // Version 160: Hiding notifications from the lockscreen is only available as
3650 // primary user option, profiles can only make them redacted. If a profile was
3651 // configured to not show lockscreen notifications, ensure that at the very
3652 // least these will be come hidden.
3653 if (mUserManager.isManagedProfile(userId)) {
3654 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3655 Setting showNotifications = secureSettings.getSettingLocked(
3656 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3657 // The default value is "1", check if user has turned it off.
3658 if ("0".equals(showNotifications.getValue())) {
3659 secureSettings.insertSettingLocked(
3660 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3661 null /* tag */, false /* makeDefault */,
3662 SettingsState.SYSTEM_PACKAGE_NAME);
3663 }
3664 // The setting is no longer valid for managed profiles, it should be
3665 // treated as if it was set to "1".
3666 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3667 }
3668 currentVersion = 160;
3669 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003670
3671 if (currentVersion == 160) {
3672 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003673 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003674 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3675 final SettingsState globalSettings = getGlobalSettingsLocked();
3676
3677 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003678 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3679 if (TextUtils.equals(null, oldValue)) {
3680 globalSettings.insertSettingLocked(
3681 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3682 Integer.toString(getContext().getResources().getInteger(
3683 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3684 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3685 }
3686
3687 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003688 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3689 if (TextUtils.equals(null, oldValue)) {
3690 globalSettings.insertSettingLocked(
3691 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3692 Integer.toString(getContext().getResources().getInteger(
3693 R.integer.def_sound_trigger_detection_service_op_timeout)),
3694 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3695 }
3696 currentVersion = 161;
3697 }
3698
Mike Digman55272862018-02-20 14:35:17 -08003699 if (currentVersion == 161) {
3700 // Version 161: Add a gesture for silencing phones
3701 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3702 final Setting currentSetting = secureSettings.getSettingLocked(
3703 Secure.VOLUME_HUSH_GESTURE);
3704 if (currentSetting.isNull()) {
3705 secureSettings.insertSettingLocked(
3706 Secure.VOLUME_HUSH_GESTURE,
3707 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3708 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3709 }
3710
3711 currentVersion = 162;
3712 }
3713
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003714 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003715 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003716 currentVersion = 163;
3717 }
3718
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003719 if (currentVersion == 163) {
3720 // Version 163: Update default value of
3721 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3722 final SettingsState settings = getGlobalSettingsLocked();
3723 final Setting currentSetting = settings.getSettingLocked(
3724 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3725 if (currentSetting.isDefaultFromSystem()) {
3726 settings.insertSettingLocked(
3727 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3728 Integer.toString(getContext().getResources().getInteger(
3729 R.integer
3730 .def_max_sound_trigger_detection_service_ops_per_day)),
3731 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3732 }
3733
3734 currentVersion = 164;
3735 }
3736
Julia Reynolds76bfa602018-04-23 09:38:47 -04003737 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003738 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003739 currentVersion = 165;
3740 }
3741
Beverly301e92a2018-04-27 09:43:05 -04003742 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003743 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3744 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003745 currentVersion = 166;
3746 }
3747
Beverly38fcfd02018-05-18 17:33:40 -04003748 if (currentVersion == 166) {
3749 // Version 166: add default values for hush gesture used and manual ringer
3750 // toggle
3751 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3752 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3753 Secure.HUSH_GESTURE_USED);
3754 if (currentHushUsedSetting.isNull()) {
3755 secureSettings.insertSettingLocked(
3756 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
3757 SettingsState.SYSTEM_PACKAGE_NAME);
3758 }
3759
3760 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
3761 Secure.MANUAL_RINGER_TOGGLE_COUNT);
3762 if (currentRingerToggleCountSetting.isNull()) {
3763 secureSettings.insertSettingLocked(
3764 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
3765 SettingsState.SYSTEM_PACKAGE_NAME);
3766 }
3767 currentVersion = 167;
3768 }
3769
Beverly155c9d22018-05-23 18:03:23 -04003770 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04003771 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
3772 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04003773 currentVersion = 168;
3774 }
3775
Michael Wright0e9eeee2018-05-26 00:31:20 +01003776 if (currentVersion == 168) {
3777 // Version 168: by default, vibrate for phone calls
3778 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3779 final Setting currentSetting = systemSettings.getSettingLocked(
3780 Settings.System.VIBRATE_WHEN_RINGING);
3781 if (currentSetting.isNull()) {
3782 systemSettings.insertSettingLocked(
3783 Settings.System.VIBRATE_WHEN_RINGING,
3784 getContext().getResources().getBoolean(
3785 R.bool.def_vibrate_when_ringing) ? "1" : "0",
3786 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3787 }
3788 currentVersion = 169;
3789 }
3790
Nadav Barf9f115d2018-06-24 10:06:50 +03003791 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04003792 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
3793 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
3794 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03003795
Beverly91d0a632018-07-02 16:45:00 -04003796 final SettingsState globalSettings = getGlobalSettingsLocked();
3797 final Setting globalZenDuration = globalSettings.getSettingLocked(
3798 Global.ZEN_DURATION);
3799
3800 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3801 final Setting secureZenDuration = secureSettings.getSettingLocked(
3802 Secure.ZEN_DURATION);
3803
3804 // ZEN_DURATION
3805 if (!globalZenDuration.isNull()) {
3806 secureSettings.insertSettingLocked(
3807 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
3808 SettingsState.SYSTEM_PACKAGE_NAME);
3809
3810 // set global zen duration setting to null since it's deprecated
3811 globalSettings.insertSettingLocked(
3812 Global.ZEN_DURATION, null, null, true,
3813 SettingsState.SYSTEM_PACKAGE_NAME);
3814 } else if (secureZenDuration.isNull()) {
3815 String defaultZenDuration = Integer.toString(getContext()
3816 .getResources().getInteger(R.integer.def_zen_duration));
3817 secureSettings.insertSettingLocked(
3818 Secure.ZEN_DURATION, defaultZenDuration, null, true,
3819 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03003820 }
Beverly91d0a632018-07-02 16:45:00 -04003821
3822 // SHOW_ZEN_SETTINGS_SUGGESTION
3823 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
3824 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
3825 if (currentShowZenSettingSuggestion.isNull()) {
3826 secureSettings.insertSettingLocked(
3827 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
3828 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3829 }
3830
3831 // ZEN_SETTINGS_UPDATED
3832 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
3833 Secure.ZEN_SETTINGS_UPDATED);
3834 if (currentUpdatedSetting.isNull()) {
3835 secureSettings.insertSettingLocked(
3836 Secure.ZEN_SETTINGS_UPDATED, "0",
3837 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3838 }
3839
3840 // ZEN_SETTINGS_SUGGESTION_VIEWED
3841 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
3842 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
3843 if (currentSettingSuggestionViewed.isNull()) {
3844 secureSettings.insertSettingLocked(
3845 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
3846 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3847 }
3848
Nadav Barf9f115d2018-06-24 10:06:50 +03003849 currentVersion = 170;
3850 }
3851
Beverly91d0a632018-07-02 16:45:00 -04003852 if (currentVersion == 170) {
3853 // Version 170: Set the default value for Secure Settings:
3854 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
3855
3856 final SettingsState globalSettings = getGlobalSettingsLocked();
3857 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3858
3859 // CHARGING_SOUNDS_ENABLED
3860 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
3861 Global.CHARGING_SOUNDS_ENABLED);
3862 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
3863 Secure.CHARGING_SOUNDS_ENABLED);
3864
3865 if (!globalChargingSoundEnabled.isNull()) {
3866 secureSettings.insertSettingLocked(
3867 Secure.CHARGING_SOUNDS_ENABLED,
3868 globalChargingSoundEnabled.getValue(), null, false,
3869 SettingsState.SYSTEM_PACKAGE_NAME);
3870
3871 // set global charging_sounds_enabled setting to null since it's deprecated
3872 globalSettings.insertSettingLocked(
3873 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
3874 SettingsState.SYSTEM_PACKAGE_NAME);
3875 } else if (secureChargingSoundsEnabled.isNull()) {
3876 String defChargingSoundsEnabled = getContext().getResources()
3877 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
3878 secureSettings.insertSettingLocked(
3879 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
3880 true, SettingsState.SYSTEM_PACKAGE_NAME);
3881 }
3882
3883 // CHARGING_VIBRATION_ENABLED
3884 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
3885 Secure.CHARGING_VIBRATION_ENABLED);
3886
3887 if (secureChargingVibrationEnabled.isNull()) {
3888 String defChargingVibrationEnabled = getContext().getResources()
3889 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
3890 secureSettings.insertSettingLocked(
3891 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
3892 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3893 }
3894
3895 currentVersion = 171;
3896 }
3897
Felipe Lemeff355092017-04-03 12:55:02 -07003898 // vXXX: Add new settings above this point.
3899
Dan Sandler71f85e92016-07-20 13:46:05 -04003900 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003901 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003902 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003903 + currentVersion +
3904 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3905 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003906 if (DEBUG) {
3907 throw new RuntimeException("db upgrade error");
3908 }
3909 }
3910
Jeff Brown503cffc2015-03-26 18:08:51 -07003911 // Return the current version.
3912 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003913 }
3914 }
Svet Ganov13701552017-02-23 12:45:17 -08003915
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003916 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3917 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003918 List<String> names = settings.getSettingNamesLocked();
3919 final int nameCount = names.size();
3920 for (int i = 0; i < nameCount; i++) {
3921 String name = names.get(i);
3922 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003923
3924 // In the upgrade case we pretend the call is made from the app
3925 // that made the last change to the setting to properly determine
3926 // whether the call has been made by a system component.
3927 int callingUid = -1;
3928 try {
3929 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3930 } catch (RemoteException e) {
3931 /* ignore - handled below */
3932 }
3933 if (callingUid < 0) {
3934 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3935 continue;
3936 }
3937 try {
3938 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3939 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003940 if (systemSet) {
3941 settings.insertSettingLocked(name, setting.getValue(),
3942 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003943 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3944 // We had a bug where changes by non-system packages were marked
3945 // as system made and as a result set as the default. Therefore, if
3946 // the package changed the setting last is not a system one but the
3947 // setting is marked as its default coming from the system we clear
3948 // the default and clear the system set flag.
3949 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003950 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003951 } catch (IllegalStateException e) {
3952 // If the package goes over its quota during the upgrade, don't
3953 // crash but just log the error as the system does the upgrade.
3954 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3955
Svet Ganov13701552017-02-23 12:45:17 -08003956 }
3957 }
3958 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003959 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003960}