blob: f5d1ccfe378b038100eb3191a0f7b036923e4cb2 [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
Matt Pape25c940d2019-03-26 12:14:33 -070019import static android.os.Process.INVALID_UID;
yuemingw1d13eae2018-01-30 17:27:54 +000020import static android.os.Process.ROOT_UID;
21import static android.os.Process.SHELL_UID;
22import static android.os.Process.SYSTEM_UID;
Winson Chungd9f2fb32019-03-05 11:10:12 -080023import static android.view.WindowManagerPolicyConstants.NAV_BAR_MODE_2BUTTON_OVERLAY;
yuemingw1d13eae2018-01-30 17:27:54 +000024
Svetoslav683914b2015-01-15 14:22:26 -080025import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080026import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070027import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070028import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070029import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070031import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080032import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.ContentValues;
35import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070036import android.content.Intent;
37import android.content.IntentFilter;
Winson Chungd9f2fb32019-03-05 11:10:12 -080038import android.content.om.IOverlayManager;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070040import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080041import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070043import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070044import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070047import android.database.sqlite.SQLiteDatabase;
48import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080049import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040050import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070051import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070052import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080054import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070055import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080056import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070057import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070058import android.os.HandlerThread;
Christopher Tate65fb2e42019-10-11 17:00:23 -070059import android.os.IUserRestrictionsListener;
Svetoslav7e0683b2015-08-03 16:02:52 -070060import android.os.Looper;
61import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070063import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070064import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070065import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070066import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070067import android.os.UserHandle;
68import android.os.UserManager;
Matt Pape1278d1c2018-12-11 13:03:49 -080069import android.provider.DeviceConfig;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010071import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080072import android.provider.Settings.Secure;
Al Sutton91f89d02019-08-16 12:56:57 +010073import android.provider.settings.validators.SystemSettingsValidators;
Al Suttonb0067fb2019-08-16 10:34:46 +010074import android.provider.settings.validators.Validator;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070075import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010076import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080077import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070078import android.util.Slog;
79import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070080import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080081import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040082
Svetoslav683914b2015-01-15 14:22:26 -080083import com.android.internal.annotations.GuardedBy;
84import com.android.internal.content.PackageMonitor;
85import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080086import com.android.providers.settings.SettingsState.Setting;
Ruben Brunk98576cf2016-03-07 18:54:28 -080087import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040088
Irina Dumitrescue3696872019-01-09 16:07:59 +000089import com.google.android.collect.Sets;
90
Neil Fuller3447fb42019-04-08 22:03:14 +010091import libcore.util.HexEncoding;
92
Svetoslav683914b2015-01-15 14:22:26 -080093import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080094import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080096import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080097import java.nio.ByteBuffer;
98import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000099import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -0800100import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700101import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -0800102import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +0000103import java.util.Collection;
Matt Pape6bfc62e2018-11-28 13:16:03 -0800104import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +0000105import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -0800106import java.util.List;
Andre Lago3fa139c2016-08-04 13:53:44 +0100107import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800108import java.util.Set;
109import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000110
Mark Rathjen7599f132017-01-23 14:15:54 -0800111import javax.crypto.Mac;
112import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113
Svetoslav Ganove080da92016-12-21 17:10:35 -0800114
Svetoslav683914b2015-01-15 14:22:26 -0800115/**
116 * <p>
117 * This class is a content provider that publishes the system settings.
118 * It can be accessed via the content provider APIs or via custom call
119 * commands. The latter is a bit faster and is the preferred way to access
120 * the platform settings.
121 * </p>
122 * <p>
123 * There are three settings types, global (with signature level protection
124 * and shared across users), secure (with signature permission level
125 * protection and per user), and system (with dangerous permission level
126 * protection and per user). Global settings are stored under the device owner.
127 * Each of these settings is represented by a {@link
128 * com.android.providers.settings.SettingsState} object mapped to an integer
129 * key derived from the setting type in the most significant bits and user
130 * id in the least significant bits. Settings are synchronously loaded on
131 * instantiation of a SettingsState and asynchronously persisted on mutation.
132 * Settings are stored in the user specific system directory.
133 * </p>
134 * <p>
135 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
136 * and get a warning. Targeting higher API version prohibits this as the
137 * system settings are not a place for apps to save their state. When a package
138 * is removed the settings it added are deleted. Apps cannot delete system
139 * settings added by the platform. System settings values are validated to
140 * ensure the clients do not put bad values. Global and secure settings are
141 * changed only by trusted parties, therefore no validation is performed. Also
142 * there is a limit on the amount of app specific settings that can be added
143 * to prevent unlimited growth of the system process memory footprint.
144 * </p>
145 */
146@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700148 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700149
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700150 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800151
152 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700153
Christopher Tate06efb532012-08-24 15:29:27 -0700154 private static final String TABLE_SYSTEM = "system";
155 private static final String TABLE_SECURE = "secure";
156 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800157
158 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private static final String TABLE_FAVORITES = "favorites";
160 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800161 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
162 private static final String TABLE_BOOKMARKS = "bookmarks";
163 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Svetoslav683914b2015-01-15 14:22:26 -0800165 // The set of removed legacy tables.
166 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700167 static {
Svetoslav683914b2015-01-15 14:22:26 -0800168 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
169 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
170 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
171 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
172 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
173 }
Christopher Tate06efb532012-08-24 15:29:27 -0700174
Svetoslav683914b2015-01-15 14:22:26 -0800175 private static final int MUTATION_OPERATION_INSERT = 1;
176 private static final int MUTATION_OPERATION_DELETE = 2;
177 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800178 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400179
Svetoslav683914b2015-01-15 14:22:26 -0800180 private static final String[] ALL_COLUMNS = new String[] {
181 Settings.NameValueTable._ID,
182 Settings.NameValueTable.NAME,
183 Settings.NameValueTable.VALUE
184 };
185
Makoto Onuki53f0e022017-11-29 13:51:01 -0800186 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
187 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
188 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
189 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700190 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700191
192 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
193 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700194
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800195 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800196 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800197
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700198 // Overlay specified settings whitelisted for Instant Apps
199 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
200 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
201 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
202
203 static {
204 for (String name : Resources.getSystem().getStringArray(
205 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
206 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
207 }
208 for (String name : Resources.getSystem().getStringArray(
209 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
210 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
211 }
212 for (String name : Resources.getSystem().getStringArray(
213 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
214 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
215 }
216 }
217
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800218 // Changes to these global settings are synchronously persisted
219 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
220 static {
221 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
222 }
223
224 // Changes to these secure settings are synchronously persisted
225 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
226 static {
227 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
228 }
229
Svetoslav683914b2015-01-15 14:22:26 -0800230 // Per user secure settings that moved to the for all users global settings.
231 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
232 static {
233 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700234 }
235
Svetoslav683914b2015-01-15 14:22:26 -0800236 // Per user system settings that moved to the for all users global settings.
237 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
238 static {
239 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700240 }
241
Svetoslav683914b2015-01-15 14:22:26 -0800242 // Per user system settings that moved to the per user secure settings.
243 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
244 static {
245 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 }
247
Svetoslav683914b2015-01-15 14:22:26 -0800248 // Per all users global settings that moved to the per user secure settings.
249 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
250 static {
251 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252 }
253
Svetoslav683914b2015-01-15 14:22:26 -0800254 // Per user secure settings that are cloned for the managed profiles of the user.
255 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
256 static {
257 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 }
259
Svetoslav683914b2015-01-15 14:22:26 -0800260 // Per user system settings that are cloned for the managed profiles of the user.
261 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
262 static {
263 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400264 }
265
Andre Lago3fa139c2016-08-04 13:53:44 +0100266 // Per user system settings that are cloned from the profile's parent when a dependency
267 // in {@link Settings.Secure} is set to "1".
268 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
269 static {
270 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
271 }
272
Svetoslav683914b2015-01-15 14:22:26 -0800273 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700274
Svetoslav683914b2015-01-15 14:22:26 -0800275 @GuardedBy("mLock")
276 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700277
Svet Ganova8f90262016-05-10 08:44:48 -0700278 @GuardedBy("mLock")
279 private HandlerThread mHandlerThread;
280
Makoto Onuki73360ab2017-03-17 11:50:13 -0700281 @GuardedBy("mLock")
282 private Handler mHandler;
283
Svetoslav7ec28e82015-05-20 17:01:10 -0700284 // We have to call in the user manager with no lock held,
285 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800286
Svetoslav7ec28e82015-05-20 17:01:10 -0700287 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700288 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700289
Svet Ganov53a441c2016-04-19 19:38:00 -0700290 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800291 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700292 }
293
294 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800295 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700296 }
297
298 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800299 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700300 }
301
302 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800303 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 }
305
306 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800307 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700308 }
309
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 @Override
311 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800312 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000313
Svetoslav683914b2015-01-15 14:22:26 -0800314 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700315 mUserManager = UserManager.get(getContext());
316 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700317 mHandlerThread = new HandlerThread(LOG_TAG,
318 Process.THREAD_PRIORITY_BACKGROUND);
319 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700320 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800321 mSettingsRegistry = new SettingsRegistry();
322 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700323 mHandler.post(() -> {
324 registerBroadcastReceivers();
325 startWatchingUserRestrictionChanges();
326 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700327 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800328 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700329 return true;
330 }
331
Svetoslav683914b2015-01-15 14:22:26 -0800332 @Override
333 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700334 final int requestingUserId = getRequestingUserId(args);
335 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700336 case Settings.CALL_METHOD_GET_CONFIG: {
337 Setting setting = getConfigSetting(name);
338 return packageValueForCallResult(setting, isTrackingGeneration(args));
339 }
340
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 case Settings.CALL_METHOD_GET_GLOBAL: {
342 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700343 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800344 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700345
346 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800347 Setting setting = getSecureSetting(name, requestingUserId,
348 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700349 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700350 }
351
352 case Settings.CALL_METHOD_GET_SYSTEM: {
353 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700354 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700355 }
356
Matt Pape1b31a332018-10-17 09:58:28 -0700357 case Settings.CALL_METHOD_PUT_CONFIG: {
358 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700359 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800360 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700361 break;
362 }
363
Svetoslav7ec28e82015-05-20 17:01:10 -0700364 case Settings.CALL_METHOD_PUT_GLOBAL: {
365 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800366 String tag = getSettingTag(args);
367 final boolean makeDefault = getSettingMakeDefault(args);
368 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700369 break;
370 }
371
372 case Settings.CALL_METHOD_PUT_SECURE: {
373 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800374 String tag = getSettingTag(args);
375 final boolean makeDefault = getSettingMakeDefault(args);
376 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700377 break;
378 }
379
380 case Settings.CALL_METHOD_PUT_SYSTEM: {
381 String value = getSettingValue(args);
382 insertSystemSetting(name, value, requestingUserId);
383 break;
384 }
385
Matt Pape1b31a332018-10-17 09:58:28 -0700386 case Settings.CALL_METHOD_RESET_CONFIG: {
387 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800388 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800389 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700390 break;
391 }
392
Svetoslav Ganove080da92016-12-21 17:10:35 -0800393 case Settings.CALL_METHOD_RESET_GLOBAL: {
394 final int mode = getResetModeEnforcingPermission(args);
395 String tag = getSettingTag(args);
396 resetGlobalSetting(requestingUserId, mode, tag);
397 break;
398 }
399
400 case Settings.CALL_METHOD_RESET_SECURE: {
401 final int mode = getResetModeEnforcingPermission(args);
402 String tag = getSettingTag(args);
403 resetSecureSetting(requestingUserId, mode, tag);
404 break;
405 }
406
Matt Pape6bfc62e2018-11-28 13:16:03 -0800407 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800408 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800409 Bundle result = new Bundle();
410 result.putInt(RESULT_ROWS_DELETED, rows);
411 return result;
412 }
413
414 case Settings.CALL_METHOD_DELETE_GLOBAL: {
415 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
416 Bundle result = new Bundle();
417 result.putInt(RESULT_ROWS_DELETED, rows);
418 return result;
419 }
420
Matt Pape6bfc62e2018-11-28 13:16:03 -0800421 case Settings.CALL_METHOD_DELETE_SECURE: {
422 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
423 Bundle result = new Bundle();
424 result.putInt(RESULT_ROWS_DELETED, rows);
425 return result;
426 }
427
428 case Settings.CALL_METHOD_DELETE_SYSTEM: {
429 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
430 Bundle result = new Bundle();
431 result.putInt(RESULT_ROWS_DELETED, rows);
432 return result;
433 }
434
435 case Settings.CALL_METHOD_LIST_CONFIG: {
436 String prefix = getSettingPrefix(args);
Matt Pape793b15c2019-10-07 13:17:20 -0700437 return packageValuesForCallResult(getAllConfigFlags(prefix),
438 isTrackingGeneration(args));
Matt Pape6bfc62e2018-11-28 13:16:03 -0800439 }
440
441 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800442 Bundle result = new Bundle();
443 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800444 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800445 return result;
446 }
447
448 case Settings.CALL_METHOD_LIST_SECURE: {
449 Bundle result = new Bundle();
450 result.putStringArrayList(RESULT_SETTINGS_LIST,
451 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
452 return result;
453 }
454
Matt Pape6bfc62e2018-11-28 13:16:03 -0800455 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800456 Bundle result = new Bundle();
457 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800458 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800459 return result;
460 }
461
Svetoslav7ec28e82015-05-20 17:01:10 -0700462 default: {
463 Slog.w(LOG_TAG, "call() with invalid method: " + method);
464 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700465 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700466
Christopher Tate06efb532012-08-24 15:29:27 -0700467 return null;
468 }
469
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800470 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800471 public String getType(Uri uri) {
472 Arguments args = new Arguments(uri, null, null, true);
473 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700474 return "vnd.android.cursor.dir/" + args.table;
475 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700476 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700477 }
478 }
479
480 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800481 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
482 String order) {
483 if (DEBUG) {
484 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700485 }
486
Svetoslav683914b2015-01-15 14:22:26 -0800487 Arguments args = new Arguments(uri, where, whereArgs, true);
488 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489
Svetoslav683914b2015-01-15 14:22:26 -0800490 // If a legacy table that is gone, done.
491 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
492 return new MatrixCursor(normalizedProjection, 0);
493 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700494
Svetoslav7ec28e82015-05-20 17:01:10 -0700495 switch (args.table) {
496 case TABLE_GLOBAL: {
497 if (args.name != null) {
498 Setting setting = getGlobalSetting(args.name);
499 return packageSettingForQuery(setting, normalizedProjection);
500 } else {
501 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700502 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700503 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700504
Svetoslav7ec28e82015-05-20 17:01:10 -0700505 case TABLE_SECURE: {
506 final int userId = UserHandle.getCallingUserId();
507 if (args.name != null) {
508 Setting setting = getSecureSetting(args.name, userId);
509 return packageSettingForQuery(setting, normalizedProjection);
510 } else {
511 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800512 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700513 }
Svetoslav683914b2015-01-15 14:22:26 -0800514
Svetoslav7ec28e82015-05-20 17:01:10 -0700515 case TABLE_SYSTEM: {
516 final int userId = UserHandle.getCallingUserId();
517 if (args.name != null) {
518 Setting setting = getSystemSetting(args.name, userId);
519 return packageSettingForQuery(setting, normalizedProjection);
520 } else {
521 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800522 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700523 }
Svetoslav683914b2015-01-15 14:22:26 -0800524
Svetoslav7ec28e82015-05-20 17:01:10 -0700525 default: {
526 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700527 }
528 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700529 }
530
Nicholas Sauer72500532018-11-21 10:30:58 -0800531 private ArrayList<String> buildSettingsList(Cursor cursor) {
532 final ArrayList<String> lines = new ArrayList<String>();
533 try {
534 while (cursor != null && cursor.moveToNext()) {
535 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
536 }
537 } finally {
538 if (cursor != null) {
539 cursor.close();
540 }
541 }
542 return lines;
543 }
544
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700545 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800546 public Uri insert(Uri uri, ContentValues values) {
547 if (DEBUG) {
548 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700549 }
550
Svetoslav683914b2015-01-15 14:22:26 -0800551 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700552
Svetoslav683914b2015-01-15 14:22:26 -0800553 // If a legacy table that is gone, done.
554 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 return null;
556 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557
Svetoslav683914b2015-01-15 14:22:26 -0800558 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700559 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800560 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700561 }
562
Svetoslav683914b2015-01-15 14:22:26 -0800563 String value = values.getAsString(Settings.Secure.VALUE);
564
Svetoslav7ec28e82015-05-20 17:01:10 -0700565 switch (table) {
566 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800567 if (insertGlobalSetting(name, value, null, false,
568 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700569 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700570 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700571 } break;
572
573 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800574 if (insertSecureSetting(name, value, null, false,
575 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700576 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
577 }
578 } break;
579
580 case TABLE_SYSTEM: {
581 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
582 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
583 }
584 } break;
585
586 default: {
587 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700588 }
589 }
590
Svetoslav683914b2015-01-15 14:22:26 -0800591 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700592 }
593
594 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800595 public int bulkInsert(Uri uri, ContentValues[] allValues) {
596 if (DEBUG) {
597 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700599
Svetoslav683914b2015-01-15 14:22:26 -0800600 int insertionCount = 0;
601 final int valuesCount = allValues.length;
602 for (int i = 0; i < valuesCount; i++) {
603 ContentValues values = allValues[i];
604 if (insert(uri, values) != null) {
605 insertionCount++;
606 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700607 }
Svetoslav683914b2015-01-15 14:22:26 -0800608
609 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700610 }
611
612 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800613 public int delete(Uri uri, String where, String[] whereArgs) {
614 if (DEBUG) {
615 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700617
Svetoslav683914b2015-01-15 14:22:26 -0800618 Arguments args = new Arguments(uri, where, whereArgs, false);
619
620 // If a legacy table that is gone, done.
621 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
622 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700623 }
Svetoslav683914b2015-01-15 14:22:26 -0800624
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700625 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800626 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700627 }
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();
Svet Ganov53a441c2016-04-19 19:38:00 -0700632 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700633 }
Svetoslav683914b2015-01-15 14:22:26 -0800634
Svetoslav7ec28e82015-05-20 17:01:10 -0700635 case TABLE_SECURE: {
636 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700637 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700638 }
Svetoslav683914b2015-01-15 14:22:26 -0800639
Svetoslav7ec28e82015-05-20 17:01:10 -0700640 case TABLE_SYSTEM: {
641 final int userId = UserHandle.getCallingUserId();
642 return deleteSystemSetting(args.name, userId) ? 1 : 0;
643 }
644
645 default: {
646 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800647 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700648 }
Svetoslav683914b2015-01-15 14:22:26 -0800649 }
650
651 @Override
652 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
653 if (DEBUG) {
654 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700655 }
Svetoslav683914b2015-01-15 14:22:26 -0800656
657 Arguments args = new Arguments(uri, where, whereArgs, false);
658
659 // If a legacy table that is gone, done.
660 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
661 return 0;
662 }
663
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700664 String name = values.getAsString(Settings.Secure.NAME);
665 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800666 return 0;
667 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700668 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800669
Svetoslav7ec28e82015-05-20 17:01:10 -0700670 switch (args.table) {
671 case TABLE_GLOBAL: {
672 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800673 return updateGlobalSetting(args.name, value, null, false,
674 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700675 }
Svetoslav683914b2015-01-15 14:22:26 -0800676
Svetoslav7ec28e82015-05-20 17:01:10 -0700677 case TABLE_SECURE: {
678 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800679 return updateSecureSetting(args.name, value, null, false,
680 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700681 }
Svetoslav683914b2015-01-15 14:22:26 -0800682
Svetoslav7ec28e82015-05-20 17:01:10 -0700683 case TABLE_SYSTEM: {
684 final int userId = UserHandle.getCallingUserId();
685 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
686 }
Svetoslav683914b2015-01-15 14:22:26 -0800687
Svetoslav7ec28e82015-05-20 17:01:10 -0700688 default: {
689 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800690 }
691 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700692 }
693
694 @Override
695 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100696 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
697 if (userId != UserHandle.getCallingUserId()) {
698 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
699 "Access files from the settings of another user");
700 }
701 uri = ContentProvider.getUriWithoutUserId(uri);
702
Andre Lago3fa139c2016-08-04 13:53:44 +0100703 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700704 final String cacheName;
705 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100706 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700707 cacheName = Settings.System.RINGTONE_CACHE;
708 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100709 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700710 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
711 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100712 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700713 cacheName = Settings.System.ALARM_ALERT_CACHE;
714 } else {
715 throw new FileNotFoundException("Direct file access no longer supported; "
716 + "ringtone playback is available through android.media.Ringtone");
717 }
718
Andre Lago3fa139c2016-08-04 13:53:44 +0100719 int actualCacheOwner;
720 // Redirect cache to parent if ringtone setting is owned by profile parent
721 synchronized (mLock) {
722 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
723 cacheRingtoneSetting);
724 }
725 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700726 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
727 }
728
729 private File getRingtoneCacheDir(int userId) {
730 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
731 cacheDir.mkdir();
732 SELinux.restorecon(cacheDir);
733 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700734 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800735
Eugene Suslad72c3972016-12-27 15:49:30 -0800736 /**
737 * Dump all settings as a proto buf.
738 *
739 * @param fd The file to dump to
740 */
741 void dumpProto(@NonNull FileDescriptor fd) {
742 ProtoOutputStream proto = new ProtoOutputStream(fd);
743
744 synchronized (mLock) {
745 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800746 }
747
748 proto.flush();
749 }
750
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700751 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800752 synchronized (mLock) {
753 final long identity = Binder.clearCallingIdentity();
754 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700755 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800756 final int userCount = users.size();
757 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700758 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800759 }
760 } finally {
761 Binder.restoreCallingIdentity(identity);
762 }
763 }
764 }
765
Andreas Gampeb58893072018-09-05 16:52:31 -0700766 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700767 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700768 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700769 pw.println("CONFIG SETTINGS (user " + userId + ")");
770 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
771 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
772 if (configSettings != null) {
773 dumpSettingsLocked(configSettings, pw);
774 pw.println();
775 configSettings.dumpHistoricalOperations(pw);
776 }
777
Svetoslavb505ccc2015-02-17 12:41:04 -0800778 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700779 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
780 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700781 if (globalSettings != null) {
782 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800783 pw.println();
784 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700785 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800786 }
787
788 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700789 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
790 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700791 if (secureSettings != null) {
792 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800793 pw.println();
794 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700795 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700796
Svetoslavb505ccc2015-02-17 12:41:04 -0800797 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700798 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
799 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700800 if (systemSettings != null) {
801 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800802 pw.println();
803 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700804 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800805 }
806
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700807 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
808 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800809
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700810 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800811
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700812 for (int i = 0; i < nameCount; i++) {
813 String name = names.get(i);
814 Setting setting = settingsState.getSettingLocked(name);
815 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
816 pw.print(" name:"); pw.print(toDumpString(name));
817 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800818 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700819 }
820 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800821 if (setting.getDefaultValue() != null) {
822 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800823 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800824 }
825 if (setting.getTag() != null) {
826 pw.print(" tag:"); pw.print(setting.getTag());
827 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800828 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700829 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800830 }
831
Svetoslav7e0683b2015-08-03 16:02:52 -0700832 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700833 if (s != null) {
834 return s;
835 }
836 return "{null}";
837 }
838
Svetoslav683914b2015-01-15 14:22:26 -0800839 private void registerBroadcastReceivers() {
840 IntentFilter userFilter = new IntentFilter();
841 userFilter.addAction(Intent.ACTION_USER_REMOVED);
842 userFilter.addAction(Intent.ACTION_USER_STOPPED);
843
844 getContext().registerReceiver(new BroadcastReceiver() {
845 @Override
846 public void onReceive(Context context, Intent intent) {
847 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700848 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800849
850 switch (intent.getAction()) {
851 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700852 synchronized (mLock) {
853 mSettingsRegistry.removeUserStateLocked(userId, true);
854 }
Svetoslav683914b2015-01-15 14:22:26 -0800855 } break;
856
857 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700858 synchronized (mLock) {
859 mSettingsRegistry.removeUserStateLocked(userId, false);
860 }
Svetoslav683914b2015-01-15 14:22:26 -0800861 } break;
862 }
863 }
864 }, userFilter);
865
866 PackageMonitor monitor = new PackageMonitor() {
867 @Override
868 public void onPackageRemoved(String packageName, int uid) {
869 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100870 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800871 UserHandle.getUserId(uid));
872 }
873 }
Mark Rathjend891f012017-01-19 04:10:37 +0000874
875 @Override
876 public void onUidRemoved(int uid) {
877 synchronized (mLock) {
878 mSettingsRegistry.onUidRemovedLocked(uid);
879 }
880 }
Zimuzoc56192c2018-07-25 10:40:01 +0100881
882 @Override
883 public void onPackageDataCleared(String packageName, int uid) {
884 synchronized (mLock) {
885 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
886 UserHandle.getUserId(uid));
887 }
888 }
Svetoslav683914b2015-01-15 14:22:26 -0800889 };
890
891 // package changes
892 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
893 UserHandle.ALL, true);
894 }
895
Svet Ganov53a441c2016-04-19 19:38:00 -0700896 private void startWatchingUserRestrictionChanges() {
897 // TODO: The current design of settings looking different based on user restrictions
898 // should be reworked to keep them separate and system code should check the setting
899 // first followed by checking the user restriction before performing an operation.
Christopher Tate65fb2e42019-10-11 17:00:23 -0700900 IUserRestrictionsListener listener = new IUserRestrictionsListener.Stub() {
901 @Override
902 public void onUserRestrictionsChanged(int userId,
903 Bundle newRestrictions, Bundle prevRestrictions) {
904 Set<String> changedRestrictions =
905 getRestrictionDiff(prevRestrictions, newRestrictions);
906 // We are changing the settings affected by restrictions to their current
907 // value with a forced update to ensure that all cross profile dependencies
908 // are taken into account. Also make sure the settings update to.. the same
909 // value passes the security checks, so clear binder calling id.
910 if (changedRestrictions.contains(UserManager.DISALLOW_SHARE_LOCATION)) {
911 final long identity = Binder.clearCallingIdentity();
912 try {
913 synchronized (mLock) {
914 Setting setting = getSecureSetting(
915 Settings.Secure.LOCATION_MODE, userId);
916 updateSecureSetting(Settings.Secure.LOCATION_MODE,
917 setting != null ? setting.getValue() : null, null,
918 true, userId, true);
919 setting = getSecureSetting(
920 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
921 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
922 setting != null ? setting.getValue() : null, null,
923 true, userId, true);
924 }
925 } finally {
926 Binder.restoreCallingIdentity(identity);
Svet Ganov53a441c2016-04-19 19:38:00 -0700927 }
Christopher Tate65fb2e42019-10-11 17:00:23 -0700928 }
929 if (changedRestrictions.contains(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
930 || changedRestrictions.contains(
931 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
932 final long identity = Binder.clearCallingIdentity();
933 try {
934 synchronized (mLock) {
935 Setting setting = getGlobalSetting(
936 Settings.Global.INSTALL_NON_MARKET_APPS);
937 String value = setting != null ? setting.getValue() : null;
938 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
939 value, null, true, userId, true);
940 }
941 } finally {
942 Binder.restoreCallingIdentity(identity);
943 }
944 }
945 if (changedRestrictions.contains(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
946 final long identity = Binder.clearCallingIdentity();
947 try {
948 synchronized (mLock) {
949 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
950 String value = setting != null ? setting.getValue() : null;
951 updateGlobalSetting(Settings.Global.ADB_ENABLED,
952 value, null, true, userId, true);
953 }
954 } finally {
955 Binder.restoreCallingIdentity(identity);
956 }
957 }
958 if (changedRestrictions.contains(UserManager.ENSURE_VERIFY_APPS)) {
959 final long identity = Binder.clearCallingIdentity();
960 try {
961 synchronized (mLock) {
962 Setting enable = getGlobalSetting(
963 Settings.Global.PACKAGE_VERIFIER_ENABLE);
964 String enableValue = enable != null ? enable.getValue() : null;
965 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
966 enableValue, null, true, userId, true);
967 Setting include = getGlobalSetting(
968 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
969 String includeValue = include != null ? include.getValue() : null;
970 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
971 includeValue, null, true, userId, true);
972 }
973 } finally {
974 Binder.restoreCallingIdentity(identity);
975 }
976 }
977 if (changedRestrictions.contains(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
978 final long identity = Binder.clearCallingIdentity();
979 try {
980 synchronized (mLock) {
981 Setting setting = getGlobalSetting(
982 Settings.Global.PREFERRED_NETWORK_MODE);
983 String value = setting != null ? setting.getValue() : null;
984 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
985 value, null, true, userId, true);
986 }
987 } finally {
988 Binder.restoreCallingIdentity(identity);
989 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700990 }
991 }
Christopher Tate65fb2e42019-10-11 17:00:23 -0700992 };
993 mUserManager.addUserRestrictionsListener(listener);
Svet Ganov53a441c2016-04-19 19:38:00 -0700994 }
995
Irina Dumitrescue3696872019-01-09 16:07:59 +0000996 private static Set<String> getRestrictionDiff(Bundle prevRestrictions, Bundle newRestrictions) {
997 Set<String> restrictionNames = Sets.newArraySet();
998 restrictionNames.addAll(prevRestrictions.keySet());
999 restrictionNames.addAll(newRestrictions.keySet());
1000 Set<String> diff = Sets.newArraySet();
1001 for (String restrictionName : restrictionNames) {
1002 if (prevRestrictions.getBoolean(restrictionName) != newRestrictions.getBoolean(
1003 restrictionName)) {
1004 diff.add(restrictionName);
1005 }
1006 }
1007 return diff;
1008 }
1009
Matt Pape1b31a332018-10-17 09:58:28 -07001010 private Setting getConfigSetting(String name) {
1011 if (DEBUG) {
1012 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1013 }
1014
Stanislav Zholnin55799502019-03-08 14:54:55 +00001015 DeviceConfig.enforceReadPermission(getContext(), /*namespace=*/name.split("/")[0]);
Matt Pape1b31a332018-10-17 09:58:28 -07001016
1017 // Get the value.
1018 synchronized (mLock) {
1019 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1020 UserHandle.USER_SYSTEM, name);
1021 }
1022 }
1023
Matt Papec1323dc2018-12-11 12:32:42 -08001024 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001025 if (DEBUG) {
1026 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001027 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001028 }
Matt Papec1323dc2018-12-11 12:32:42 -08001029 return mutateConfigSetting(name, value, null, makeDefault,
1030 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001031 }
1032
Matt Papec1323dc2018-12-11 12:32:42 -08001033 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001034 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001035 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001036 }
Matt Papec1323dc2018-12-11 12:32:42 -08001037 return mutateConfigSetting(name, null, null, false,
1038 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001039 }
1040
Matt Papec1323dc2018-12-11 12:32:42 -08001041 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001042 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001043 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001044 }
Matt Papec1323dc2018-12-11 12:32:42 -08001045 mutateConfigSetting(null, null, prefix, false,
1046 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001047 }
1048
Matt Pape6bfc62e2018-11-28 13:16:03 -08001049 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001050 boolean makeDefault, int operation, int mode) {
Stanislav Zholnin5a25a842019-03-13 14:43:26 +00001051 enforceWritePermission(Manifest.permission.WRITE_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001052
Matt Pape1b31a332018-10-17 09:58:28 -07001053 // Perform the mutation.
1054 synchronized (mLock) {
1055 switch (operation) {
1056 case MUTATION_OPERATION_INSERT: {
1057 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001058 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001059 resolveCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001060 }
1061
Matt Pape6bfc62e2018-11-28 13:16:03 -08001062 case MUTATION_OPERATION_DELETE: {
1063 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001064 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001065 }
1066
Matt Pape1b31a332018-10-17 09:58:28 -07001067 case MUTATION_OPERATION_RESET: {
1068 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001069 UserHandle.USER_SYSTEM, resolveCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001070 } return true;
1071 }
1072 }
1073
1074 return false;
1075 }
1076
Matt Pape793b15c2019-10-07 13:17:20 -07001077 private HashMap<String, String> getAllConfigFlags(@Nullable String prefix) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001078 if (DEBUG) {
1079 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1080 }
1081
Matt Pape91beb9c2019-10-17 15:20:34 -07001082 DeviceConfig.enforceReadPermission(getContext(),
1083 prefix != null ? prefix.split("/")[0] : null);
1084
Matt Pape6bfc62e2018-11-28 13:16:03 -08001085 synchronized (mLock) {
1086 // Get the settings.
1087 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1088 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001089 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1090 UserHandle.USER_SYSTEM);
1091
1092 final int nameCount = names.size();
Matt Pape793b15c2019-10-07 13:17:20 -07001093 HashMap<String, String> flagsToValues = new HashMap<>(names.size());
Matt Pape6bfc62e2018-11-28 13:16:03 -08001094
1095 for (int i = 0; i < nameCount; i++) {
1096 String name = names.get(i);
1097 Setting setting = settingsState.getSettingLocked(name);
1098 if (prefix == null || setting.getName().startsWith(prefix)) {
1099 flagsToValues.put(setting.getName(), setting.getValue());
1100 }
1101 }
1102
1103 return flagsToValues;
1104 }
1105 }
1106
Svetoslav7ec28e82015-05-20 17:01:10 -07001107 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001108 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001109 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001110 }
1111
Svetoslav7ec28e82015-05-20 17:01:10 -07001112 synchronized (mLock) {
1113 // Get the settings.
1114 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001115 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001116
Chad Brubaker97bccee2017-01-05 15:51:41 -08001117 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1118 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001119
Svetoslav7ec28e82015-05-20 17:01:10 -07001120 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001121
Svetoslav7ec28e82015-05-20 17:01:10 -07001122 String[] normalizedProjection = normalizeProjection(projection);
1123 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001124
Svetoslav7ec28e82015-05-20 17:01:10 -07001125 // Anyone can get the global settings, so no security checks.
1126 for (int i = 0; i < nameCount; i++) {
1127 String name = names.get(i);
1128 Setting setting = settingsState.getSettingLocked(name);
1129 appendSettingToCursor(result, setting);
1130 }
1131
1132 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001133 }
Svetoslav683914b2015-01-15 14:22:26 -08001134 }
1135
Svetoslav7ec28e82015-05-20 17:01:10 -07001136 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001137 if (DEBUG) {
1138 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1139 }
1140
Chad Brubakera6830e72017-04-28 17:34:36 -07001141 // Ensure the caller can access the setting.
1142 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1143
Svetoslav683914b2015-01-15 14:22:26 -08001144 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001145 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001146 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001147 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001148 }
Svetoslav683914b2015-01-15 14:22:26 -08001149 }
1150
Svetoslav Ganove080da92016-12-21 17:10:35 -08001151 private boolean updateGlobalSetting(String name, String value, String tag,
1152 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001153 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001154 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1155 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1156 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001157 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001158 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1159 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001160 }
1161
Svetoslav Ganove080da92016-12-21 17:10:35 -08001162 private boolean insertGlobalSetting(String name, String value, String tag,
1163 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001164 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001165 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1166 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1167 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001168 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001169 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1170 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001171 }
1172
Svet Ganov53a441c2016-04-19 19:38:00 -07001173 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001174 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001175 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1176 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001177 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001178 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1179 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001180 }
1181
Svetoslav Ganove080da92016-12-21 17:10:35 -08001182 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1183 if (DEBUG) {
1184 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1185 + mode + ", " + tag + ")");
1186 }
1187 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1188 MUTATION_OPERATION_RESET, false, mode);
1189 }
1190
Christopher Tate65fb2e42019-10-11 17:00:23 -07001191 private boolean isSettingRestrictedForUser(String name, int userId,
1192 String value, int callerUid) {
1193 final long oldId = Binder.clearCallingIdentity();
1194 try {
1195 return (name != null
1196 && mUserManager.isSettingRestrictedForUser(name, userId, value, callerUid));
1197 } finally {
1198 Binder.restoreCallingIdentity(oldId);
1199 }
1200 }
1201
Svetoslav Ganove080da92016-12-21 17:10:35 -08001202 private boolean mutateGlobalSetting(String name, String value, String tag,
1203 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1204 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001205 // Make sure the caller can change the settings - treated as secure.
1206 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1207
Svetoslav683914b2015-01-15 14:22:26 -08001208 // Resolve the userId on whose behalf the call is made.
1209 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1210
Makoto Onuki28da2e32015-11-20 11:30:44 -08001211 // If this is a setting that is currently restricted for this user, do not allow
1212 // unrestricting changes.
Christopher Tate65fb2e42019-10-11 17:00:23 -07001213 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001214 return false;
1215 }
1216
1217 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001218 synchronized (mLock) {
1219 switch (operation) {
1220 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001221 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1222 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001223 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001224 }
Svetoslav683914b2015-01-15 14:22:26 -08001225
Svetoslav7ec28e82015-05-20 17:01:10 -07001226 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001227 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001228 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001229 }
Svetoslav683914b2015-01-15 14:22:26 -08001230
Svetoslav7ec28e82015-05-20 17:01:10 -07001231 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001232 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1233 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001234 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001235 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001236
1237 case MUTATION_OPERATION_RESET: {
1238 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1239 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1240 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001241 }
1242 }
1243
1244 return false;
1245 }
1246
Christopher Tateb218e762017-04-05 16:34:07 -07001247 private PackageInfo getCallingPackageInfo(int userId) {
1248 try {
1249 return mPackageManager.getPackageInfo(getCallingPackage(),
1250 PackageManager.GET_SIGNATURES, userId);
1251 } catch (RemoteException e) {
1252 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1253 }
1254 }
1255
Svetoslav7ec28e82015-05-20 17:01:10 -07001256 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001257 if (DEBUG) {
1258 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1259 }
1260
1261 // Resolve the userId on whose behalf the call is made.
1262 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1263
Christopher Tateb218e762017-04-05 16:34:07 -07001264 // The relevant "calling package" userId will be the owning userId for some
1265 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1266 // up front who the effective "new SSAID" user ID for that settings name will be.
1267 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1268 Settings.Secure.ANDROID_ID);
1269 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1270
Svetoslav7ec28e82015-05-20 17:01:10 -07001271 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001272 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001273
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001275
Svetoslav7ec28e82015-05-20 17:01:10 -07001276 String[] normalizedProjection = normalizeProjection(projection);
1277 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001278
Svetoslav7ec28e82015-05-20 17:01:10 -07001279 for (int i = 0; i < nameCount; i++) {
1280 String name = names.get(i);
1281 // Determine the owning user as some profile settings are cloned from the parent.
1282 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1283 name);
Svetoslav683914b2015-01-15 14:22:26 -08001284
Alex Klyubin1991f572017-03-03 14:08:36 -08001285 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1286 // This caller is not permitted to access this setting. Pretend the setting
1287 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001288 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001289 }
Svetoslav683914b2015-01-15 14:22:26 -08001290
Mark Rathjen7599f132017-01-23 14:15:54 -08001291 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001292 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1293 final Setting setting;
1294 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001295 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001296 } else {
1297 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1298 name);
1299 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001300 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001301 }
1302
Svetoslav7ec28e82015-05-20 17:01:10 -07001303 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001304 }
Svetoslav683914b2015-01-15 14:22:26 -08001305 }
1306
Svetoslav7ec28e82015-05-20 17:01:10 -07001307 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001308 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1309 }
1310
1311 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001312 if (DEBUG) {
1313 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1314 }
1315
1316 // Resolve the userId on whose behalf the call is made.
1317 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1318
Chad Brubakera6830e72017-04-28 17:34:36 -07001319 // Ensure the caller can access the setting.
1320 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1321
Svetoslav683914b2015-01-15 14:22:26 -08001322 // Determine the owning user as some profile settings are cloned from the parent.
1323 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1324
Alex Klyubin1991f572017-03-03 14:08:36 -08001325 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1326 // This caller is not permitted to access this setting. Pretend the setting doesn't
1327 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001328 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1329 owningUserId);
1330 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001331 }
1332
Christopher Tateb218e762017-04-05 16:34:07 -07001333 // As of Android O, the SSAID is read from an app-specific entry in table
1334 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1335 if (isNewSsaidSetting(name)) {
1336 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1337 synchronized (mLock) {
1338 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001339 }
Christopher Tateb218e762017-04-05 16:34:07 -07001340 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001341 if (enableOverride) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001342 if (Secure.LOCATION_MODE.equals(name)) {
1343 final Setting overridden = getLocationModeSetting(owningUserId);
Makoto Onuki0000d322017-11-28 16:31:47 -08001344 if (overridden != null) {
1345 return overridden;
1346 }
1347 }
1348 }
Mark Rathjend891f012017-01-19 04:10:37 +00001349
Christopher Tateb218e762017-04-05 16:34:07 -07001350 // Not the SSAID; do a straight lookup
1351 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001352 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001353 owningUserId, name);
1354 }
Svetoslav683914b2015-01-15 14:22:26 -08001355 }
1356
Mark Rathjend891f012017-01-19 04:10:37 +00001357 private boolean isNewSsaidSetting(String name) {
1358 return Settings.Secure.ANDROID_ID.equals(name)
1359 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1360 }
1361
Andreas Gampeb58893072018-09-05 16:52:31 -07001362 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001363 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001364 // Get uid of caller (key) used to store ssaid value
1365 String name = Integer.toString(
1366 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1367
1368 if (DEBUG) {
1369 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1370 }
1371
1372 // Retrieve the ssaid from the table if present.
1373 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1374 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001375 // If the app is an Instant App use its stored SSAID instead of our own.
1376 final String instantSsaid;
1377 final long token = Binder.clearCallingIdentity();
1378 try {
1379 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1380 owningUserId);
1381 } catch (RemoteException e) {
1382 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1383 return null;
1384 } finally {
1385 Binder.restoreCallingIdentity(token);
1386 }
Svet Ganov96c99462017-05-05 14:27:13 -07001387
1388 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1389 SETTINGS_TYPE_SSAID, owningUserId);
1390
Chad Brubaker0d277a72017-04-12 16:56:53 -07001391 if (instantSsaid != null) {
1392 // Use the stored value if it is still valid.
1393 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001394 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001395 }
1396 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001397 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1398 true, callingPkg.packageName);
1399 if (!success) {
1400 throw new IllegalStateException("Failed to update instant app android id");
1401 }
Svet Ganov96c99462017-05-05 14:27:13 -07001402 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1403 owningUserId, name);
1404 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001405 }
Mark Rathjend891f012017-01-19 04:10:37 +00001406
1407 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001408 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001409 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1410 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001411 }
1412
Svet Ganov96c99462017-05-05 14:27:13 -07001413 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1414 }
1415
1416 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1417 // SSAID settings are located in a dedicated table for internal bookkeeping
1418 // but for the world they reside in the secure table, so adjust the key here.
1419 // We have a special name when looking it up but want the world to see it as
1420 // "android_id".
1421 if (ssaidSetting != null) {
1422 return settingsState.new Setting(ssaidSetting) {
1423 @Override
1424 public int getKey() {
1425 final int userId = getUserIdFromKey(super.getKey());
1426 return makeKey(SETTINGS_TYPE_SECURE, userId);
1427 }
1428
1429 @Override
1430 public String getName() {
1431 return Settings.Secure.ANDROID_ID;
1432 }
1433 };
1434 }
1435 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001436 }
1437
Kweku Adams5e0052b2019-02-22 15:17:52 -08001438 private Setting getLocationModeSetting(int owningUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001439 synchronized (mLock) {
1440 final Setting setting = getGlobalSetting(
1441 Global.LOCATION_GLOBAL_KILL_SWITCH);
1442 if (!"1".equals(setting.getValue())) {
1443 return null;
1444 }
1445 // Global kill-switch is enabled. Return an empty value.
1446 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1447 SETTINGS_TYPE_SECURE, owningUserId);
1448 return settingsState.new Setting(
Kweku Adams5e0052b2019-02-22 15:17:52 -08001449 Secure.LOCATION_MODE,
Makoto Onuki0000d322017-11-28 16:31:47 -08001450 "", // value
1451 "", // tag
1452 "", // default value
1453 "", // package name
1454 false, // from system
1455 "0" // id
1456 ) {
1457 @Override
1458 public boolean update(String value, boolean setDefault, String packageName,
1459 String tag, boolean forceNonSystemPackage) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001460 Slog.wtf(LOG_TAG, "update shouldn't be called on this instance.");
Makoto Onuki0000d322017-11-28 16:31:47 -08001461 return false;
1462 }
1463 };
1464 }
1465 }
1466
Svetoslav Ganove080da92016-12-21 17:10:35 -08001467 private boolean insertSecureSetting(String name, String value, String tag,
1468 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001469 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001470 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001471 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1472 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001473 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001474 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1475 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001476 }
1477
Svet Ganov53a441c2016-04-19 19:38:00 -07001478 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001479 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001480 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1481 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001482 }
1483
Svetoslav Ganove080da92016-12-21 17:10:35 -08001484 return mutateSecureSetting(name, null, null, false, requestingUserId,
1485 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001486 }
1487
Svetoslav Ganove080da92016-12-21 17:10:35 -08001488 private boolean updateSecureSetting(String name, String value, String tag,
1489 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001490 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001491 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001492 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1493 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001494 }
1495
Svetoslav Ganove080da92016-12-21 17:10:35 -08001496 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1497 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001498 }
1499
Svetoslav Ganove080da92016-12-21 17:10:35 -08001500 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1501 if (DEBUG) {
1502 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1503 + mode + ", " + tag + ")");
1504 }
1505
1506 mutateSecureSetting(null, null, tag, false, requestingUserId,
1507 MUTATION_OPERATION_RESET, false, mode);
1508 }
1509
1510 private boolean mutateSecureSetting(String name, String value, String tag,
1511 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1512 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001513 // Make sure the caller can change the settings.
1514 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1515
Svetoslav683914b2015-01-15 14:22:26 -08001516 // Resolve the userId on whose behalf the call is made.
1517 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1518
Makoto Onuki28da2e32015-11-20 11:30:44 -08001519 // If this is a setting that is currently restricted for this user, do not allow
1520 // unrestricting changes.
Christopher Tate65fb2e42019-10-11 17:00:23 -07001521 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001522 return false;
1523 }
1524
1525 // Determine the owning user as some profile settings are cloned from the parent.
1526 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1527
1528 // Only the owning user can change the setting.
1529 if (owningUserId != callingUserId) {
1530 return false;
1531 }
1532
Svetoslav683914b2015-01-15 14:22:26 -08001533 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001534 synchronized (mLock) {
Soonil Nagarkar10b19602019-09-10 15:46:32 -07001535 // Special cases for location providers (sigh).
1536 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1537 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1538 forceNotify);
1539 }
1540
Svetoslav7ec28e82015-05-20 17:01:10 -07001541 switch (operation) {
1542 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001543 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001544 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001545 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001546 }
Svetoslav683914b2015-01-15 14:22:26 -08001547
Svetoslav7ec28e82015-05-20 17:01:10 -07001548 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001549 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001550 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001551 }
Svetoslav683914b2015-01-15 14:22:26 -08001552
Svetoslav7ec28e82015-05-20 17:01:10 -07001553 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001554 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001555 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001556 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001557 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001558
1559 case MUTATION_OPERATION_RESET: {
1560 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1561 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1562 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001563 }
1564 }
1565
1566 return false;
1567 }
1568
Svetoslav7ec28e82015-05-20 17:01:10 -07001569 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001570 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001571 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001572 }
1573
1574 // Resolve the userId on whose behalf the call is made.
1575 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1576
Svetoslav7ec28e82015-05-20 17:01:10 -07001577 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001578 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001579
Svetoslav7ec28e82015-05-20 17:01:10 -07001580 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001581
Svetoslav7ec28e82015-05-20 17:01:10 -07001582 String[] normalizedProjection = normalizeProjection(projection);
1583 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001584
Svetoslav7ec28e82015-05-20 17:01:10 -07001585 for (int i = 0; i < nameCount; i++) {
1586 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001587
Svetoslav7ec28e82015-05-20 17:01:10 -07001588 // Determine the owning user as some profile settings are cloned from the parent.
1589 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1590 name);
Svetoslav683914b2015-01-15 14:22:26 -08001591
Svetoslav7ec28e82015-05-20 17:01:10 -07001592 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001593 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001594 appendSettingToCursor(result, setting);
1595 }
1596
1597 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001598 }
Svetoslav683914b2015-01-15 14:22:26 -08001599 }
1600
Svetoslav7ec28e82015-05-20 17:01:10 -07001601 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001602 if (DEBUG) {
1603 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1604 }
1605
1606 // Resolve the userId on whose behalf the call is made.
1607 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1608
Chad Brubakera6830e72017-04-28 17:34:36 -07001609 // Ensure the caller can access the setting.
1610 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001611
Svetoslav683914b2015-01-15 14:22:26 -08001612 // Determine the owning user as some profile settings are cloned from the parent.
1613 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1614
1615 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001616 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001617 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001618 }
Svetoslav683914b2015-01-15 14:22:26 -08001619 }
1620
Svetoslav7ec28e82015-05-20 17:01:10 -07001621 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001622 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001623 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001624 + requestingUserId + ")");
1625 }
1626
Svetoslav7ec28e82015-05-20 17:01:10 -07001627 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001628 }
1629
Svetoslav7ec28e82015-05-20 17:01:10 -07001630 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001631 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001632 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001633 }
1634
Svetoslav7ec28e82015-05-20 17:01:10 -07001635 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001636 }
1637
Svetoslav7ec28e82015-05-20 17:01:10 -07001638 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001639 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001640 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001641 + requestingUserId + ")");
1642 }
1643
Svetoslav7ec28e82015-05-20 17:01:10 -07001644 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001645 }
1646
Svetoslav7ec28e82015-05-20 17:01:10 -07001647 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001648 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001649 if (!hasWriteSecureSettingsPermission()) {
1650 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1651 // operation is allowed for the calling package through appops.
1652 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1653 Binder.getCallingUid(), getCallingPackage(), true)) {
1654 return false;
1655 }
Svetoslav683914b2015-01-15 14:22:26 -08001656 }
1657
Svetoslav683914b2015-01-15 14:22:26 -08001658 // Resolve the userId on whose behalf the call is made.
1659 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1660
Christopher Tate65fb2e42019-10-11 17:00:23 -07001661 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
yuemingw1d13eae2018-01-30 17:27:54 +00001662 return false;
1663 }
1664
Svetoslavd8d25e02015-11-20 13:09:26 -08001665 // Enforce what the calling package can mutate the system settings.
1666 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1667
Svetoslav683914b2015-01-15 14:22:26 -08001668 // Determine the owning user as some profile settings are cloned from the parent.
1669 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1670
1671 // Only the owning user id can change the setting.
1672 if (owningUserId != callingUserId) {
1673 return false;
1674 }
1675
Jeff Sharkey413573a2016-02-22 17:52:45 -07001676 // Invalidate any relevant cache files
1677 String cacheName = null;
1678 if (Settings.System.RINGTONE.equals(name)) {
1679 cacheName = Settings.System.RINGTONE_CACHE;
1680 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1681 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1682 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1683 cacheName = Settings.System.ALARM_ALERT_CACHE;
1684 }
1685 if (cacheName != null) {
1686 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001687 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001688 cacheFile.delete();
1689 }
1690
Svetoslav683914b2015-01-15 14:22:26 -08001691 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001692 synchronized (mLock) {
1693 switch (operation) {
1694 case MUTATION_OPERATION_INSERT: {
1695 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001696 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001697 owningUserId, name, value, null, false, getCallingPackage(),
1698 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001699 }
1700
1701 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001702 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001703 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001704 }
1705
1706 case MUTATION_OPERATION_UPDATE: {
1707 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001708 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001709 owningUserId, name, value, null, false, getCallingPackage(),
1710 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001711 }
Svetoslav683914b2015-01-15 14:22:26 -08001712 }
1713
Svetoslav7ec28e82015-05-20 17:01:10 -07001714 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001715 }
Svetoslav683914b2015-01-15 14:22:26 -08001716 }
1717
Billy Lau6ad2d662015-07-18 00:26:58 +01001718 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001719 // Write secure settings is a more protected permission. If caller has it we are good.
1720 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1721 == PackageManager.PERMISSION_GRANTED) {
1722 return true;
1723 }
1724
Svetoslavf41334b2015-06-23 12:06:03 -07001725 return false;
1726 }
1727
Svetoslav683914b2015-01-15 14:22:26 -08001728 private void validateSystemSettingValue(String name, String value) {
Al Sutton91f89d02019-08-16 12:56:57 +01001729 Validator validator = SystemSettingsValidators.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001730 if (validator != null && !validator.validate(value)) {
1731 throw new IllegalArgumentException("Invalid value: " + value
1732 + " for setting: " + name);
1733 }
1734 }
1735
Alex Klyubin1991f572017-03-03 14:08:36 -08001736 /**
1737 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1738 */
1739 private boolean isSecureSettingAccessible(String name, int callingUserId,
1740 int owningUserId) {
1741 // Special case for location (sigh).
1742 // This check is not inside the name-based checks below because this method performs checks
1743 // only if the calling user ID is not the same as the owning user ID.
1744 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1745 return false;
1746 }
1747
1748 switch (name) {
1749 case "bluetooth_address":
1750 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1751 // address in this secure setting. Secure settings can normally be read by any app,
1752 // which thus enables them to bypass the recently introduced restrictions on access
1753 // to device identifiers.
1754 // To mitigate this we make this setting available only to callers privileged to see
1755 // this device's MAC addresses, same as through public API
1756 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1757 return getContext().checkCallingOrSelfPermission(
1758 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1759 default:
1760 return true;
1761 }
1762 }
1763
Svetoslav683914b2015-01-15 14:22:26 -08001764 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1765 int owningUserId) {
1766 // Optimization - location providers are restricted only for managed profiles.
1767 if (callingUserId == owningUserId) {
1768 return false;
1769 }
1770 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1771 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1772 new UserHandle(callingUserId))) {
1773 return true;
1774 }
1775 return false;
1776 }
1777
Svetoslav683914b2015-01-15 14:22:26 -08001778 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1779 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1780 }
1781
1782 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001783 final int parentId;
1784 // Resolves dependency if setting has a dependency and the calling user has a parent
1785 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1786 && (parentId = getGroupParentLocked(userId)) != userId) {
1787 // The setting has a dependency and the profile has a parent
1788 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001789 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1790 final long token = Binder.clearCallingIdentity();
1791 try {
1792 Setting settingObj = getSecureSetting(dependency, userId);
1793 if (settingObj != null && settingObj.getValue().equals("1")) {
1794 return parentId;
1795 }
1796 } finally {
1797 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001798 }
1799 }
Svetoslav683914b2015-01-15 14:22:26 -08001800 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1801 }
1802
1803 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1804 final int parentId = getGroupParentLocked(userId);
1805 if (parentId != userId && keys.contains(name)) {
1806 return parentId;
1807 }
1808 return userId;
1809 }
1810
Svetoslavf41334b2015-06-23 12:06:03 -07001811 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001812 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001813 // System/root/shell can mutate whatever secure settings they want.
1814 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001815 final int appId = UserHandle.getAppId(callingUid);
1816 if (appId == android.os.Process.SYSTEM_UID
1817 || appId == Process.SHELL_UID
1818 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001819 return;
1820 }
1821
1822 switch (operation) {
1823 case MUTATION_OPERATION_INSERT:
1824 // Insert updates.
1825 case MUTATION_OPERATION_UPDATE: {
1826 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1827 return;
1828 }
1829
1830 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001831 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001832
1833 // Privileged apps can do whatever they want.
1834 if ((packageInfo.applicationInfo.privateFlags
1835 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1836 return;
1837 }
1838
1839 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1840 packageInfo.applicationInfo.targetSdkVersion, name);
1841 } break;
1842
1843 case MUTATION_OPERATION_DELETE: {
1844 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1845 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1846 throw new IllegalArgumentException("You cannot delete system defined"
1847 + " secure settings.");
1848 }
1849
1850 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001851 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001852
1853 // Privileged apps can do whatever they want.
1854 if ((packageInfo.applicationInfo.privateFlags &
1855 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1856 return;
1857 }
1858
1859 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1860 packageInfo.applicationInfo.targetSdkVersion, name);
1861 } break;
1862 }
1863 }
1864
Todd Kennedybe0b8892017-02-15 14:13:52 -08001865 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001866 switch (settingsType) {
1867 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001868 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001869 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001870 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001871 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001872 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001873 default:
1874 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1875 }
1876 }
1877
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001878 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1879 switch (settingsType) {
1880 case SETTINGS_TYPE_GLOBAL:
1881 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1882 case SETTINGS_TYPE_SYSTEM:
1883 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1884 case SETTINGS_TYPE_SECURE:
1885 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1886 default:
1887 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1888 }
1889 }
1890
Andreas Gampeb58893072018-09-05 16:52:31 -07001891 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001892 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001893 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1894 // in the current form.
1895 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001896 }
1897
Chad Brubakera6830e72017-04-28 17:34:36 -07001898 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001899 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1900 return;
1901 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001902 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001903 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001904 return;
1905 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001906 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1907 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001908 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1909 // breakage in the current form.
1910 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1911 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001912 }
1913 }
1914
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001915 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1916 // We always use the callingUid for this lookup. This means that if hypothetically an
1917 // app was installed in user A with cross user and in user B as an Instant App
1918 // the app in A would be able to see all the settings in user B. However since cross
1919 // user is a system permission and the app must be uninstalled in B and then installed as
1920 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001921 ApplicationInfo ai = null;
1922 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001923 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1924 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001925 } catch (RemoteException ignored) {
1926 }
1927 if (ai == null) {
1928 throw new IllegalStateException("Failed to lookup info for package "
1929 + getCallingPackage());
1930 }
1931 return ai;
1932 }
1933
Xiaohui Chen43765b72015-08-31 10:57:33 -07001934 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001935 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001936 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1937 getCallingPackage(), 0, userId);
1938 if (packageInfo != null) {
1939 return packageInfo;
1940 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001941 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001942 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001943 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001944 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001945 }
1946
1947 private int getGroupParentLocked(int userId) {
1948 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001949 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001950 return userId;
1951 }
1952 // We are in the same process with the user manager and the returned
1953 // user info is a cached instance, so just look up instead of cache.
1954 final long identity = Binder.clearCallingIdentity();
1955 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001956 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001957 UserInfo userInfo = mUserManager.getProfileParent(userId);
1958 return (userInfo != null) ? userInfo.id : userId;
1959 } finally {
1960 Binder.restoreCallingIdentity(identity);
1961 }
1962 }
1963
Svetoslav683914b2015-01-15 14:22:26 -08001964 private void enforceWritePermission(String permission) {
1965 if (getContext().checkCallingOrSelfPermission(permission)
1966 != PackageManager.PERMISSION_GRANTED) {
1967 throw new SecurityException("Permission denial: writing to settings requires:"
1968 + permission);
1969 }
1970 }
1971
1972 /*
1973 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1974 * This setting contains a list of the currently enabled location providers.
1975 * But helper functions in android.providers.Settings can enable or disable
1976 * a single provider by using a "+" or "-" prefix before the provider name.
1977 *
yuemingw1d13eae2018-01-30 17:27:54 +00001978 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1979 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1980 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001981 *
Svetoslav683914b2015-01-15 14:22:26 -08001982 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001983 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001984 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001985 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1986 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001987 if (TextUtils.isEmpty(value)) {
1988 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001989 }
Maggie83e03f52018-03-16 12:22:20 -07001990 Setting oldSetting = getSecureSetting(
1991 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1992 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001993 return false;
1994 }
Maggie83e03f52018-03-16 12:22:20 -07001995 String oldProviders = oldSetting.getValue();
1996 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1997 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1998 Set<String> newProvidersSet = new ArraySet<>();
1999 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002000
Maggie83e03f52018-03-16 12:22:20 -07002001 String[] providerUpdates = value.split(",");
2002 boolean inputError = false;
2003 for (String provider : providerUpdates) {
2004 // do not update location_providers_allowed when input is invalid
2005 if (TextUtils.isEmpty(provider)) {
2006 inputError = true;
2007 break;
Svetoslav683914b2015-01-15 14:22:26 -08002008 }
Maggie83e03f52018-03-16 12:22:20 -07002009 final char prefix = provider.charAt(0);
2010 // do not update location_providers_allowed when input is invalid
2011 if (prefix != '+' && prefix != '-') {
2012 inputError = true;
2013 break;
Svetoslav683914b2015-01-15 14:22:26 -08002014 }
Maggie83e03f52018-03-16 12:22:20 -07002015 // skip prefix
2016 provider = provider.substring(1);
2017 if (prefix == '+') {
2018 newProvidersSet.add(provider);
2019 } else if (prefix == '-') {
2020 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002021 }
Maggie83e03f52018-03-16 12:22:20 -07002022 }
2023 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2024 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002025 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002026 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002027 mSettingsRegistry.notifyForSettingsChange(
2028 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002029 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2030 }
Svetoslav683914b2015-01-15 14:22:26 -08002031 return false;
2032 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002033 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002034 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2035 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002036 }
2037
Svetoslav683914b2015-01-15 14:22:26 -08002038 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2039 int targetSdkVersion, String name) {
2040 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2041 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2042 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2043 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2044 + " This will soon become an error.");
2045 } else {
2046 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2047 + " This will soon become an error.");
2048 }
2049 } else {
2050 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2051 throw new IllegalArgumentException("You cannot change private secure settings.");
2052 } else {
2053 throw new IllegalArgumentException("You cannot keep your settings in"
2054 + " the secure settings.");
2055 }
2056 }
2057 }
2058
2059 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2060 if (requestingUserId == UserHandle.getCallingUserId()) {
2061 return requestingUserId;
2062 }
2063 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2064 Binder.getCallingUid(), requestingUserId, false, true,
2065 "get/set setting for user", null);
2066 }
2067
Matt Pape793b15c2019-10-07 13:17:20 -07002068 private Bundle packageValueForCallResult(Setting setting, boolean trackingGeneration) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002069 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002070 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002071 return NULL_SETTING_BUNDLE;
2072 }
2073 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002074 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002075 Bundle result = new Bundle();
2076 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002077 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002078
Svetoslav Ganove080da92016-12-21 17:10:35 -08002079 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002080 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002081 }
2082
Matt Pape793b15c2019-10-07 13:17:20 -07002083 private Bundle packageValuesForCallResult(HashMap<String, String> keyValues,
2084 boolean trackingGeneration) {
2085 Bundle result = new Bundle();
2086 result.putSerializable(Settings.NameValueTable.VALUE, keyValues);
2087 if (trackingGeneration) {
2088 synchronized (mLock) {
2089 mSettingsRegistry.mGenerationRegistry.addGenerationData(result,
2090 mSettingsRegistry.getSettingsLocked(
2091 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM).mKey);
2092 }
2093 }
2094
2095 return result;
2096 }
2097
Svetoslav683914b2015-01-15 14:22:26 -08002098 private static int getRequestingUserId(Bundle args) {
2099 final int callingUserId = UserHandle.getCallingUserId();
2100 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2101 : callingUserId;
2102 }
2103
Svet Ganov53a441c2016-04-19 19:38:00 -07002104 private boolean isTrackingGeneration(Bundle args) {
2105 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2106 }
2107
Svetoslav683914b2015-01-15 14:22:26 -08002108 private static String getSettingValue(Bundle args) {
2109 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2110 }
2111
Svetoslav Ganove080da92016-12-21 17:10:35 -08002112 private static String getSettingTag(Bundle args) {
2113 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2114 }
2115
Matt Pape6bfc62e2018-11-28 13:16:03 -08002116 private static String getSettingPrefix(Bundle args) {
Matt Papec6001532019-10-24 15:50:32 -07002117 return (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002118 }
2119
Svetoslav Ganove080da92016-12-21 17:10:35 -08002120 private static boolean getSettingMakeDefault(Bundle args) {
2121 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2122 }
2123
2124 private static int getResetModeEnforcingPermission(Bundle args) {
2125 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2126 switch (mode) {
2127 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2128 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2129 throw new SecurityException("Only system, shell/root on a "
2130 + "debuggable build can reset to untrusted defaults");
2131 }
2132 return mode;
2133 }
2134 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2135 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2136 throw new SecurityException("Only system, shell/root on a "
2137 + "debuggable build can reset untrusted changes");
2138 }
2139 return mode;
2140 }
2141 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2142 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2143 throw new SecurityException("Only system, shell/root on a "
2144 + "debuggable build can reset to trusted defaults");
2145 }
2146 return mode;
2147 }
2148 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2149 return mode;
2150 }
2151 }
2152 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2153 }
2154
2155 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2156 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2157 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2158 && (appId == SHELL_UID || appId == ROOT_UID));
2159 }
2160
Svetoslav683914b2015-01-15 14:22:26 -08002161 private static String getValidTableOrThrow(Uri uri) {
2162 if (uri.getPathSegments().size() > 0) {
2163 String table = uri.getPathSegments().get(0);
2164 if (DatabaseHelper.isValidTable(table)) {
2165 return table;
2166 }
2167 throw new IllegalArgumentException("Bad root path: " + table);
2168 }
2169 throw new IllegalArgumentException("Invalid URI:" + uri);
2170 }
2171
2172 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002173 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002174 return new MatrixCursor(projection, 0);
2175 }
2176 MatrixCursor cursor = new MatrixCursor(projection, 1);
2177 appendSettingToCursor(cursor, setting);
2178 return cursor;
2179 }
2180
2181 private static String[] normalizeProjection(String[] projection) {
2182 if (projection == null) {
2183 return ALL_COLUMNS;
2184 }
2185
2186 final int columnCount = projection.length;
2187 for (int i = 0; i < columnCount; i++) {
2188 String column = projection[i];
2189 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2190 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002191 }
2192 }
2193
Svetoslav683914b2015-01-15 14:22:26 -08002194 return projection;
2195 }
2196
2197 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002198 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002199 return;
2200 }
Svetoslav683914b2015-01-15 14:22:26 -08002201 final int columnCount = cursor.getColumnCount();
2202
2203 String[] values = new String[columnCount];
2204
2205 for (int i = 0; i < columnCount; i++) {
2206 String column = cursor.getColumnName(i);
2207
2208 switch (column) {
2209 case Settings.NameValueTable._ID: {
2210 values[i] = setting.getId();
2211 } break;
2212
2213 case Settings.NameValueTable.NAME: {
2214 values[i] = setting.getName();
2215 } break;
2216
2217 case Settings.NameValueTable.VALUE: {
2218 values[i] = setting.getValue();
2219 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002220 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002221 }
2222
Svetoslav683914b2015-01-15 14:22:26 -08002223 cursor.addRow(values);
2224 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002225
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002226 private static boolean isKeyValid(String key) {
2227 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2228 }
2229
Matt Pape7b1c6cd2019-01-04 08:10:41 -08002230 private String resolveCallingPackage() {
2231 switch (Binder.getCallingUid()) {
2232 case Process.ROOT_UID: {
2233 return "root";
2234 }
2235
2236 case Process.SHELL_UID: {
2237 return "com.android.shell";
2238 }
2239
2240 default: {
2241 return getCallingPackage();
2242 }
2243 }
2244 }
2245
Svetoslav683914b2015-01-15 14:22:26 -08002246 private static final class Arguments {
2247 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2248 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2249
2250 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2251 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2252
2253 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2254 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2255
2256 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2257 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2258
2259 public final String table;
2260 public final String name;
2261
2262 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2263 final int segmentSize = uri.getPathSegments().size();
2264 switch (segmentSize) {
2265 case 1: {
2266 if (where != null
2267 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2268 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2269 && whereArgs.length == 1) {
2270 name = whereArgs[0];
2271 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002272 return;
Svetoslav683914b2015-01-15 14:22:26 -08002273 } else if (where != null
2274 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2275 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2276 final int startIndex = Math.max(where.indexOf("'"),
2277 where.indexOf("\"")) + 1;
2278 final int endIndex = Math.max(where.lastIndexOf("'"),
2279 where.lastIndexOf("\""));
2280 name = where.substring(startIndex, endIndex);
2281 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002282 return;
Svetoslav683914b2015-01-15 14:22:26 -08002283 } else if (supportAll && where == null && whereArgs == null) {
2284 name = null;
2285 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002286 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002287 }
Svetoslav683914b2015-01-15 14:22:26 -08002288 } break;
2289
Svetoslav28494652015-02-12 14:11:42 -08002290 case 2: {
2291 if (where == null && whereArgs == null) {
2292 name = uri.getPathSegments().get(1);
2293 table = computeTableForSetting(uri, name);
2294 return;
2295 }
2296 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002297 }
Svetoslav28494652015-02-12 14:11:42 -08002298
2299 EventLogTags.writeUnsupportedSettingsQuery(
2300 uri.toSafeString(), where, Arrays.toString(whereArgs));
2301 String message = String.format( "Supported SQL:\n"
2302 + " uri content://some_table/some_property with null where and where args\n"
2303 + " uri content://some_table with query name=? and single name as arg\n"
2304 + " uri content://some_table with query name=some_name and null args\n"
2305 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2306 Arrays.toString(whereArgs));
2307 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002308 }
2309
Svetoslav28494652015-02-12 14:11:42 -08002310 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002311 String table = getValidTableOrThrow(uri);
2312
2313 if (name != null) {
2314 if (sSystemMovedToSecureSettings.contains(name)) {
2315 table = TABLE_SECURE;
2316 }
2317
2318 if (sSystemMovedToGlobalSettings.contains(name)) {
2319 table = TABLE_GLOBAL;
2320 }
2321
2322 if (sSecureMovedToGlobalSettings.contains(name)) {
2323 table = TABLE_GLOBAL;
2324 }
2325
2326 if (sGlobalMovedToSecureSettings.contains(name)) {
2327 table = TABLE_SECURE;
2328 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002329 }
Svetoslav683914b2015-01-15 14:22:26 -08002330
2331 return table;
2332 }
2333 }
2334
2335 final class SettingsRegistry {
2336 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2337
Svetoslav683914b2015-01-15 14:22:26 -08002338 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2339 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2340 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002341 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002342 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002343
2344 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002345
2346 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2347
Svet Ganov53a441c2016-04-19 19:38:00 -07002348 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002349
Svetoslav7e0683b2015-08-03 16:02:52 -07002350 private final Handler mHandler;
2351
Svet Ganov53a441c2016-04-19 19:38:00 -07002352 private final BackupManager mBackupManager;
2353
Amith Yamasani39452022017-03-21 15:23:47 -07002354 private String mSettingsCreationBuildId;
2355
Svetoslav683914b2015-01-15 14:22:26 -08002356 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002357 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002358 mGenerationRegistry = new GenerationRegistry(mLock);
2359 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002360 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002361 syncSsaidTableOnStart();
2362 }
2363
2364 private void generateUserKeyLocked(int userId) {
2365 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002366 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002367 final SecureRandom rand = new SecureRandom();
2368 rand.nextBytes(keyBytes);
2369
2370 // Convert to string for storage in settings table.
Neil Fuller3447fb42019-04-08 22:03:14 +01002371 final String userKey = HexEncoding.encodeToString(keyBytes, true /* upperCase */);
Mark Rathjend891f012017-01-19 04:10:37 +00002372
2373 // Store the key in the ssaid table.
2374 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2375 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2376 true, SettingsState.SYSTEM_PACKAGE_NAME);
2377
2378 if (!success) {
2379 throw new IllegalStateException("Ssaid settings not accessible");
2380 }
2381 }
2382
Mark Rathjen7599f132017-01-23 14:15:54 -08002383 private byte[] getLengthPrefix(byte[] data) {
2384 return ByteBuffer.allocate(4).putInt(data.length).array();
2385 }
2386
Christopher Tateb218e762017-04-05 16:34:07 -07002387 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002388 // Read the user's key from the ssaid table.
2389 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002390 if (userKeySetting == null || userKeySetting.isNull()
2391 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002392 // Lazy initialize and store the user key.
2393 generateUserKeyLocked(userId);
2394 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002395 if (userKeySetting == null || userKeySetting.isNull()
2396 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002397 throw new IllegalStateException("User key not accessible");
2398 }
2399 }
2400 final String userKey = userKeySetting.getValue();
Neil Fuller3447fb42019-04-08 22:03:14 +01002401 if (userKey == null || userKey.length() % 2 != 0) {
2402 throw new IllegalStateException("User key invalid");
2403 }
Mark Rathjend891f012017-01-19 04:10:37 +00002404
2405 // Convert the user's key back to a byte array.
Neil Fuller3447fb42019-04-08 22:03:14 +01002406 final byte[] keyBytes = HexEncoding.decode(userKey);
Mark Rathjen7599f132017-01-23 14:15:54 -08002407
2408 // Validate that the key is of expected length.
2409 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
Neil Fuller3447fb42019-04-08 22:03:14 +01002410 if (keyBytes.length != 16 && keyBytes.length != 32) {
Mark Rathjend891f012017-01-19 04:10:37 +00002411 throw new IllegalStateException("User key invalid");
2412 }
2413
Mark Rathjen7599f132017-01-23 14:15:54 -08002414 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002415 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002416 m = Mac.getInstance("HmacSHA256");
2417 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002418 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002419 throw new IllegalStateException("HmacSHA256 is not available", e);
2420 } catch (InvalidKeyException e) {
2421 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002422 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002423
Mark Rathjenf42dd912017-06-05 19:04:34 -07002424 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002425 for (int i = 0; i < callingPkg.signatures.length; i++) {
2426 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002427 m.update(getLengthPrefix(sig), 0, 4);
2428 m.update(sig);
2429 }
Mark Rathjend891f012017-01-19 04:10:37 +00002430
2431 // Convert result to a string for storage in settings table. Only want first 64 bits.
Neil Fuller3447fb42019-04-08 22:03:14 +01002432 final String ssaid = HexEncoding.encodeToString(m.doFinal(), false /* upperCase */)
2433 .substring(0, 16);
Mark Rathjend891f012017-01-19 04:10:37 +00002434
2435 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002436 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002437 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2438 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002439 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002440
2441 if (!success) {
2442 throw new IllegalStateException("Ssaid settings not accessible");
2443 }
2444
2445 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2446 }
2447
2448 public void syncSsaidTableOnStart() {
2449 synchronized (mLock) {
2450 // Verify that each user's packages and ssaid's are in sync.
2451 for (UserInfo user : mUserManager.getUsers(true)) {
2452 // Get all uids for the user's packages.
2453 final List<PackageInfo> packages;
2454 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002455 packages = mPackageManager.getInstalledPackages(
2456 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2457 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002458 } catch (RemoteException e) {
2459 throw new IllegalStateException("Package manager not available");
2460 }
2461 final Set<String> appUids = new HashSet<>();
2462 for (PackageInfo info : packages) {
2463 appUids.add(Integer.toString(info.applicationInfo.uid));
2464 }
2465
2466 // Get all uids currently stored in the user's ssaid table.
2467 final Set<String> ssaidUids = new HashSet<>(
2468 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2469 ssaidUids.remove(SSAID_USER_KEY);
2470
2471 // Perform a set difference for the appUids and ssaidUids.
2472 ssaidUids.removeAll(appUids);
2473
2474 // If there are ssaidUids left over they need to be removed from the table.
2475 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2476 user.id);
2477 for (String uid : ssaidUids) {
2478 ssaidSettings.deleteSettingLocked(uid);
2479 }
2480 }
2481 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002482 }
2483
Svetoslav683914b2015-01-15 14:22:26 -08002484 public List<String> getSettingsNamesLocked(int type, int userId) {
2485 final int key = makeKey(type, userId);
2486 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002487 if (settingsState == null) {
2488 return new ArrayList<String>();
2489 }
Svetoslav683914b2015-01-15 14:22:26 -08002490 return settingsState.getSettingNamesLocked();
2491 }
2492
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002493 public SparseBooleanArray getKnownUsersLocked() {
2494 SparseBooleanArray users = new SparseBooleanArray();
2495 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2496 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2497 }
2498 return users;
2499 }
2500
Kweku Adamsb0886f32017-10-31 15:32:09 -07002501 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002502 public SettingsState getSettingsLocked(int type, int userId) {
2503 final int key = makeKey(type, userId);
2504 return peekSettingsStateLocked(key);
2505 }
2506
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002507 public boolean ensureSettingsForUserLocked(int userId) {
2508 // First make sure this user actually exists.
2509 if (mUserManager.getUserInfo(userId) == null) {
2510 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2511 return false;
2512 }
2513
Svetoslav683914b2015-01-15 14:22:26 -08002514 // Migrate the setting for this user if needed.
2515 migrateLegacySettingsForUserIfNeededLocked(userId);
2516
Matt Pape1b31a332018-10-17 09:58:28 -07002517 // Ensure config settings loaded if owner.
2518 if (userId == UserHandle.USER_SYSTEM) {
2519 final int configKey
2520 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2521 ensureSettingsStateLocked(configKey);
2522 }
2523
Svetoslav683914b2015-01-15 14:22:26 -08002524 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002525 if (userId == UserHandle.USER_SYSTEM) {
2526 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002527 ensureSettingsStateLocked(globalKey);
2528 }
2529
2530 // Ensure secure settings loaded.
2531 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2532 ensureSettingsStateLocked(secureKey);
2533
2534 // Make sure the secure settings have an Android id set.
2535 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2536 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2537
2538 // Ensure system settings loaded.
2539 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2540 ensureSettingsStateLocked(systemKey);
2541
Mark Rathjend891f012017-01-19 04:10:37 +00002542 // Ensure secure settings loaded.
2543 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2544 ensureSettingsStateLocked(ssaidKey);
2545
Svetoslav683914b2015-01-15 14:22:26 -08002546 // Upgrade the settings to the latest version.
2547 UpgradeController upgrader = new UpgradeController(userId);
2548 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002549 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002550 }
2551
2552 private void ensureSettingsStateLocked(int key) {
2553 if (mSettingsStates.get(key) == null) {
2554 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002555 SettingsState settingsState = new SettingsState(getContext(), mLock,
2556 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002557 mSettingsStates.put(key, settingsState);
2558 }
2559 }
2560
2561 public void removeUserStateLocked(int userId, boolean permanently) {
2562 // We always keep the global settings in memory.
2563
2564 // Nuke system settings.
2565 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2566 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2567 if (systemSettingsState != null) {
2568 if (permanently) {
2569 mSettingsStates.remove(systemKey);
2570 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002571 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002572 systemSettingsState.destroyLocked(new Runnable() {
2573 @Override
2574 public void run() {
2575 mSettingsStates.remove(systemKey);
2576 }
2577 });
2578 }
2579 }
2580
2581 // Nuke secure settings.
2582 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2583 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2584 if (secureSettingsState != null) {
2585 if (permanently) {
2586 mSettingsStates.remove(secureKey);
2587 secureSettingsState.destroyLocked(null);
2588 } else {
2589 secureSettingsState.destroyLocked(new Runnable() {
2590 @Override
2591 public void run() {
2592 mSettingsStates.remove(secureKey);
2593 }
2594 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002595 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002596 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002597
Mark Rathjend891f012017-01-19 04:10:37 +00002598 // Nuke ssaid settings.
2599 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2600 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2601 if (ssaidSettingsState != null) {
2602 if (permanently) {
2603 mSettingsStates.remove(ssaidKey);
2604 ssaidSettingsState.destroyLocked(null);
2605 } else {
2606 ssaidSettingsState.destroyLocked(new Runnable() {
2607 @Override
2608 public void run() {
2609 mSettingsStates.remove(ssaidKey);
2610 }
2611 });
2612 }
2613 }
2614
Svet Ganov53a441c2016-04-19 19:38:00 -07002615 // Nuke generation tracking data
2616 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002617 }
2618
Svetoslav683914b2015-01-15 14:22:26 -08002619 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002620 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2621 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002622 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2623 packageName, forceNotify, criticalSettings);
2624 }
2625
2626 public boolean insertSettingLocked(int type, int userId, String name, String value,
2627 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2628 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002629 final int key = makeKey(type, userId);
2630
Svetoslav Ganove080da92016-12-21 17:10:35 -08002631 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002632 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002633 if (settingsState != null) {
2634 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002635 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002636 }
Svetoslav683914b2015-01-15 14:22:26 -08002637
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002638 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2639 settingsState.persistSyncLocked();
2640 }
2641
Svet Ganov53a441c2016-04-19 19:38:00 -07002642 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002643 notifyForSettingsChange(key, name);
2644 }
2645 return success;
2646 }
2647
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002648 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2649 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002650 final int key = makeKey(type, userId);
2651
Svetoslav Ganove080da92016-12-21 17:10:35 -08002652 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002653 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002654 if (settingsState != null) {
2655 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002656 }
Svetoslav683914b2015-01-15 14:22:26 -08002657
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002658 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2659 settingsState.persistSyncLocked();
2660 }
2661
Svet Ganov53a441c2016-04-19 19:38:00 -07002662 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002663 notifyForSettingsChange(key, name);
2664 }
2665 return success;
2666 }
2667
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002668 public boolean updateSettingLocked(int type, int userId, String name, String value,
2669 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2670 Set<String> criticalSettings) {
2671 final int key = makeKey(type, userId);
2672
2673 boolean success = false;
2674 SettingsState settingsState = peekSettingsStateLocked(key);
2675 if (settingsState != null) {
2676 success = settingsState.updateSettingLocked(name, value, tag,
2677 makeDefault, packageName);
2678 }
2679
2680 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2681 settingsState.persistSyncLocked();
2682 }
2683
2684 if (forceNotify || success) {
2685 notifyForSettingsChange(key, name);
2686 }
2687
2688 return success;
2689 }
2690
Svetoslav683914b2015-01-15 14:22:26 -08002691 public Setting getSettingLocked(int type, int userId, String name) {
2692 final int key = makeKey(type, userId);
2693
2694 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002695 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002696 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002697 }
Mark Rathjend891f012017-01-19 04:10:37 +00002698
2699 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002700 return settingsState.getSettingLocked(name);
2701 }
2702
Svetoslav Ganove080da92016-12-21 17:10:35 -08002703 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2704 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002705 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2706 }
2707
2708 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2709 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002710 final int key = makeKey(type, userId);
2711 SettingsState settingsState = peekSettingsStateLocked(key);
2712 if (settingsState == null) {
2713 return;
2714 }
2715
2716 switch (mode) {
2717 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2718 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002719 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002720 Setting setting = settingsState.getSettingLocked(name);
2721 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002722 if ((tag != null && !tag.equals(setting.getTag()))
2723 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002724 continue;
2725 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002726 if (settingsState.resetSettingLocked(name)) {
2727 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002728 notifyForSettingsChange(key, name);
2729 }
2730 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002731 if (someSettingChanged) {
2732 settingsState.persistSyncLocked();
2733 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002734 }
2735 } break;
2736
2737 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2738 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002739 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002740 Setting setting = settingsState.getSettingLocked(name);
2741 if (!SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07002742 setting.getPackageName(), INVALID_UID, userId)) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002743 if (prefix != null && !setting.getName().startsWith(prefix)) {
2744 continue;
2745 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002746 if (settingsState.resetSettingLocked(name)) {
2747 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002748 notifyForSettingsChange(key, name);
2749 }
2750 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002751 if (someSettingChanged) {
2752 settingsState.persistSyncLocked();
2753 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002754 }
2755 } break;
2756
2757 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2758 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002759 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002760 Setting setting = settingsState.getSettingLocked(name);
2761 if (!SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07002762 setting.getPackageName(), INVALID_UID, userId)) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002763 if (prefix != null && !setting.getName().startsWith(prefix)) {
2764 continue;
2765 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002766 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002767 if (settingsState.resetSettingLocked(name)) {
2768 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002769 notifyForSettingsChange(key, name);
2770 }
2771 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002772 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002773 notifyForSettingsChange(key, name);
2774 }
2775 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002776 if (someSettingChanged) {
2777 settingsState.persistSyncLocked();
2778 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002779 }
2780 } break;
2781
2782 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2783 for (String name : settingsState.getSettingNamesLocked()) {
2784 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002785 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002786 if (prefix != null && !setting.getName().startsWith(prefix)) {
2787 continue;
2788 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002789 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002790 if (settingsState.resetSettingLocked(name)) {
2791 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002792 notifyForSettingsChange(key, name);
2793 }
2794 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002795 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002796 notifyForSettingsChange(key, name);
2797 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002798 if (someSettingChanged) {
2799 settingsState.persistSyncLocked();
2800 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002801 }
2802 } break;
2803 }
2804 }
2805
Zimuzoc56192c2018-07-25 10:40:01 +01002806 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002807 // Global and secure settings are signature protected. Apps signed
2808 // by the platform certificate are generally not uninstalled and
2809 // the main exception is tests. We trust components signed
2810 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002811
2812 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2813 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002814 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002815 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002816 }
Svetoslav683914b2015-01-15 14:22:26 -08002817 }
2818
Mark Rathjend891f012017-01-19 04:10:37 +00002819 public void onUidRemovedLocked(int uid) {
2820 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2821 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002822 if (ssaidSettings != null) {
2823 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2824 }
Mark Rathjend891f012017-01-19 04:10:37 +00002825 }
2826
Kweku Adamsb0886f32017-10-31 15:32:09 -07002827 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002828 private SettingsState peekSettingsStateLocked(int key) {
2829 SettingsState settingsState = mSettingsStates.get(key);
2830 if (settingsState != null) {
2831 return settingsState;
2832 }
2833
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002834 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2835 return null;
2836 }
Svetoslav683914b2015-01-15 14:22:26 -08002837 return mSettingsStates.get(key);
2838 }
2839
2840 private void migrateAllLegacySettingsIfNeeded() {
2841 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002842 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002843 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002844 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002845 return;
2846 }
2847
Amith Yamasani39452022017-03-21 15:23:47 -07002848 mSettingsCreationBuildId = Build.ID;
2849
Svetoslav683914b2015-01-15 14:22:26 -08002850 final long identity = Binder.clearCallingIdentity();
2851 try {
2852 List<UserInfo> users = mUserManager.getUsers(true);
2853
2854 final int userCount = users.size();
2855 for (int i = 0; i < userCount; i++) {
2856 final int userId = users.get(i).id;
2857
2858 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2859 SQLiteDatabase database = dbHelper.getWritableDatabase();
2860 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2861
2862 // Upgrade to the latest version.
2863 UpgradeController upgrader = new UpgradeController(userId);
2864 upgrader.upgradeIfNeededLocked();
2865
2866 // Drop from memory if not a running user.
2867 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2868 removeUserStateLocked(userId, false);
2869 }
2870 }
2871 } finally {
2872 Binder.restoreCallingIdentity(identity);
2873 }
2874 }
2875 }
2876
2877 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2878 // Every user has secure settings and if no file we need to migrate.
2879 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2880 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002881 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002882 return;
2883 }
2884
2885 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2886 SQLiteDatabase database = dbHelper.getWritableDatabase();
2887
2888 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2889 }
2890
2891 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2892 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002893 // Move over the system settings.
2894 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2895 ensureSettingsStateLocked(systemKey);
2896 SettingsState systemSettings = mSettingsStates.get(systemKey);
2897 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2898 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002899
2900 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002901 // Do this after System settings, since this is the first thing we check when deciding
2902 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002903 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2904 ensureSettingsStateLocked(secureKey);
2905 SettingsState secureSettings = mSettingsStates.get(secureKey);
2906 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2907 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2908 secureSettings.persistSyncLocked();
2909
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002910 // Move over the global settings if owner.
2911 // Do this last, since this is the first thing we check when deciding
2912 // to skip over migration from db to xml for owner user.
2913 if (userId == UserHandle.USER_SYSTEM) {
2914 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2915 ensureSettingsStateLocked(globalKey);
2916 SettingsState globalSettings = mSettingsStates.get(globalKey);
2917 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002918 // If this was just created
2919 if (mSettingsCreationBuildId != null) {
2920 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2921 mSettingsCreationBuildId, null, true,
2922 SettingsState.SYSTEM_PACKAGE_NAME);
2923 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002924 globalSettings.persistSyncLocked();
2925 }
Svetoslav683914b2015-01-15 14:22:26 -08002926
2927 // Drop the database as now all is moved and persisted.
2928 if (DROP_DATABASE_ON_MIGRATION) {
2929 dbHelper.dropDatabase();
2930 } else {
2931 dbHelper.backupDatabase();
2932 }
2933 }
2934
2935 private void migrateLegacySettingsLocked(SettingsState settingsState,
2936 SQLiteDatabase database, String table) {
2937 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2938 queryBuilder.setTables(table);
2939
2940 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2941 null, null, null, null, null);
2942
2943 if (cursor == null) {
2944 return;
2945 }
2946
2947 try {
2948 if (!cursor.moveToFirst()) {
2949 return;
2950 }
2951
2952 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2953 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2954
2955 settingsState.setVersionLocked(database.getVersion());
2956
2957 while (!cursor.isAfterLast()) {
2958 String name = cursor.getString(nameColumnIdx);
2959 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002960 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002961 SettingsState.SYSTEM_PACKAGE_NAME);
2962 cursor.moveToNext();
2963 }
2964 } finally {
2965 cursor.close();
2966 }
2967 }
2968
Andreas Gampeb58893072018-09-05 16:52:31 -07002969 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002970 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2971 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2972
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002973 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002974 return;
2975 }
2976
2977 final int userId = getUserIdFromKey(secureSettings.mKey);
2978
2979 final UserInfo user;
2980 final long identity = Binder.clearCallingIdentity();
2981 try {
2982 user = mUserManager.getUserInfo(userId);
2983 } finally {
2984 Binder.restoreCallingIdentity(identity);
2985 }
2986 if (user == null) {
2987 // Can happen due to races when deleting users - treat as benign.
2988 return;
2989 }
2990
2991 String androidId = Long.toHexString(new SecureRandom().nextLong());
2992 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002993 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002994
2995 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2996 + "] for user " + userId);
2997
2998 // Write a drop box entry if it's a restricted profile
2999 if (user.isRestricted()) {
3000 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3001 Context.DROPBOX_SERVICE);
3002 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3003 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3004 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3005 }
3006 }
3007 }
3008
3009 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003010 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003011 mGenerationRegistry.incrementGeneration(key);
3012
Linus Tufvesson93c38552019-05-30 12:47:39 +01003013 if (isGlobalSettingsKey(key) || isConfigSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003014 final long token = Binder.clearCallingIdentity();
3015 try {
Linus Tufvesson93c38552019-05-30 12:47:39 +01003016 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)
3017 && isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003018 // When the global kill switch is updated, send the
3019 // change notification for the location setting.
3020 notifyLocationChangeForRunningUsers();
3021 }
Linus Tufvesson93c38552019-05-30 12:47:39 +01003022 notifySettingChangeForRunningUsers(key, name);
Jeff Sharkey308093f2018-03-25 22:53:29 -06003023 } finally {
3024 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003025 }
Svet Ganov945864c2018-03-22 21:49:10 -07003026 } else {
3027 final int userId = getUserIdFromKey(key);
3028 final Uri uri = getNotificationUriFor(key, name);
3029 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3030 userId, 0, uri).sendToTarget();
3031 if (isSecureSettingsKey(key)) {
3032 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3033 sSecureCloneToManagedSettings);
3034 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3035 sSystemCloneFromParentOnDependency.values());
3036 } else if (isSystemSettingsKey(key)) {
3037 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3038 sSystemCloneToManagedSettings);
3039 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003040 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003041
Svet Ganov945864c2018-03-22 21:49:10 -07003042 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003043 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003044 }
3045
Svet Ganov53a441c2016-04-19 19:38:00 -07003046 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003047 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003048 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003049 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003050 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003051 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003052 final int key = makeKey(type, profileId);
3053 // Increment the generation first, so observers always see the new value
3054 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003055 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003056 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003057 }
3058 }
3059 }
Svetoslav683914b2015-01-15 14:22:26 -08003060 }
3061
Linus Tufvesson93c38552019-05-30 12:47:39 +01003062 private void notifySettingChangeForRunningUsers(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003063 // Important: No need to update generation for each user as there
3064 // is a singleton generation entry for the global settings which
3065 // is already incremented be the caller.
3066 final Uri uri = getNotificationUriFor(key, name);
3067 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3068 for (int i = 0; i < users.size(); i++) {
3069 final int userId = users.get(i).id;
3070 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3071 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3072 userId, 0, uri).sendToTarget();
3073 }
3074 }
3075 }
3076
Makoto Onuki0000d322017-11-28 16:31:47 -08003077 private void notifyLocationChangeForRunningUsers() {
3078 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3079
3080 for (int i = 0; i < users.size(); i++) {
3081 final int userId = users.get(i).id;
3082
3083 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3084 continue;
3085 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003086
Svet Ganov945864c2018-03-22 21:49:10 -07003087 // Increment the generation first, so observers always see the new value
3088 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3089 mGenerationRegistry.incrementGeneration(key);
3090
Kweku Adams5e0052b2019-02-22 15:17:52 -08003091 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_MODE);
Makoto Onuki0000d322017-11-28 16:31:47 -08003092 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3093 userId, 0, uri).sendToTarget();
3094 }
3095 }
3096
Matt Pape1b31a332018-10-17 09:58:28 -07003097 private boolean isConfigSettingsKey(int key) {
3098 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3099 }
3100
Svetoslav683914b2015-01-15 14:22:26 -08003101 private boolean isGlobalSettingsKey(int key) {
3102 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3103 }
3104
3105 private boolean isSystemSettingsKey(int key) {
3106 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3107 }
3108
3109 private boolean isSecureSettingsKey(int key) {
3110 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3111 }
3112
Mark Rathjend891f012017-01-19 04:10:37 +00003113 private boolean isSsaidSettingsKey(int key) {
3114 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3115 }
3116
Svetoslav683914b2015-01-15 14:22:26 -08003117 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003118 if (isConfigSettingsKey(key)) {
3119 final int userId = getUserIdFromKey(key);
3120 return new File(Environment.getUserSystemDirectory(userId),
3121 SETTINGS_FILE_CONFIG);
3122 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003123 final int userId = getUserIdFromKey(key);
3124 return new File(Environment.getUserSystemDirectory(userId),
3125 SETTINGS_FILE_GLOBAL);
3126 } else if (isSystemSettingsKey(key)) {
3127 final int userId = getUserIdFromKey(key);
3128 return new File(Environment.getUserSystemDirectory(userId),
3129 SETTINGS_FILE_SYSTEM);
3130 } else if (isSecureSettingsKey(key)) {
3131 final int userId = getUserIdFromKey(key);
3132 return new File(Environment.getUserSystemDirectory(userId),
3133 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003134 } else if (isSsaidSettingsKey(key)) {
3135 final int userId = getUserIdFromKey(key);
3136 return new File(Environment.getUserSystemDirectory(userId),
3137 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003138 } else {
3139 throw new IllegalArgumentException("Invalid settings key:" + key);
3140 }
3141 }
3142
3143 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003144 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003145 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3146 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003147 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003148 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3149 : Settings.Global.CONTENT_URI;
3150 } else if (isSecureSettingsKey(key)) {
3151 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3152 : Settings.Secure.CONTENT_URI;
3153 } else if (isSystemSettingsKey(key)) {
3154 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3155 : Settings.System.CONTENT_URI;
3156 } else {
3157 throw new IllegalArgumentException("Invalid settings key:" + key);
3158 }
3159 }
3160
3161 private int getMaxBytesPerPackageForType(int type) {
3162 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003163 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003164 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003165 case SETTINGS_TYPE_SECURE:
3166 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003167 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3168 }
3169
3170 default: {
3171 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3172 }
3173 }
3174 }
3175
Svetoslav7e0683b2015-08-03 16:02:52 -07003176 private final class MyHandler extends Handler {
3177 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3178 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3179
3180 public MyHandler(Looper looper) {
3181 super(looper);
3182 }
3183
3184 @Override
3185 public void handleMessage(Message msg) {
3186 switch (msg.what) {
3187 case MSG_NOTIFY_URI_CHANGED: {
3188 final int userId = msg.arg1;
3189 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003190 try {
3191 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3192 } catch (SecurityException e) {
3193 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3194 }
Varun Shah2ecf7ad2019-10-16 12:30:57 -07003195 if (DEBUG) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003196 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3197 }
3198 } break;
3199
3200 case MSG_NOTIFY_DATA_CHANGED: {
3201 mBackupManager.dataChanged();
3202 } break;
3203 }
3204 }
3205 }
3206
Svetoslav683914b2015-01-15 14:22:26 -08003207 private final class UpgradeController {
Beverlyf364d7c2019-10-10 16:44:43 -04003208 private static final int SETTINGS_VERSION = 184;
Svetoslav683914b2015-01-15 14:22:26 -08003209
3210 private final int mUserId;
3211
3212 public UpgradeController(int userId) {
3213 mUserId = userId;
3214 }
3215
3216 public void upgradeIfNeededLocked() {
3217 // The version of all settings for a user is the same (all users have secure).
3218 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003219 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003220
3221 // Try an update from the current state.
3222 final int oldVersion = secureSettings.getVersionLocked();
3223 final int newVersion = SETTINGS_VERSION;
3224
Svet Ganovc9755bc2015-03-28 13:21:22 -07003225 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003226 if (oldVersion == newVersion) {
3227 return;
3228 }
3229
3230 // Try to upgrade.
3231 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3232
3233 // If upgrade failed start from scratch and upgrade.
3234 if (curVersion != newVersion) {
3235 // Drop state we have for this user.
3236 removeUserStateLocked(mUserId, true);
3237
3238 // Recreate the database.
3239 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3240 SQLiteDatabase database = dbHelper.getWritableDatabase();
3241 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3242
3243 // Migrate the settings for this user.
3244 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3245
3246 // Now upgrade should work fine.
3247 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003248
3249 // Make a note what happened, so we don't wonder why data was lost
3250 String reason = "Settings rebuilt! Current version: "
3251 + curVersion + " while expected: " + newVersion;
3252 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003253 Settings.Global.DATABASE_DOWNGRADE_REASON,
3254 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003255 }
3256
3257 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003258 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003259 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003260 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003261 globalSettings.setVersionLocked(newVersion);
3262 }
3263
3264 // Set the secure settings version.
3265 secureSettings.setVersionLocked(newVersion);
3266
3267 // Set the system settings version.
3268 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003269 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003270 systemSettings.setVersionLocked(newVersion);
3271 }
3272
3273 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003274 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003275 }
3276
3277 private SettingsState getSecureSettingsLocked(int userId) {
3278 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3279 }
3280
Mark Rathjend891f012017-01-19 04:10:37 +00003281 private SettingsState getSsaidSettingsLocked(int userId) {
3282 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3283 }
3284
Svetoslav683914b2015-01-15 14:22:26 -08003285 private SettingsState getSystemSettingsLocked(int userId) {
3286 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3287 }
3288
Jeff Brown503cffc2015-03-26 18:08:51 -07003289 /**
3290 * You must perform all necessary mutations to bring the settings
3291 * for this user from the old to the new version. When you add a new
3292 * upgrade step you *must* update SETTINGS_VERSION.
3293 *
3294 * This is an example of moving a setting from secure to global.
3295 *
3296 * // v119: Example settings changes.
3297 * if (currentVersion == 118) {
3298 * if (userId == UserHandle.USER_OWNER) {
3299 * // Remove from the secure settings.
3300 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3301 * String name = "example_setting_to_move";
3302 * String value = secureSettings.getSetting(name);
3303 * secureSettings.deleteSetting(name);
3304 *
3305 * // Add to the global settings.
3306 * SettingsState globalSettings = getGlobalSettingsLocked();
3307 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3308 * }
3309 *
3310 * // Update the current version.
3311 * currentVersion = 119;
3312 * }
3313 */
Svetoslav683914b2015-01-15 14:22:26 -08003314 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3315 if (DEBUG) {
3316 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3317 + oldVersion + " to version: " + newVersion);
3318 }
3319
Jeff Brown503cffc2015-03-26 18:08:51 -07003320 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003321
John Spurlocke11ae112015-05-11 16:09:03 -04003322 // v119: Reset zen + ringer mode.
3323 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003324 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003325 final SettingsState globalSettings = getGlobalSettingsLocked();
3326 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003327 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3328 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003329 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003330 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3331 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003332 }
3333 currentVersion = 119;
3334 }
3335
Jason Monk27bbb2d2015-03-31 16:46:39 -04003336 // v120: Add double tap to wake setting.
3337 if (currentVersion == 119) {
3338 SettingsState secureSettings = getSecureSettingsLocked(userId);
3339 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3340 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003341 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003342 SettingsState.SYSTEM_PACKAGE_NAME);
3343
3344 currentVersion = 120;
3345 }
3346
Svetoslav7e0683b2015-08-03 16:02:52 -07003347 if (currentVersion == 120) {
3348 // Before 121, we used a different string encoding logic. We just bump the
3349 // version here; SettingsState knows how to handle pre-version 120 files.
3350 currentVersion = 121;
3351 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003352
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003353 if (currentVersion == 121) {
3354 // Version 122: allow OEMs to set a default payment component in resources.
3355 // Note that we only write the default if no default has been set;
3356 // if there is, we just leave the default at whatever it currently is.
3357 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3358 String defaultComponent = (getContext().getResources().getString(
3359 R.string.def_nfc_payment_component));
3360 Setting currentSetting = secureSettings.getSettingLocked(
3361 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3362 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003363 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003364 secureSettings.insertSettingLocked(
3365 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003366 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003367 }
3368 currentVersion = 122;
3369 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003370
3371 if (currentVersion == 122) {
3372 // Version 123: Adding a default value for the ability to add a user from
3373 // the lock screen.
3374 if (userId == UserHandle.USER_SYSTEM) {
3375 final SettingsState globalSettings = getGlobalSettingsLocked();
3376 Setting currentSetting = globalSettings.getSettingLocked(
3377 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003378 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003379 globalSettings.insertSettingLocked(
3380 Settings.Global.ADD_USERS_WHEN_LOCKED,
3381 getContext().getResources().getBoolean(
3382 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003383 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003384 }
3385 }
3386 currentVersion = 123;
3387 }
Bryce Leebd179282015-12-17 19:01:37 -08003388
3389 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003390 final SettingsState globalSettings = getGlobalSettingsLocked();
3391 String defaultDisabledProfiles = (getContext().getResources().getString(
3392 R.string.def_bluetooth_disabled_profiles));
3393 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003394 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003395 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003396 }
3397
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003398 if (currentVersion == 124) {
3399 // Version 124: allow OEMs to set a default value for whether IME should be
3400 // shown when a physical keyboard is connected.
3401 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3402 Setting currentSetting = secureSettings.getSettingLocked(
3403 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003404 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003405 secureSettings.insertSettingLocked(
3406 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3407 getContext().getResources().getBoolean(
3408 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003409 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003410 }
3411 currentVersion = 125;
3412 }
3413
Ruben Brunk98576cf2016-03-07 18:54:28 -08003414 if (currentVersion == 125) {
3415 // Version 125: Allow OEMs to set the default VR service.
3416 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3417
3418 Setting currentSetting = secureSettings.getSettingLocked(
3419 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003420 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003421 ArraySet<ComponentName> l =
3422 SystemConfig.getInstance().getDefaultVrComponents();
3423
3424 if (l != null && !l.isEmpty()) {
3425 StringBuilder b = new StringBuilder();
3426 boolean start = true;
3427 for (ComponentName c : l) {
3428 if (!start) {
3429 b.append(':');
3430 }
3431 b.append(c.flattenToString());
3432 start = false;
3433 }
3434 secureSettings.insertSettingLocked(
3435 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003436 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003437 }
3438
3439 }
3440 currentVersion = 126;
3441 }
3442
Daniel U02ba6122016-04-01 18:41:42 +01003443 if (currentVersion == 126) {
3444 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3445 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3446 if (mUserManager.isManagedProfile(userId)) {
3447 final SettingsState systemSecureSettings =
3448 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3449
3450 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3451 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003452 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003453 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3454 secureSettings.insertSettingLocked(
3455 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003456 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003457 SettingsState.SYSTEM_PACKAGE_NAME);
3458 }
3459
3460 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3461 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003462 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003463 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3464 secureSettings.insertSettingLocked(
3465 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003466 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003467 SettingsState.SYSTEM_PACKAGE_NAME);
3468 }
3469 }
3470 currentVersion = 127;
3471 }
3472
Steven Ngdc20ba62016-04-26 18:19:04 +01003473 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003474 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003475 currentVersion = 128;
3476 }
3477
Julia Reynolds1f721e12016-07-11 08:50:58 -04003478 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003479 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003480 currentVersion = 129;
3481 }
3482
Dan Sandler71f85e92016-07-20 13:46:05 -04003483 if (currentVersion == 129) {
3484 // default longpress timeout changed from 500 to 400. If unchanged from the old
3485 // default, update to the new default.
3486 final SettingsState systemSecureSettings =
3487 getSecureSettingsLocked(userId);
3488 final String oldValue = systemSecureSettings.getSettingLocked(
3489 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3490 if (TextUtils.equals("500", oldValue)) {
3491 systemSecureSettings.insertSettingLocked(
3492 Settings.Secure.LONG_PRESS_TIMEOUT,
3493 String.valueOf(getContext().getResources().getInteger(
3494 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003495 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003496 }
3497 currentVersion = 130;
3498 }
3499
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003500 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003501 // Split Ambient settings
3502 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3503 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3504 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3505
3506 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003507 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003508 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003509 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003510 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003511 }
3512 currentVersion = 131;
3513 }
3514
3515 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003516 // Initialize new multi-press timeout to default value
3517 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3518 final String oldValue = systemSecureSettings.getSettingLocked(
3519 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3520 if (TextUtils.equals(null, oldValue)) {
3521 systemSecureSettings.insertSettingLocked(
3522 Settings.Secure.MULTI_PRESS_TIMEOUT,
3523 String.valueOf(getContext().getResources().getInteger(
3524 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003525 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003526 }
3527
Adrian Roos69741a22016-10-21 14:49:17 -07003528 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003529 }
3530
Adrian Roos69741a22016-10-21 14:49:17 -07003531 if (currentVersion == 132) {
3532 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003533 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3534 String defaultSyncParentSounds = (getContext().getResources()
3535 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3536 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003537 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3538 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003539 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003540 }
3541
Adrian Roos69741a22016-10-21 14:49:17 -07003542 if (currentVersion == 133) {
3543 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003544 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003545 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3546 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003547 String defaultEndButtonBehavior = Integer.toString(getContext()
3548 .getResources().getInteger(R.integer.def_end_button_behavior));
3549 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003550 defaultEndButtonBehavior, null, true,
3551 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003552 }
Adrian Roos69741a22016-10-21 14:49:17 -07003553 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003554 }
3555
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003556 if (currentVersion == 134) {
3557 // Remove setting that specifies if magnification values should be preserved.
3558 // This setting defaulted to true and never has a UI.
3559 getSecureSettingsLocked(userId).deleteSettingLocked(
3560 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3561 currentVersion = 135;
3562 }
3563
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003564 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003565 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003566 currentVersion = 136;
3567 }
3568
Mark Rathjend891f012017-01-19 04:10:37 +00003569 if (currentVersion == 136) {
3570 // Version 136: Store legacy SSAID for all apps currently installed on the
3571 // device as first step in migrating SSAID to be unique per application.
3572
3573 final boolean isUpgrade;
3574 try {
Svet Ganovd8eb8b22019-04-05 18:52:08 -07003575 isUpgrade = mPackageManager.isDeviceUpgrading();
Mark Rathjend891f012017-01-19 04:10:37 +00003576 } catch (RemoteException e) {
3577 throw new IllegalStateException("Package manager not available");
3578 }
3579 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3580 // user data or first boot on a new device should use new ssaid generation.
3581 if (isUpgrade) {
3582 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003583 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3584 userId, Settings.Secure.ANDROID_ID);
3585 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3586 || legacySsaidSetting.getValue() == null) {
3587 throw new IllegalStateException("Legacy ssaid not accessible");
3588 }
3589 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003590
3591 // Fill each uid with the legacy ssaid to be backwards compatible.
3592 final List<PackageInfo> packages;
3593 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003594 packages = mPackageManager.getInstalledPackages(
3595 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3596 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003597 } catch (RemoteException e) {
3598 throw new IllegalStateException("Package manager not available");
3599 }
3600
3601 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3602 for (PackageInfo info : packages) {
3603 // Check if the UID already has an entry in the table.
3604 final String uid = Integer.toString(info.applicationInfo.uid);
3605 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3606
3607 if (ssaid.isNull() || ssaid.getValue() == null) {
3608 // Android Id doesn't exist for this package so create it.
3609 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3610 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003611 if (DEBUG) {
3612 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3613 }
Mark Rathjend891f012017-01-19 04:10:37 +00003614 }
3615 }
3616 }
3617
3618 currentVersion = 137;
3619 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003620 if (currentVersion == 137) {
3621 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3622 // default value set to 1. The user can no longer change the value of this
3623 // setting through the UI.
3624 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3625 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003626 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3627 && secureSetting.getSettingLocked(
3628 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3629
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003630 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3631 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003632 // For managed profiles with profile owners, DevicePolicyManagerService
3633 // may want to set the user restriction in this case
3634 secureSetting.insertSettingLocked(
3635 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3636 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003637 }
3638 currentVersion = 138;
3639 }
Mark Rathjend891f012017-01-19 04:10:37 +00003640
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003641 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003642 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003643 currentVersion = 139;
3644 }
3645
Phil Weaver385912e2017-02-10 10:06:56 -08003646 if (currentVersion == 139) {
3647 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3648 // the user can no longer change the value of this setting through the UI.
3649 // Force to true.
3650 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3651 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3652 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3653 currentVersion = 140;
3654 }
3655
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003656 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003657 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003658 currentVersion = 141;
3659 }
3660
Svet Ganov13701552017-02-23 12:45:17 -08003661 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003662 // This implementation was incorrectly setting the current value of
3663 // settings changed by non-system packages as the default which default
3664 // is set by the system. We add a new upgrade step at the end to properly
3665 // handle this case which would also fix incorrect changes made by the
3666 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003667 currentVersion = 142;
3668 }
3669
Stephen Chen5d0922f2017-03-27 10:28:04 -07003670 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003671 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003672 if (userId == UserHandle.USER_SYSTEM) {
3673 final SettingsState globalSettings = getGlobalSettingsLocked();
3674 Setting currentSetting = globalSettings.getSettingLocked(
3675 Settings.Global.WIFI_WAKEUP_ENABLED);
3676 if (currentSetting.isNull()) {
3677 globalSettings.insertSettingLocked(
3678 Settings.Global.WIFI_WAKEUP_ENABLED,
3679 getContext().getResources().getBoolean(
3680 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3681 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3682 }
3683 }
3684
3685 currentVersion = 143;
3686 }
3687
Felipe Lemeff355092017-04-03 12:55:02 -07003688 if (currentVersion == 143) {
3689 // Version 144: Set a default value for Autofill service.
3690 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3691 final Setting currentSetting = secureSettings
3692 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3693 if (currentSetting.isNull()) {
3694 final String defaultValue = getContext().getResources().getString(
3695 com.android.internal.R.string.config_defaultAutofillService);
3696 if (defaultValue != null) {
3697 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3698 + "for user " + userId);
3699 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3700 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3701 }
3702 }
3703
3704 currentVersion = 144;
3705 }
3706
Jeremy Joslin45caa252017-05-04 11:22:46 -07003707 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003708 // Version 145: Removed
3709 currentVersion = 145;
3710 }
3711
3712 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003713 // Version 146: In step 142 we had a bug where incorrectly
3714 // some settings were considered system set and as a result
3715 // made the default and marked as the default being set by
3716 // the system. Here reevaluate the default and default system
3717 // set flags. This would both fix corruption by the old impl
3718 // of step 142 and also properly handle devices which never
3719 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003720 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003721 SettingsState globalSettings = getGlobalSettingsLocked();
3722 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3723 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003724 }
3725
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003726 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3727 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3728 secureSettings.persistSyncLocked();
3729
3730 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3731 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3732 systemSettings.persistSyncLocked();
3733
Amin Shaikh86367962017-06-07 08:58:22 -07003734 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003735 }
3736
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003737 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003738 // Version 147: Removed. (This version previously allowed showing the
3739 // "wifi_wakeup_available" setting).
3740 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003741 currentVersion = 147;
3742 }
3743
3744 if (currentVersion == 147) {
3745 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003746 if (userId == UserHandle.USER_SYSTEM) {
3747 final SettingsState globalSettings = getGlobalSettingsLocked();
3748 final Setting currentSetting = globalSettings.getSettingLocked(
3749 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3750 if (currentSetting.isNull()) {
3751 globalSettings.insertSettingLocked(
3752 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3753 getContext().getResources().getBoolean(
3754 R.bool.def_restrict_background_data) ? "1" : "0",
3755 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3756 }
3757 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003758 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003759 }
3760
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003761 if (currentVersion == 148) {
3762 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3763 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3764 final String oldValue = systemSecureSettings.getSettingLocked(
3765 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3766 if (TextUtils.equals(null, oldValue)) {
3767 final String defaultValue = getContext().getResources().getString(
3768 R.string.def_backup_manager_constants);
3769 if (!TextUtils.isEmpty(defaultValue)) {
3770 systemSecureSettings.insertSettingLocked(
3771 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3772 true, SettingsState.SYSTEM_PACKAGE_NAME);
3773 }
3774 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003775 currentVersion = 149;
3776 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003777
3778 if (currentVersion == 149) {
3779 // Version 150: Set a default value for mobile data always on
3780 final SettingsState globalSettings = getGlobalSettingsLocked();
3781 final Setting currentSetting = globalSettings.getSettingLocked(
3782 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3783 if (currentSetting.isNull()) {
3784 globalSettings.insertSettingLocked(
3785 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3786 getContext().getResources().getBoolean(
3787 R.bool.def_mobile_data_always_on) ? "1" : "0",
3788 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3789 }
3790
3791 currentVersion = 150;
3792 }
3793
Mike Digman4af4a6f2018-01-16 14:49:38 -08003794 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003795 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003796 currentVersion = 151;
3797 }
3798
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003799 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003800 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3801 // by default but it is now no longer configurable).
3802 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003803 currentVersion = 152;
3804 }
3805
Joe LaPenna250d7842018-01-25 10:19:42 -08003806 if (currentVersion == 152) {
3807 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3808 currentVersion = 153;
3809 }
3810
Ben Linb4df8bc2018-01-29 11:48:20 -08003811 if (currentVersion == 153) {
3812 // Version 154: Read notification badge configuration from config.
3813 // If user has already set the value, don't do anything.
3814 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3815 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3816 Settings.Secure.NOTIFICATION_BADGING);
3817 if (showNotificationBadges.isNull()) {
3818 final boolean defaultValue = getContext().getResources().getBoolean(
3819 com.android.internal.R.bool.config_notificationBadging);
3820 systemSecureSettings.insertSettingLocked(
3821 Secure.NOTIFICATION_BADGING,
3822 defaultValue ? "1" : "0",
3823 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3824 }
3825 currentVersion = 154;
3826 }
3827
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003828 if (currentVersion == 154) {
3829 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3830 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3831 final String oldValue = systemSecureSettings.getSettingLocked(
3832 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3833 if (TextUtils.equals(null, oldValue)) {
3834 final String defaultValue = getContext().getResources().getString(
3835 R.string.def_backup_local_transport_parameters);
3836 if (!TextUtils.isEmpty(defaultValue)) {
3837 systemSecureSettings.insertSettingLocked(
3838 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3839 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3840 }
3841
3842 }
3843 currentVersion = 155;
3844 }
3845
Beverlyda904812018-03-02 09:55:30 -05003846 if (currentVersion == 155) {
Beverlyf364d7c2019-10-10 16:44:43 -04003847 // Version 156: migrated to version 184
Beverlyda904812018-03-02 09:55:30 -05003848 currentVersion = 156;
3849 }
3850
Beverly09da25f2018-02-26 09:17:07 -05003851 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003852 // Version 157: Set a default value for zen duration,
3853 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003854 final SettingsState globalSettings = getGlobalSettingsLocked();
3855 final Setting currentSetting = globalSettings.getSettingLocked(
3856 Global.ZEN_DURATION);
3857 if (currentSetting.isNull()) {
3858 String defaultZenDuration = Integer.toString(getContext()
3859 .getResources().getInteger(R.integer.def_zen_duration));
3860 globalSettings.insertSettingLocked(
3861 Global.ZEN_DURATION, defaultZenDuration,
3862 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3863 }
Beverly09da25f2018-02-26 09:17:07 -05003864 currentVersion = 157;
3865 }
Annie Mengd069a882018-03-13 15:31:40 +00003866
3867 if (currentVersion == 157) {
3868 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3869 final SettingsState globalSettings = getGlobalSettingsLocked();
3870 final String oldValue = globalSettings.getSettingLocked(
3871 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3872 if (TextUtils.equals(null, oldValue)) {
3873 final String defaultValue = getContext().getResources().getString(
3874 R.string.def_backup_agent_timeout_parameters);
3875 if (!TextUtils.isEmpty(defaultValue)) {
3876 globalSettings.insertSettingLocked(
3877 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3878 null, true,
3879 SettingsState.SYSTEM_PACKAGE_NAME);
3880 }
3881 }
3882 currentVersion = 158;
3883 }
Roshan Pius9c396672018-03-02 14:54:13 -08003884
3885 if (currentVersion == 158) {
3886 // Remove setting that specifies wifi bgscan throttling params
3887 getGlobalSettingsLocked().deleteSettingLocked(
3888 "wifi_scan_background_throttle_interval_ms");
3889 getGlobalSettingsLocked().deleteSettingLocked(
3890 "wifi_scan_background_throttle_package_whitelist");
3891 currentVersion = 159;
3892 }
3893
Pavel Grafovc5c97302018-03-19 13:37:15 +00003894 if (currentVersion == 159) {
3895 // Version 160: Hiding notifications from the lockscreen is only available as
3896 // primary user option, profiles can only make them redacted. If a profile was
3897 // configured to not show lockscreen notifications, ensure that at the very
3898 // least these will be come hidden.
3899 if (mUserManager.isManagedProfile(userId)) {
3900 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3901 Setting showNotifications = secureSettings.getSettingLocked(
3902 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3903 // The default value is "1", check if user has turned it off.
3904 if ("0".equals(showNotifications.getValue())) {
3905 secureSettings.insertSettingLocked(
3906 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3907 null /* tag */, false /* makeDefault */,
3908 SettingsState.SYSTEM_PACKAGE_NAME);
3909 }
3910 // The setting is no longer valid for managed profiles, it should be
3911 // treated as if it was set to "1".
3912 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3913 }
3914 currentVersion = 160;
3915 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003916
3917 if (currentVersion == 160) {
3918 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003919 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003920 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3921 final SettingsState globalSettings = getGlobalSettingsLocked();
3922
3923 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003924 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3925 if (TextUtils.equals(null, oldValue)) {
3926 globalSettings.insertSettingLocked(
3927 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3928 Integer.toString(getContext().getResources().getInteger(
3929 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3930 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3931 }
3932
3933 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003934 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3935 if (TextUtils.equals(null, oldValue)) {
3936 globalSettings.insertSettingLocked(
3937 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3938 Integer.toString(getContext().getResources().getInteger(
3939 R.integer.def_sound_trigger_detection_service_op_timeout)),
3940 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3941 }
3942 currentVersion = 161;
3943 }
3944
Mike Digman55272862018-02-20 14:35:17 -08003945 if (currentVersion == 161) {
3946 // Version 161: Add a gesture for silencing phones
3947 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3948 final Setting currentSetting = secureSettings.getSettingLocked(
3949 Secure.VOLUME_HUSH_GESTURE);
3950 if (currentSetting.isNull()) {
3951 secureSettings.insertSettingLocked(
3952 Secure.VOLUME_HUSH_GESTURE,
3953 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3954 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3955 }
3956
3957 currentVersion = 162;
3958 }
3959
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003960 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003961 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003962 currentVersion = 163;
3963 }
3964
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003965 if (currentVersion == 163) {
3966 // Version 163: Update default value of
3967 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3968 final SettingsState settings = getGlobalSettingsLocked();
3969 final Setting currentSetting = settings.getSettingLocked(
3970 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3971 if (currentSetting.isDefaultFromSystem()) {
3972 settings.insertSettingLocked(
3973 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3974 Integer.toString(getContext().getResources().getInteger(
3975 R.integer
3976 .def_max_sound_trigger_detection_service_ops_per_day)),
3977 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3978 }
3979
3980 currentVersion = 164;
3981 }
3982
Julia Reynolds76bfa602018-04-23 09:38:47 -04003983 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003984 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003985 currentVersion = 165;
3986 }
3987
Beverly301e92a2018-04-27 09:43:05 -04003988 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003989 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3990 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003991 currentVersion = 166;
3992 }
3993
Beverly38fcfd02018-05-18 17:33:40 -04003994 if (currentVersion == 166) {
3995 // Version 166: add default values for hush gesture used and manual ringer
3996 // toggle
3997 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3998 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3999 Secure.HUSH_GESTURE_USED);
4000 if (currentHushUsedSetting.isNull()) {
4001 secureSettings.insertSettingLocked(
4002 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4003 SettingsState.SYSTEM_PACKAGE_NAME);
4004 }
4005
4006 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4007 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4008 if (currentRingerToggleCountSetting.isNull()) {
4009 secureSettings.insertSettingLocked(
4010 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4011 SettingsState.SYSTEM_PACKAGE_NAME);
4012 }
4013 currentVersion = 167;
4014 }
4015
Beverly155c9d22018-05-23 18:03:23 -04004016 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004017 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4018 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004019 currentVersion = 168;
4020 }
4021
Michael Wright0e9eeee2018-05-26 00:31:20 +01004022 if (currentVersion == 168) {
4023 // Version 168: by default, vibrate for phone calls
4024 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4025 final Setting currentSetting = systemSettings.getSettingLocked(
4026 Settings.System.VIBRATE_WHEN_RINGING);
4027 if (currentSetting.isNull()) {
4028 systemSettings.insertSettingLocked(
4029 Settings.System.VIBRATE_WHEN_RINGING,
4030 getContext().getResources().getBoolean(
4031 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4032 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4033 }
4034 currentVersion = 169;
4035 }
4036
Nadav Barf9f115d2018-06-24 10:06:50 +03004037 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004038 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4039 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4040 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004041
Beverly91d0a632018-07-02 16:45:00 -04004042 final SettingsState globalSettings = getGlobalSettingsLocked();
4043 final Setting globalZenDuration = globalSettings.getSettingLocked(
4044 Global.ZEN_DURATION);
4045
4046 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4047 final Setting secureZenDuration = secureSettings.getSettingLocked(
4048 Secure.ZEN_DURATION);
4049
4050 // ZEN_DURATION
4051 if (!globalZenDuration.isNull()) {
4052 secureSettings.insertSettingLocked(
4053 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4054 SettingsState.SYSTEM_PACKAGE_NAME);
4055
4056 // set global zen duration setting to null since it's deprecated
4057 globalSettings.insertSettingLocked(
4058 Global.ZEN_DURATION, null, null, true,
4059 SettingsState.SYSTEM_PACKAGE_NAME);
4060 } else if (secureZenDuration.isNull()) {
4061 String defaultZenDuration = Integer.toString(getContext()
4062 .getResources().getInteger(R.integer.def_zen_duration));
4063 secureSettings.insertSettingLocked(
4064 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4065 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004066 }
Beverly91d0a632018-07-02 16:45:00 -04004067
4068 // SHOW_ZEN_SETTINGS_SUGGESTION
4069 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4070 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4071 if (currentShowZenSettingSuggestion.isNull()) {
4072 secureSettings.insertSettingLocked(
4073 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4074 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4075 }
4076
4077 // ZEN_SETTINGS_UPDATED
4078 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4079 Secure.ZEN_SETTINGS_UPDATED);
4080 if (currentUpdatedSetting.isNull()) {
4081 secureSettings.insertSettingLocked(
4082 Secure.ZEN_SETTINGS_UPDATED, "0",
4083 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4084 }
4085
4086 // ZEN_SETTINGS_SUGGESTION_VIEWED
4087 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4088 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4089 if (currentSettingSuggestionViewed.isNull()) {
4090 secureSettings.insertSettingLocked(
4091 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4092 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4093 }
4094
Nadav Barf9f115d2018-06-24 10:06:50 +03004095 currentVersion = 170;
4096 }
4097
Beverly91d0a632018-07-02 16:45:00 -04004098 if (currentVersion == 170) {
4099 // Version 170: Set the default value for Secure Settings:
4100 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4101
4102 final SettingsState globalSettings = getGlobalSettingsLocked();
4103 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4104
4105 // CHARGING_SOUNDS_ENABLED
4106 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4107 Global.CHARGING_SOUNDS_ENABLED);
4108 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4109 Secure.CHARGING_SOUNDS_ENABLED);
4110
4111 if (!globalChargingSoundEnabled.isNull()) {
Beverlyff9c5872019-01-02 15:44:00 -05004112 if (secureChargingSoundsEnabled.isNull()) {
4113 secureSettings.insertSettingLocked(
4114 Secure.CHARGING_SOUNDS_ENABLED,
4115 globalChargingSoundEnabled.getValue(), null, false,
4116 SettingsState.SYSTEM_PACKAGE_NAME);
4117 }
Beverly91d0a632018-07-02 16:45:00 -04004118
4119 // set global charging_sounds_enabled setting to null since it's deprecated
4120 globalSettings.insertSettingLocked(
4121 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4122 SettingsState.SYSTEM_PACKAGE_NAME);
4123 } else if (secureChargingSoundsEnabled.isNull()) {
4124 String defChargingSoundsEnabled = getContext().getResources()
4125 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4126 secureSettings.insertSettingLocked(
4127 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4128 true, SettingsState.SYSTEM_PACKAGE_NAME);
4129 }
4130
4131 // CHARGING_VIBRATION_ENABLED
4132 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4133 Secure.CHARGING_VIBRATION_ENABLED);
4134
4135 if (secureChargingVibrationEnabled.isNull()) {
4136 String defChargingVibrationEnabled = getContext().getResources()
4137 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4138 secureSettings.insertSettingLocked(
4139 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4140 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4141 }
4142
4143 currentVersion = 171;
4144 }
4145
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004146 if (currentVersion == 171) {
4147 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4148 // be muted.
4149 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4150 final Setting currentSetting = systemSettings.getSettingLocked(
4151 Settings.System.MUTE_STREAMS_AFFECTED);
4152 if (!currentSetting.isNull()) {
4153 try {
4154 int currentSettingIntegerValue = Integer.parseInt(
4155 currentSetting.getValue());
4156 if ((currentSettingIntegerValue
4157 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4158 systemSettings.insertSettingLocked(
4159 Settings.System.MUTE_STREAMS_AFFECTED,
4160 Integer.toString(
4161 currentSettingIntegerValue
4162 | (1 << AudioManager.STREAM_VOICE_CALL)),
4163 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4164 }
4165 } catch (NumberFormatException e) {
4166 // remove the setting in case it is not a valid integer
4167 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4168 + "setting, removing setting", e);
4169 systemSettings.deleteSettingLocked(
4170 Settings.System.MUTE_STREAMS_AFFECTED);
4171 }
4172
4173 }
4174 currentVersion = 172;
4175 }
4176
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004177 if (currentVersion == 172) {
4178 // Version 172: Set the default value for Secure Settings: LOCATION_MODE
4179
4180 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4181
4182 final Setting locationMode = secureSettings.getSettingLocked(
4183 Secure.LOCATION_MODE);
4184
4185 if (locationMode.isNull()) {
4186 final Setting locationProvidersAllowed = secureSettings.getSettingLocked(
4187 Secure.LOCATION_PROVIDERS_ALLOWED);
4188
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004189 final int defLocationMode;
4190 if (locationProvidersAllowed.isNull()) {
4191 defLocationMode = getContext().getResources().getInteger(
4192 R.integer.def_location_mode);
4193 } else {
4194 defLocationMode =
4195 !TextUtils.isEmpty(locationProvidersAllowed.getValue())
4196 ? Secure.LOCATION_MODE_ON
4197 : Secure.LOCATION_MODE_OFF;
4198 }
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004199 secureSettings.insertSettingLocked(
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004200 Secure.LOCATION_MODE, Integer.toString(defLocationMode),
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004201 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4202 }
4203
4204 currentVersion = 173;
4205 }
4206
Beverly4179f992019-02-08 11:34:16 -05004207 if (currentVersion == 173) {
4208 // Version 173: Set the default value for Secure Settings: NOTIFICATION_BUBBLES
Lyn Hanb739fa62019-06-27 18:41:11 -07004209 // Removed. Moved NOTIFICATION_BUBBLES to Global Settings.
Beverly4179f992019-02-08 11:34:16 -05004210 currentVersion = 174;
4211 }
4212
Yiwen Chen0305b572019-03-05 11:26:59 -08004213 if (currentVersion == 174) {
4214 // Version 174: Set the default value for Global Settings: APPLY_RAMPING_RINGER
4215
4216 final SettingsState globalSettings = getGlobalSettingsLocked();
4217
4218 Setting currentRampingRingerSetting = globalSettings.getSettingLocked(
4219 Settings.Global.APPLY_RAMPING_RINGER);
4220 if (currentRampingRingerSetting.isNull()) {
4221 globalSettings.insertSettingLocked(
4222 Settings.Global.APPLY_RAMPING_RINGER,
4223 getContext().getResources().getBoolean(
4224 R.bool.def_apply_ramping_ringer) ? "1" : "0", null,
4225 true, SettingsState.SYSTEM_PACKAGE_NAME);
4226 }
4227
4228 currentVersion = 175;
4229 }
4230
wilsonshih5d999e22019-03-20 11:50:42 +08004231 if (currentVersion == 175) {
4232 // Version 175: Set the default value for System Settings:
4233 // RING_VIBRATION_INTENSITY. If the notification vibration intensity has been
4234 // set and ring vibration intensity hasn't, the ring vibration intensity should
4235 // followed notification vibration intensity.
4236
4237 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4238
4239 Setting notificationVibrationIntensity = systemSettings.getSettingLocked(
4240 Settings.System.NOTIFICATION_VIBRATION_INTENSITY);
4241
4242 Setting ringVibrationIntensity = systemSettings.getSettingLocked(
4243 Settings.System.RING_VIBRATION_INTENSITY);
4244
4245 if (!notificationVibrationIntensity.isNull()
4246 && ringVibrationIntensity.isNull()) {
4247 systemSettings.insertSettingLocked(
4248 Settings.System.RING_VIBRATION_INTENSITY,
4249 notificationVibrationIntensity.getValue(),
4250 null , true, SettingsState.SYSTEM_PACKAGE_NAME);
4251 }
4252
4253 currentVersion = 176;
4254 }
4255
Winson Chungd9f2fb32019-03-05 11:10:12 -08004256 if (currentVersion == 176) {
4257 // Version 176: Migrate the existing swipe up setting into the resource overlay
Winson Chung3d5d3b32019-04-24 16:52:47 -07004258 // for the navigation bar interaction mode. We do so only if the
4259 // setting is set.
Winson Chungd9f2fb32019-03-05 11:10:12 -08004260
Winson Chungd9f2fb32019-03-05 11:10:12 -08004261 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4262 final Setting swipeUpSetting = secureSettings.getSettingLocked(
Winson Chung85e74592019-03-06 11:49:22 -08004263 "swipe_up_to_switch_apps_enabled");
Winson Chung3d5d3b32019-04-24 16:52:47 -07004264 if (swipeUpSetting != null && !swipeUpSetting.isNull()
4265 && swipeUpSetting.getValue().equals("1")) {
4266 final IOverlayManager overlayManager = IOverlayManager.Stub.asInterface(
4267 ServiceManager.getService(Context.OVERLAY_SERVICE));
Winson Chungd9f2fb32019-03-05 11:10:12 -08004268 try {
Winson Chung3d5d3b32019-04-24 16:52:47 -07004269 overlayManager.setEnabledExclusiveInCategory(
4270 NAV_BAR_MODE_2BUTTON_OVERLAY, UserHandle.USER_CURRENT);
Winson Chungd9f2fb32019-03-05 11:10:12 -08004271 } catch (RemoteException e) {
4272 throw new IllegalStateException(
4273 "Failed to set nav bar interaction mode overlay");
4274 }
4275 }
4276
4277 currentVersion = 177;
4278 }
4279
Edgar Wangeb8bddb2019-04-19 17:29:49 +08004280 if (currentVersion == 177) {
4281 // Version 177: Set the default value for Secure Settings: AWARE_ENABLED
4282
4283 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4284
4285 final Setting awareEnabled = secureSettings.getSettingLocked(
4286 Secure.AWARE_ENABLED);
4287
4288 if (awareEnabled.isNull()) {
4289 final boolean defAwareEnabled = getContext().getResources().getBoolean(
4290 R.bool.def_aware_enabled);
4291 secureSettings.insertSettingLocked(
4292 Secure.AWARE_ENABLED, defAwareEnabled ? "1" : "0",
4293 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4294 }
4295
4296 currentVersion = 178;
4297 }
4298
Edgar Wangdabc41e2019-05-07 18:53:31 +08004299 if (currentVersion == 178) {
4300 // Version 178: Set the default value for Secure Settings:
4301 // SKIP_GESTURE & SILENCE_GESTURE
4302
4303 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4304
4305 final Setting skipGesture = secureSettings.getSettingLocked(
4306 Secure.SKIP_GESTURE);
4307
4308 if (skipGesture.isNull()) {
4309 final boolean defSkipGesture = getContext().getResources().getBoolean(
4310 R.bool.def_skip_gesture);
4311 secureSettings.insertSettingLocked(
4312 Secure.SKIP_GESTURE, defSkipGesture ? "1" : "0",
4313 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4314 }
4315
4316 final Setting silenceGesture = secureSettings.getSettingLocked(
4317 Secure.SILENCE_GESTURE);
4318
4319 if (silenceGesture.isNull()) {
4320 final boolean defSilenceGesture = getContext().getResources().getBoolean(
4321 R.bool.def_silence_gesture);
4322 secureSettings.insertSettingLocked(
4323 Secure.SILENCE_GESTURE, defSilenceGesture ? "1" : "0",
4324 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4325 }
4326
4327 currentVersion = 179;
4328 }
4329
Mady Mellor95e879a2019-05-06 08:50:06 -07004330 if (currentVersion == 179) {
4331 // Version 178: Reset the default for Secure Settings: NOTIFICATION_BUBBLES
4332 // This is originally set in version 173, however, the default value changed
Lyn Hanb739fa62019-06-27 18:41:11 -07004333 // so this step is to ensure the value is updated to the correct default.
Mady Mellor95e879a2019-05-06 08:50:06 -07004334
Lyn Hanb739fa62019-06-27 18:41:11 -07004335 // Removed. Moved NOTIFICATION_BUBBLES to Global Settings.
Mady Mellor95e879a2019-05-06 08:50:06 -07004336 currentVersion = 180;
4337 }
Winson Chungd9f2fb32019-03-05 11:10:12 -08004338
Edgar Wang4870e4b2019-05-15 19:14:43 +08004339 if (currentVersion == 180) {
4340 // Version 180: Set the default value for Secure Settings: AWARE_LOCK_ENABLED
4341
4342 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4343
4344 final Setting awareLockEnabled = secureSettings.getSettingLocked(
4345 Secure.AWARE_LOCK_ENABLED);
4346
4347 if (awareLockEnabled.isNull()) {
4348 final boolean defAwareLockEnabled = getContext().getResources().getBoolean(
4349 R.bool.def_aware_lock_enabled);
4350 secureSettings.insertSettingLocked(
4351 Secure.AWARE_LOCK_ENABLED, defAwareLockEnabled ? "1" : "0",
4352 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4353 }
4354
4355 currentVersion = 181;
4356 }
4357
Eric Laurent02153e62019-06-12 17:20:03 -07004358 if (currentVersion == 181) {
4359 // Version cd : by default, add STREAM_BLUETOOTH_SCO to list of streams that can
4360 // be muted.
4361 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4362 final Setting currentSetting = systemSettings.getSettingLocked(
4363 Settings.System.MUTE_STREAMS_AFFECTED);
4364 if (!currentSetting.isNull()) {
4365 try {
4366 int currentSettingIntegerValue = Integer.parseInt(
4367 currentSetting.getValue());
4368 if ((currentSettingIntegerValue
4369 & (1 << AudioManager.STREAM_BLUETOOTH_SCO)) == 0) {
4370 systemSettings.insertSettingLocked(
4371 Settings.System.MUTE_STREAMS_AFFECTED,
4372 Integer.toString(
4373 currentSettingIntegerValue
4374 | (1 << AudioManager.STREAM_BLUETOOTH_SCO)),
4375 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4376 }
4377 } catch (NumberFormatException e) {
4378 // remove the setting in case it is not a valid integer
4379 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4380 + "setting, removing setting", e);
4381 systemSettings.deleteSettingLocked(
4382 Settings.System.MUTE_STREAMS_AFFECTED);
4383 }
4384
4385 }
4386 currentVersion = 182;
4387 }
4388
Lyn Hanb739fa62019-06-27 18:41:11 -07004389 if (currentVersion == 182) {
4390 // Remove secure bubble settings.
Mady Mellorfa9556a2019-09-19 11:10:31 -07004391 getSecureSettingsLocked(userId).deleteSettingLocked("notification_bubbles");
Lyn Hanb739fa62019-06-27 18:41:11 -07004392
4393 // Add global bubble settings.
4394 getGlobalSettingsLocked().insertSettingLocked(Global.NOTIFICATION_BUBBLES,
4395 getContext().getResources().getBoolean(
4396 R.bool.def_notification_bubbles) ? "1" : "0", null /* tag */,
4397 true /* makeDefault */, SettingsState.SYSTEM_PACKAGE_NAME);
4398
4399 currentVersion = 183;
4400 }
4401
Beverlyf364d7c2019-10-10 16:44:43 -04004402 if (currentVersion == 183) {
4403 // Version 184: Set default values for WIRELESS_CHARGING_STARTED_SOUND
4404 // and CHARGING_STARTED_SOUND
4405 final SettingsState globalSettings = getGlobalSettingsLocked();
4406
4407 final String oldValueWireless = globalSettings.getSettingLocked(
4408 Global.WIRELESS_CHARGING_STARTED_SOUND).getValue();
4409 final String oldValueWired = globalSettings.getSettingLocked(
4410 Global.CHARGING_STARTED_SOUND).getValue();
4411
4412 final String defaultValueWireless = getContext().getResources().getString(
4413 R.string.def_wireless_charging_started_sound);
4414 final String defaultValueWired = getContext().getResources().getString(
4415 R.string.def_charging_started_sound);
4416
4417 // wireless charging sound
4418 if (oldValueWireless == null
4419 || TextUtils.equals(oldValueWireless, defaultValueWired)) {
4420 if (!TextUtils.isEmpty(defaultValueWireless)) {
4421 globalSettings.insertSettingLocked(
4422 Global.WIRELESS_CHARGING_STARTED_SOUND, defaultValueWireless,
4423 null /* tag */, true /* makeDefault */,
4424 SettingsState.SYSTEM_PACKAGE_NAME);
4425 } else if (!TextUtils.isEmpty(defaultValueWired)) {
4426 // if the wireless sound is empty, use the wired charging sound
4427 globalSettings.insertSettingLocked(
4428 Global.WIRELESS_CHARGING_STARTED_SOUND, defaultValueWired,
4429 null /* tag */, true /* makeDefault */,
4430 SettingsState.SYSTEM_PACKAGE_NAME);
4431 }
4432 }
4433
4434 // wired charging sound
4435 if (oldValueWired == null && !TextUtils.isEmpty(defaultValueWired)) {
4436 globalSettings.insertSettingLocked(
4437 Global.CHARGING_STARTED_SOUND, defaultValueWired,
4438 null /* tag */, true /* makeDefault */,
4439 SettingsState.SYSTEM_PACKAGE_NAME);
4440 }
4441 currentVersion = 184;
4442 }
4443
Felipe Lemeff355092017-04-03 12:55:02 -07004444 // vXXX: Add new settings above this point.
4445
Dan Sandler71f85e92016-07-20 13:46:05 -04004446 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004447 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004448 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004449 + currentVersion +
4450 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4451 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004452 if (DEBUG) {
4453 throw new RuntimeException("db upgrade error");
4454 }
4455 }
4456
Jeff Brown503cffc2015-03-26 18:08:51 -07004457 // Return the current version.
4458 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004459 }
4460 }
Svet Ganov13701552017-02-23 12:45:17 -08004461
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004462 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4463 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004464 List<String> names = settings.getSettingNamesLocked();
4465 final int nameCount = names.size();
4466 for (int i = 0; i < nameCount; i++) {
4467 String name = names.get(i);
4468 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004469
4470 // In the upgrade case we pretend the call is made from the app
4471 // that made the last change to the setting to properly determine
4472 // whether the call has been made by a system component.
4473 int callingUid = -1;
4474 try {
4475 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4476 } catch (RemoteException e) {
4477 /* ignore - handled below */
4478 }
4479 if (callingUid < 0) {
4480 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4481 continue;
4482 }
4483 try {
4484 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07004485 setting.getPackageName(), callingUid, userId);
Svet Ganov13701552017-02-23 12:45:17 -08004486 if (systemSet) {
4487 settings.insertSettingLocked(name, setting.getValue(),
4488 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004489 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4490 // We had a bug where changes by non-system packages were marked
4491 // as system made and as a result set as the default. Therefore, if
4492 // the package changed the setting last is not a system one but the
4493 // setting is marked as its default coming from the system we clear
4494 // the default and clear the system set flag.
4495 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004496 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004497 } catch (IllegalStateException e) {
4498 // If the package goes over its quota during the upgrade, don't
4499 // crash but just log the error as the system does the upgrade.
4500 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4501
Svet Ganov13701552017-02-23 12:45:17 -08004502 }
4503 }
4504 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004505 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004506}