blob: 776593590a67de8cd0e0f970bece68e37d712370 [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";
Matt Pape6bfc62e2018-11-28 13:16:03 -0800157 private static final String TABLE_CONFIG = "config";
Svetoslav683914b2015-01-15 14:22:26 -0800158
159 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private static final String TABLE_FAVORITES = "favorites";
161 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800162 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
163 private static final String TABLE_BOOKMARKS = "bookmarks";
164 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Svetoslav683914b2015-01-15 14:22:26 -0800166 // The set of removed legacy tables.
167 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700168 static {
Svetoslav683914b2015-01-15 14:22:26 -0800169 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
170 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
171 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
172 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
173 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
174 }
Christopher Tate06efb532012-08-24 15:29:27 -0700175
Svetoslav683914b2015-01-15 14:22:26 -0800176 private static final int MUTATION_OPERATION_INSERT = 1;
177 private static final int MUTATION_OPERATION_DELETE = 2;
178 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800179 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400180
Svetoslav683914b2015-01-15 14:22:26 -0800181 private static final String[] ALL_COLUMNS = new String[] {
182 Settings.NameValueTable._ID,
183 Settings.NameValueTable.NAME,
184 Settings.NameValueTable.VALUE
185 };
186
Makoto Onuki53f0e022017-11-29 13:51:01 -0800187 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
188 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
189 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
190 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700191 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700192
193 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
194 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700195
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800196 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800197 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800198
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700199 // Overlay specified settings whitelisted for Instant Apps
200 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
201 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
202 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
203
204 static {
205 for (String name : Resources.getSystem().getStringArray(
206 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
207 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
208 }
209 for (String name : Resources.getSystem().getStringArray(
210 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
211 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
212 }
213 for (String name : Resources.getSystem().getStringArray(
214 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
215 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
216 }
217 }
218
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800219 // Changes to these global settings are synchronously persisted
220 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
221 static {
222 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
223 }
224
225 // Changes to these secure settings are synchronously persisted
226 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
227 static {
228 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
229 }
230
Svetoslav683914b2015-01-15 14:22:26 -0800231 // Per user secure settings that moved to the for all users global settings.
232 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
233 static {
234 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700235 }
236
Svetoslav683914b2015-01-15 14:22:26 -0800237 // Per user system settings that moved to the for all users global settings.
238 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
239 static {
240 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700241 }
242
Svetoslav683914b2015-01-15 14:22:26 -0800243 // Per user system settings that moved to the per user secure settings.
244 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
245 static {
246 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247 }
248
Svetoslav683914b2015-01-15 14:22:26 -0800249 // Per all users global settings that moved to the per user secure settings.
250 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
251 static {
252 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700253 }
254
Svetoslav683914b2015-01-15 14:22:26 -0800255 // Per user secure settings that are cloned for the managed profiles of the user.
256 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
257 static {
258 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700259 }
260
Svetoslav683914b2015-01-15 14:22:26 -0800261 // Per user system settings that are cloned for the managed profiles of the user.
262 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
263 static {
264 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400265 }
266
Andre Lago3fa139c2016-08-04 13:53:44 +0100267 // Per user system settings that are cloned from the profile's parent when a dependency
268 // in {@link Settings.Secure} is set to "1".
269 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
270 static {
271 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
272 }
273
Svetoslav683914b2015-01-15 14:22:26 -0800274 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700275
Svetoslav683914b2015-01-15 14:22:26 -0800276 @GuardedBy("mLock")
277 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700278
Svet Ganova8f90262016-05-10 08:44:48 -0700279 @GuardedBy("mLock")
280 private HandlerThread mHandlerThread;
281
Makoto Onuki73360ab2017-03-17 11:50:13 -0700282 @GuardedBy("mLock")
283 private Handler mHandler;
284
Svetoslav7ec28e82015-05-20 17:01:10 -0700285 // We have to call in the user manager with no lock held,
286 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800287
Svetoslav7ec28e82015-05-20 17:01:10 -0700288 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700289 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700290
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800292 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700293 }
294
295 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800296 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700297 }
298
299 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800300 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700301 }
302
303 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800304 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700305 }
306
307 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800308 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700309 }
310
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311 @Override
312 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800313 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000314
Svetoslav683914b2015-01-15 14:22:26 -0800315 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700316 mUserManager = UserManager.get(getContext());
317 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700318 mHandlerThread = new HandlerThread(LOG_TAG,
319 Process.THREAD_PRIORITY_BACKGROUND);
320 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700321 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800322 mSettingsRegistry = new SettingsRegistry();
323 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700324 mHandler.post(() -> {
325 registerBroadcastReceivers();
326 startWatchingUserRestrictionChanges();
327 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700328 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800329 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330 return true;
331 }
332
Svetoslav683914b2015-01-15 14:22:26 -0800333 @Override
334 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700335 final int requestingUserId = getRequestingUserId(args);
336 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700337 case Settings.CALL_METHOD_GET_CONFIG: {
338 Setting setting = getConfigSetting(name);
339 return packageValueForCallResult(setting, isTrackingGeneration(args));
340 }
341
Svetoslav7ec28e82015-05-20 17:01:10 -0700342 case Settings.CALL_METHOD_GET_GLOBAL: {
343 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700344 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800345 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700346
347 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800348 Setting setting = getSecureSetting(name, requestingUserId,
349 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700350 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700351 }
352
353 case Settings.CALL_METHOD_GET_SYSTEM: {
354 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700355 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700356 }
357
Matt Pape1b31a332018-10-17 09:58:28 -0700358 case Settings.CALL_METHOD_PUT_CONFIG: {
359 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700360 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800361 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700362 break;
363 }
364
Svetoslav7ec28e82015-05-20 17:01:10 -0700365 case Settings.CALL_METHOD_PUT_GLOBAL: {
366 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800367 String tag = getSettingTag(args);
368 final boolean makeDefault = getSettingMakeDefault(args);
369 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700370 break;
371 }
372
373 case Settings.CALL_METHOD_PUT_SECURE: {
374 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800375 String tag = getSettingTag(args);
376 final boolean makeDefault = getSettingMakeDefault(args);
377 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700378 break;
379 }
380
381 case Settings.CALL_METHOD_PUT_SYSTEM: {
382 String value = getSettingValue(args);
383 insertSystemSetting(name, value, requestingUserId);
384 break;
385 }
386
Matt Pape1b31a332018-10-17 09:58:28 -0700387 case Settings.CALL_METHOD_RESET_CONFIG: {
388 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800389 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800390 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700391 break;
392 }
393
Svetoslav Ganove080da92016-12-21 17:10:35 -0800394 case Settings.CALL_METHOD_RESET_GLOBAL: {
395 final int mode = getResetModeEnforcingPermission(args);
396 String tag = getSettingTag(args);
397 resetGlobalSetting(requestingUserId, mode, tag);
398 break;
399 }
400
401 case Settings.CALL_METHOD_RESET_SECURE: {
402 final int mode = getResetModeEnforcingPermission(args);
403 String tag = getSettingTag(args);
404 resetSecureSetting(requestingUserId, mode, tag);
405 break;
406 }
407
Matt Pape6bfc62e2018-11-28 13:16:03 -0800408 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800409 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800410 Bundle result = new Bundle();
411 result.putInt(RESULT_ROWS_DELETED, rows);
412 return result;
413 }
414
415 case Settings.CALL_METHOD_DELETE_GLOBAL: {
416 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
417 Bundle result = new Bundle();
418 result.putInt(RESULT_ROWS_DELETED, rows);
419 return result;
420 }
421
Matt Pape6bfc62e2018-11-28 13:16:03 -0800422 case Settings.CALL_METHOD_DELETE_SECURE: {
423 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
424 Bundle result = new Bundle();
425 result.putInt(RESULT_ROWS_DELETED, rows);
426 return result;
427 }
428
429 case Settings.CALL_METHOD_DELETE_SYSTEM: {
430 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
431 Bundle result = new Bundle();
432 result.putInt(RESULT_ROWS_DELETED, rows);
433 return result;
434 }
435
436 case Settings.CALL_METHOD_LIST_CONFIG: {
437 String prefix = getSettingPrefix(args);
Matt Pape793b15c2019-10-07 13:17:20 -0700438 return packageValuesForCallResult(getAllConfigFlags(prefix),
439 isTrackingGeneration(args));
Matt Pape6bfc62e2018-11-28 13:16:03 -0800440 }
441
442 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800443 Bundle result = new Bundle();
444 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800445 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800446 return result;
447 }
448
449 case Settings.CALL_METHOD_LIST_SECURE: {
450 Bundle result = new Bundle();
451 result.putStringArrayList(RESULT_SETTINGS_LIST,
452 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
453 return result;
454 }
455
Matt Pape6bfc62e2018-11-28 13:16:03 -0800456 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800457 Bundle result = new Bundle();
458 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800459 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800460 return result;
461 }
462
Svetoslav7ec28e82015-05-20 17:01:10 -0700463 default: {
464 Slog.w(LOG_TAG, "call() with invalid method: " + method);
465 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700466 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700467
Christopher Tate06efb532012-08-24 15:29:27 -0700468 return null;
469 }
470
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800471 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800472 public String getType(Uri uri) {
473 Arguments args = new Arguments(uri, null, null, true);
474 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700475 return "vnd.android.cursor.dir/" + args.table;
476 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700477 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 }
479 }
480
481 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800482 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
483 String order) {
484 if (DEBUG) {
485 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700486 }
487
Svetoslav683914b2015-01-15 14:22:26 -0800488 Arguments args = new Arguments(uri, where, whereArgs, true);
489 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490
Svetoslav683914b2015-01-15 14:22:26 -0800491 // If a legacy table that is gone, done.
492 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
493 return new MatrixCursor(normalizedProjection, 0);
494 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700495
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 switch (args.table) {
497 case TABLE_GLOBAL: {
498 if (args.name != null) {
499 Setting setting = getGlobalSetting(args.name);
500 return packageSettingForQuery(setting, normalizedProjection);
501 } else {
502 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700503 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700504 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700505
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 case TABLE_SECURE: {
507 final int userId = UserHandle.getCallingUserId();
508 if (args.name != null) {
509 Setting setting = getSecureSetting(args.name, userId);
510 return packageSettingForQuery(setting, normalizedProjection);
511 } else {
512 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800513 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700514 }
Svetoslav683914b2015-01-15 14:22:26 -0800515
Svetoslav7ec28e82015-05-20 17:01:10 -0700516 case TABLE_SYSTEM: {
517 final int userId = UserHandle.getCallingUserId();
518 if (args.name != null) {
519 Setting setting = getSystemSetting(args.name, userId);
520 return packageSettingForQuery(setting, normalizedProjection);
521 } else {
522 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800523 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 }
Svetoslav683914b2015-01-15 14:22:26 -0800525
Svetoslav7ec28e82015-05-20 17:01:10 -0700526 default: {
527 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700528 }
529 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700530 }
531
Nicholas Sauer72500532018-11-21 10:30:58 -0800532 private ArrayList<String> buildSettingsList(Cursor cursor) {
533 final ArrayList<String> lines = new ArrayList<String>();
534 try {
535 while (cursor != null && cursor.moveToNext()) {
536 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
537 }
538 } finally {
539 if (cursor != null) {
540 cursor.close();
541 }
542 }
543 return lines;
544 }
545
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700546 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800547 public Uri insert(Uri uri, ContentValues values) {
548 if (DEBUG) {
549 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700550 }
551
Svetoslav683914b2015-01-15 14:22:26 -0800552 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700553
Svetoslav683914b2015-01-15 14:22:26 -0800554 // If a legacy table that is gone, done.
555 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 return null;
557 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700558
Svetoslav683914b2015-01-15 14:22:26 -0800559 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700560 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800561 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700562 }
563
Svetoslav683914b2015-01-15 14:22:26 -0800564 String value = values.getAsString(Settings.Secure.VALUE);
565
Svetoslav7ec28e82015-05-20 17:01:10 -0700566 switch (table) {
567 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800568 if (insertGlobalSetting(name, value, null, false,
569 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700570 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700571 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 } break;
573
574 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800575 if (insertSecureSetting(name, value, null, false,
576 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700577 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
578 }
579 } break;
580
581 case TABLE_SYSTEM: {
582 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
583 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
584 }
585 } break;
586
587 default: {
588 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700589 }
590 }
591
Svetoslav683914b2015-01-15 14:22:26 -0800592 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593 }
594
595 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800596 public int bulkInsert(Uri uri, ContentValues[] allValues) {
597 if (DEBUG) {
598 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700600
Svetoslav683914b2015-01-15 14:22:26 -0800601 int insertionCount = 0;
602 final int valuesCount = allValues.length;
603 for (int i = 0; i < valuesCount; i++) {
604 ContentValues values = allValues[i];
605 if (insert(uri, values) != null) {
606 insertionCount++;
607 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700608 }
Svetoslav683914b2015-01-15 14:22:26 -0800609
610 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700611 }
612
613 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800614 public int delete(Uri uri, String where, String[] whereArgs) {
615 if (DEBUG) {
616 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700618
Svetoslav683914b2015-01-15 14:22:26 -0800619 Arguments args = new Arguments(uri, where, whereArgs, false);
620
621 // If a legacy table that is gone, done.
622 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
623 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700624 }
Svetoslav683914b2015-01-15 14:22:26 -0800625
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700626 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800627 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700628 }
Svetoslav683914b2015-01-15 14:22:26 -0800629
Svetoslav7ec28e82015-05-20 17:01:10 -0700630 switch (args.table) {
631 case TABLE_GLOBAL: {
632 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700633 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700634 }
Svetoslav683914b2015-01-15 14:22:26 -0800635
Svetoslav7ec28e82015-05-20 17:01:10 -0700636 case TABLE_SECURE: {
637 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700638 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700639 }
Svetoslav683914b2015-01-15 14:22:26 -0800640
Svetoslav7ec28e82015-05-20 17:01:10 -0700641 case TABLE_SYSTEM: {
642 final int userId = UserHandle.getCallingUserId();
643 return deleteSystemSetting(args.name, userId) ? 1 : 0;
644 }
645
646 default: {
647 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800648 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700649 }
Svetoslav683914b2015-01-15 14:22:26 -0800650 }
651
652 @Override
653 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
654 if (DEBUG) {
655 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700656 }
Svetoslav683914b2015-01-15 14:22:26 -0800657
658 Arguments args = new Arguments(uri, where, whereArgs, false);
659
660 // If a legacy table that is gone, done.
661 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
662 return 0;
663 }
664
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700665 String name = values.getAsString(Settings.Secure.NAME);
666 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800667 return 0;
668 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700669 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800670
Svetoslav7ec28e82015-05-20 17:01:10 -0700671 switch (args.table) {
672 case TABLE_GLOBAL: {
673 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800674 return updateGlobalSetting(args.name, value, null, false,
675 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700676 }
Svetoslav683914b2015-01-15 14:22:26 -0800677
Svetoslav7ec28e82015-05-20 17:01:10 -0700678 case TABLE_SECURE: {
679 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800680 return updateSecureSetting(args.name, value, null, false,
681 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700682 }
Svetoslav683914b2015-01-15 14:22:26 -0800683
Svetoslav7ec28e82015-05-20 17:01:10 -0700684 case TABLE_SYSTEM: {
685 final int userId = UserHandle.getCallingUserId();
686 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
687 }
Svetoslav683914b2015-01-15 14:22:26 -0800688
Svetoslav7ec28e82015-05-20 17:01:10 -0700689 default: {
690 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800691 }
692 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700693 }
694
695 @Override
696 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100697 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
698 if (userId != UserHandle.getCallingUserId()) {
699 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
700 "Access files from the settings of another user");
701 }
702 uri = ContentProvider.getUriWithoutUserId(uri);
703
Andre Lago3fa139c2016-08-04 13:53:44 +0100704 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700705 final String cacheName;
706 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100707 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700708 cacheName = Settings.System.RINGTONE_CACHE;
709 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100710 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700711 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
712 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100713 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700714 cacheName = Settings.System.ALARM_ALERT_CACHE;
715 } else {
716 throw new FileNotFoundException("Direct file access no longer supported; "
717 + "ringtone playback is available through android.media.Ringtone");
718 }
719
Andre Lago3fa139c2016-08-04 13:53:44 +0100720 int actualCacheOwner;
721 // Redirect cache to parent if ringtone setting is owned by profile parent
722 synchronized (mLock) {
723 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
724 cacheRingtoneSetting);
725 }
726 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700727 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
728 }
729
730 private File getRingtoneCacheDir(int userId) {
731 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
732 cacheDir.mkdir();
733 SELinux.restorecon(cacheDir);
734 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700735 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800736
Eugene Suslad72c3972016-12-27 15:49:30 -0800737 /**
738 * Dump all settings as a proto buf.
739 *
740 * @param fd The file to dump to
741 */
742 void dumpProto(@NonNull FileDescriptor fd) {
743 ProtoOutputStream proto = new ProtoOutputStream(fd);
744
745 synchronized (mLock) {
746 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800747 }
748
749 proto.flush();
750 }
751
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700752 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800753 synchronized (mLock) {
754 final long identity = Binder.clearCallingIdentity();
755 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700756 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800757 final int userCount = users.size();
758 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700759 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800760 }
761 } finally {
762 Binder.restoreCallingIdentity(identity);
763 }
764 }
765 }
766
Andreas Gampeb58893072018-09-05 16:52:31 -0700767 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700768 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700769 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700770 pw.println("CONFIG SETTINGS (user " + userId + ")");
771 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
772 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
773 if (configSettings != null) {
774 dumpSettingsLocked(configSettings, pw);
775 pw.println();
776 configSettings.dumpHistoricalOperations(pw);
777 }
778
Svetoslavb505ccc2015-02-17 12:41:04 -0800779 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700780 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
781 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700782 if (globalSettings != null) {
783 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800784 pw.println();
785 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700786 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800787 }
788
789 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700790 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
791 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700792 if (secureSettings != null) {
793 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800794 pw.println();
795 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700796 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700797
Svetoslavb505ccc2015-02-17 12:41:04 -0800798 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700799 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
800 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700801 if (systemSettings != null) {
802 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800803 pw.println();
804 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700805 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800806 }
807
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700808 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
809 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800810
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700811 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800812
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700813 for (int i = 0; i < nameCount; i++) {
814 String name = names.get(i);
815 Setting setting = settingsState.getSettingLocked(name);
816 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
817 pw.print(" name:"); pw.print(toDumpString(name));
818 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800819 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700820 }
821 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800822 if (setting.getDefaultValue() != null) {
823 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800824 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800825 }
826 if (setting.getTag() != null) {
827 pw.print(" tag:"); pw.print(setting.getTag());
828 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800829 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700830 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800831 }
832
Svetoslav7e0683b2015-08-03 16:02:52 -0700833 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700834 if (s != null) {
835 return s;
836 }
837 return "{null}";
838 }
839
Svetoslav683914b2015-01-15 14:22:26 -0800840 private void registerBroadcastReceivers() {
841 IntentFilter userFilter = new IntentFilter();
842 userFilter.addAction(Intent.ACTION_USER_REMOVED);
843 userFilter.addAction(Intent.ACTION_USER_STOPPED);
844
845 getContext().registerReceiver(new BroadcastReceiver() {
846 @Override
847 public void onReceive(Context context, Intent intent) {
848 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700849 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800850
851 switch (intent.getAction()) {
852 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700853 synchronized (mLock) {
854 mSettingsRegistry.removeUserStateLocked(userId, true);
855 }
Svetoslav683914b2015-01-15 14:22:26 -0800856 } break;
857
858 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700859 synchronized (mLock) {
860 mSettingsRegistry.removeUserStateLocked(userId, false);
861 }
Svetoslav683914b2015-01-15 14:22:26 -0800862 } break;
863 }
864 }
865 }, userFilter);
866
867 PackageMonitor monitor = new PackageMonitor() {
868 @Override
869 public void onPackageRemoved(String packageName, int uid) {
870 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100871 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800872 UserHandle.getUserId(uid));
873 }
874 }
Mark Rathjend891f012017-01-19 04:10:37 +0000875
876 @Override
877 public void onUidRemoved(int uid) {
878 synchronized (mLock) {
879 mSettingsRegistry.onUidRemovedLocked(uid);
880 }
881 }
Zimuzoc56192c2018-07-25 10:40:01 +0100882
883 @Override
884 public void onPackageDataCleared(String packageName, int uid) {
885 synchronized (mLock) {
886 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
887 UserHandle.getUserId(uid));
888 }
889 }
Svetoslav683914b2015-01-15 14:22:26 -0800890 };
891
892 // package changes
893 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
894 UserHandle.ALL, true);
895 }
896
Svet Ganov53a441c2016-04-19 19:38:00 -0700897 private void startWatchingUserRestrictionChanges() {
898 // TODO: The current design of settings looking different based on user restrictions
899 // should be reworked to keep them separate and system code should check the setting
900 // first followed by checking the user restriction before performing an operation.
Christopher Tate65fb2e42019-10-11 17:00:23 -0700901 IUserRestrictionsListener listener = new IUserRestrictionsListener.Stub() {
902 @Override
903 public void onUserRestrictionsChanged(int userId,
904 Bundle newRestrictions, Bundle prevRestrictions) {
905 Set<String> changedRestrictions =
906 getRestrictionDiff(prevRestrictions, newRestrictions);
907 // We are changing the settings affected by restrictions to their current
908 // value with a forced update to ensure that all cross profile dependencies
909 // are taken into account. Also make sure the settings update to.. the same
910 // value passes the security checks, so clear binder calling id.
911 if (changedRestrictions.contains(UserManager.DISALLOW_SHARE_LOCATION)) {
912 final long identity = Binder.clearCallingIdentity();
913 try {
914 synchronized (mLock) {
915 Setting setting = getSecureSetting(
916 Settings.Secure.LOCATION_MODE, userId);
917 updateSecureSetting(Settings.Secure.LOCATION_MODE,
918 setting != null ? setting.getValue() : null, null,
919 true, userId, true);
920 setting = getSecureSetting(
921 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
922 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
923 setting != null ? setting.getValue() : null, null,
924 true, userId, true);
925 }
926 } finally {
927 Binder.restoreCallingIdentity(identity);
Svet Ganov53a441c2016-04-19 19:38:00 -0700928 }
Christopher Tate65fb2e42019-10-11 17:00:23 -0700929 }
930 if (changedRestrictions.contains(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
931 || changedRestrictions.contains(
932 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
933 final long identity = Binder.clearCallingIdentity();
934 try {
935 synchronized (mLock) {
936 Setting setting = getGlobalSetting(
937 Settings.Global.INSTALL_NON_MARKET_APPS);
938 String value = setting != null ? setting.getValue() : null;
939 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
940 value, null, true, userId, true);
941 }
942 } finally {
943 Binder.restoreCallingIdentity(identity);
944 }
945 }
946 if (changedRestrictions.contains(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
947 final long identity = Binder.clearCallingIdentity();
948 try {
949 synchronized (mLock) {
950 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
951 String value = setting != null ? setting.getValue() : null;
952 updateGlobalSetting(Settings.Global.ADB_ENABLED,
953 value, null, true, userId, true);
954 }
955 } finally {
956 Binder.restoreCallingIdentity(identity);
957 }
958 }
959 if (changedRestrictions.contains(UserManager.ENSURE_VERIFY_APPS)) {
960 final long identity = Binder.clearCallingIdentity();
961 try {
962 synchronized (mLock) {
963 Setting enable = getGlobalSetting(
964 Settings.Global.PACKAGE_VERIFIER_ENABLE);
965 String enableValue = enable != null ? enable.getValue() : null;
966 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
967 enableValue, null, true, userId, true);
968 Setting include = getGlobalSetting(
969 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
970 String includeValue = include != null ? include.getValue() : null;
971 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
972 includeValue, null, true, userId, true);
973 }
974 } finally {
975 Binder.restoreCallingIdentity(identity);
976 }
977 }
978 if (changedRestrictions.contains(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
979 final long identity = Binder.clearCallingIdentity();
980 try {
981 synchronized (mLock) {
982 Setting setting = getGlobalSetting(
983 Settings.Global.PREFERRED_NETWORK_MODE);
984 String value = setting != null ? setting.getValue() : null;
985 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
986 value, null, true, userId, true);
987 }
988 } finally {
989 Binder.restoreCallingIdentity(identity);
990 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700991 }
992 }
Christopher Tate65fb2e42019-10-11 17:00:23 -0700993 };
994 mUserManager.addUserRestrictionsListener(listener);
Svet Ganov53a441c2016-04-19 19:38:00 -0700995 }
996
Irina Dumitrescue3696872019-01-09 16:07:59 +0000997 private static Set<String> getRestrictionDiff(Bundle prevRestrictions, Bundle newRestrictions) {
998 Set<String> restrictionNames = Sets.newArraySet();
999 restrictionNames.addAll(prevRestrictions.keySet());
1000 restrictionNames.addAll(newRestrictions.keySet());
1001 Set<String> diff = Sets.newArraySet();
1002 for (String restrictionName : restrictionNames) {
1003 if (prevRestrictions.getBoolean(restrictionName) != newRestrictions.getBoolean(
1004 restrictionName)) {
1005 diff.add(restrictionName);
1006 }
1007 }
1008 return diff;
1009 }
1010
Matt Pape1b31a332018-10-17 09:58:28 -07001011 private Setting getConfigSetting(String name) {
1012 if (DEBUG) {
1013 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1014 }
1015
Stanislav Zholnin55799502019-03-08 14:54:55 +00001016 DeviceConfig.enforceReadPermission(getContext(), /*namespace=*/name.split("/")[0]);
Matt Pape1b31a332018-10-17 09:58:28 -07001017
1018 // Get the value.
1019 synchronized (mLock) {
1020 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1021 UserHandle.USER_SYSTEM, name);
1022 }
1023 }
1024
Matt Papec1323dc2018-12-11 12:32:42 -08001025 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001026 if (DEBUG) {
1027 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001028 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001029 }
Matt Papec1323dc2018-12-11 12:32:42 -08001030 return mutateConfigSetting(name, value, null, makeDefault,
1031 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001032 }
1033
Matt Papec1323dc2018-12-11 12:32:42 -08001034 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001035 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001036 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001037 }
Matt Papec1323dc2018-12-11 12:32:42 -08001038 return mutateConfigSetting(name, null, null, false,
1039 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001040 }
1041
Matt Papec1323dc2018-12-11 12:32:42 -08001042 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001043 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001044 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001045 }
Matt Papec1323dc2018-12-11 12:32:42 -08001046 mutateConfigSetting(null, null, prefix, false,
1047 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001048 }
1049
Matt Pape6bfc62e2018-11-28 13:16:03 -08001050 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001051 boolean makeDefault, int operation, int mode) {
Stanislav Zholnin5a25a842019-03-13 14:43:26 +00001052 enforceWritePermission(Manifest.permission.WRITE_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001053
Matt Pape1b31a332018-10-17 09:58:28 -07001054 // Perform the mutation.
1055 synchronized (mLock) {
1056 switch (operation) {
1057 case MUTATION_OPERATION_INSERT: {
1058 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001059 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001060 resolveCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001061 }
1062
Matt Pape6bfc62e2018-11-28 13:16:03 -08001063 case MUTATION_OPERATION_DELETE: {
1064 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001065 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001066 }
1067
Matt Pape1b31a332018-10-17 09:58:28 -07001068 case MUTATION_OPERATION_RESET: {
1069 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001070 UserHandle.USER_SYSTEM, resolveCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001071 } return true;
1072 }
1073 }
1074
1075 return false;
1076 }
1077
Matt Pape793b15c2019-10-07 13:17:20 -07001078 private HashMap<String, String> getAllConfigFlags(@Nullable String prefix) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001079 if (DEBUG) {
1080 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1081 }
1082
Matt Pape91beb9c2019-10-17 15:20:34 -07001083 DeviceConfig.enforceReadPermission(getContext(),
1084 prefix != null ? prefix.split("/")[0] : null);
1085
Matt Pape6bfc62e2018-11-28 13:16:03 -08001086 synchronized (mLock) {
1087 // Get the settings.
1088 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1089 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001090 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1091 UserHandle.USER_SYSTEM);
1092
1093 final int nameCount = names.size();
Matt Pape793b15c2019-10-07 13:17:20 -07001094 HashMap<String, String> flagsToValues = new HashMap<>(names.size());
Matt Pape6bfc62e2018-11-28 13:16:03 -08001095
1096 for (int i = 0; i < nameCount; i++) {
1097 String name = names.get(i);
1098 Setting setting = settingsState.getSettingLocked(name);
1099 if (prefix == null || setting.getName().startsWith(prefix)) {
1100 flagsToValues.put(setting.getName(), setting.getValue());
1101 }
1102 }
1103
1104 return flagsToValues;
1105 }
1106 }
1107
Svetoslav7ec28e82015-05-20 17:01:10 -07001108 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001109 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001110 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001111 }
1112
Svetoslav7ec28e82015-05-20 17:01:10 -07001113 synchronized (mLock) {
1114 // Get the settings.
1115 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001116 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001117
Chad Brubaker97bccee2017-01-05 15:51:41 -08001118 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1119 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001120
Svetoslav7ec28e82015-05-20 17:01:10 -07001121 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001122
Svetoslav7ec28e82015-05-20 17:01:10 -07001123 String[] normalizedProjection = normalizeProjection(projection);
1124 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001125
Svetoslav7ec28e82015-05-20 17:01:10 -07001126 // Anyone can get the global settings, so no security checks.
1127 for (int i = 0; i < nameCount; i++) {
1128 String name = names.get(i);
1129 Setting setting = settingsState.getSettingLocked(name);
1130 appendSettingToCursor(result, setting);
1131 }
1132
1133 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001134 }
Svetoslav683914b2015-01-15 14:22:26 -08001135 }
1136
Svetoslav7ec28e82015-05-20 17:01:10 -07001137 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001138 if (DEBUG) {
1139 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1140 }
1141
Chad Brubakera6830e72017-04-28 17:34:36 -07001142 // Ensure the caller can access the setting.
1143 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1144
Svetoslav683914b2015-01-15 14:22:26 -08001145 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001146 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001147 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001148 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001149 }
Svetoslav683914b2015-01-15 14:22:26 -08001150 }
1151
Svetoslav Ganove080da92016-12-21 17:10:35 -08001152 private boolean updateGlobalSetting(String name, String value, String tag,
1153 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001154 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001155 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1156 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1157 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001158 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001159 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1160 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001161 }
1162
Svetoslav Ganove080da92016-12-21 17:10:35 -08001163 private boolean insertGlobalSetting(String name, String value, String tag,
1164 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001166 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1167 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1168 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001169 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001170 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1171 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001172 }
1173
Svet Ganov53a441c2016-04-19 19:38:00 -07001174 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001175 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001176 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1177 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001178 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001179 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1180 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001181 }
1182
Svetoslav Ganove080da92016-12-21 17:10:35 -08001183 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1184 if (DEBUG) {
1185 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1186 + mode + ", " + tag + ")");
1187 }
1188 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1189 MUTATION_OPERATION_RESET, false, mode);
1190 }
1191
Christopher Tate65fb2e42019-10-11 17:00:23 -07001192 private boolean isSettingRestrictedForUser(String name, int userId,
1193 String value, int callerUid) {
1194 final long oldId = Binder.clearCallingIdentity();
1195 try {
1196 return (name != null
1197 && mUserManager.isSettingRestrictedForUser(name, userId, value, callerUid));
1198 } finally {
1199 Binder.restoreCallingIdentity(oldId);
1200 }
1201 }
1202
Svetoslav Ganove080da92016-12-21 17:10:35 -08001203 private boolean mutateGlobalSetting(String name, String value, String tag,
1204 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1205 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001206 // Make sure the caller can change the settings - treated as secure.
1207 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1208
Svetoslav683914b2015-01-15 14:22:26 -08001209 // Resolve the userId on whose behalf the call is made.
1210 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1211
Makoto Onuki28da2e32015-11-20 11:30:44 -08001212 // If this is a setting that is currently restricted for this user, do not allow
1213 // unrestricting changes.
Christopher Tate65fb2e42019-10-11 17:00:23 -07001214 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001215 return false;
1216 }
1217
1218 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 synchronized (mLock) {
1220 switch (operation) {
1221 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001222 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1223 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001224 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001225 }
Svetoslav683914b2015-01-15 14:22:26 -08001226
Svetoslav7ec28e82015-05-20 17:01:10 -07001227 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001228 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001229 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001230 }
Svetoslav683914b2015-01-15 14:22:26 -08001231
Svetoslav7ec28e82015-05-20 17:01:10 -07001232 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001233 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1234 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001235 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001236 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001237
1238 case MUTATION_OPERATION_RESET: {
1239 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1240 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1241 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001242 }
1243 }
1244
1245 return false;
1246 }
1247
Christopher Tateb218e762017-04-05 16:34:07 -07001248 private PackageInfo getCallingPackageInfo(int userId) {
1249 try {
1250 return mPackageManager.getPackageInfo(getCallingPackage(),
1251 PackageManager.GET_SIGNATURES, userId);
1252 } catch (RemoteException e) {
1253 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1254 }
1255 }
1256
Svetoslav7ec28e82015-05-20 17:01:10 -07001257 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001258 if (DEBUG) {
1259 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1260 }
1261
1262 // Resolve the userId on whose behalf the call is made.
1263 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1264
Christopher Tateb218e762017-04-05 16:34:07 -07001265 // The relevant "calling package" userId will be the owning userId for some
1266 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1267 // up front who the effective "new SSAID" user ID for that settings name will be.
1268 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1269 Settings.Secure.ANDROID_ID);
1270 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1271
Svetoslav7ec28e82015-05-20 17:01:10 -07001272 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001273 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001274
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001276
Svetoslav7ec28e82015-05-20 17:01:10 -07001277 String[] normalizedProjection = normalizeProjection(projection);
1278 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001279
Svetoslav7ec28e82015-05-20 17:01:10 -07001280 for (int i = 0; i < nameCount; i++) {
1281 String name = names.get(i);
1282 // Determine the owning user as some profile settings are cloned from the parent.
1283 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1284 name);
Svetoslav683914b2015-01-15 14:22:26 -08001285
Alex Klyubin1991f572017-03-03 14:08:36 -08001286 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1287 // This caller is not permitted to access this setting. Pretend the setting
1288 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001289 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001290 }
Svetoslav683914b2015-01-15 14:22:26 -08001291
Mark Rathjen7599f132017-01-23 14:15:54 -08001292 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001293 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1294 final Setting setting;
1295 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001296 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001297 } else {
1298 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1299 name);
1300 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001301 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001302 }
1303
Svetoslav7ec28e82015-05-20 17:01:10 -07001304 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001305 }
Svetoslav683914b2015-01-15 14:22:26 -08001306 }
1307
Svetoslav7ec28e82015-05-20 17:01:10 -07001308 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001309 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1310 }
1311
1312 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001313 if (DEBUG) {
1314 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1315 }
1316
1317 // Resolve the userId on whose behalf the call is made.
1318 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1319
Chad Brubakera6830e72017-04-28 17:34:36 -07001320 // Ensure the caller can access the setting.
1321 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1322
Svetoslav683914b2015-01-15 14:22:26 -08001323 // Determine the owning user as some profile settings are cloned from the parent.
1324 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1325
Alex Klyubin1991f572017-03-03 14:08:36 -08001326 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1327 // This caller is not permitted to access this setting. Pretend the setting doesn't
1328 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001329 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1330 owningUserId);
1331 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001332 }
1333
Christopher Tateb218e762017-04-05 16:34:07 -07001334 // As of Android O, the SSAID is read from an app-specific entry in table
1335 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1336 if (isNewSsaidSetting(name)) {
1337 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1338 synchronized (mLock) {
1339 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001340 }
Christopher Tateb218e762017-04-05 16:34:07 -07001341 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001342 if (enableOverride) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001343 if (Secure.LOCATION_MODE.equals(name)) {
1344 final Setting overridden = getLocationModeSetting(owningUserId);
Makoto Onuki0000d322017-11-28 16:31:47 -08001345 if (overridden != null) {
1346 return overridden;
1347 }
1348 }
1349 }
Mark Rathjend891f012017-01-19 04:10:37 +00001350
Christopher Tateb218e762017-04-05 16:34:07 -07001351 // Not the SSAID; do a straight lookup
1352 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001353 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001354 owningUserId, name);
1355 }
Svetoslav683914b2015-01-15 14:22:26 -08001356 }
1357
Mark Rathjend891f012017-01-19 04:10:37 +00001358 private boolean isNewSsaidSetting(String name) {
1359 return Settings.Secure.ANDROID_ID.equals(name)
1360 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1361 }
1362
Andreas Gampeb58893072018-09-05 16:52:31 -07001363 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001364 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001365 // Get uid of caller (key) used to store ssaid value
1366 String name = Integer.toString(
1367 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1368
1369 if (DEBUG) {
1370 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1371 }
1372
1373 // Retrieve the ssaid from the table if present.
1374 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1375 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001376 // If the app is an Instant App use its stored SSAID instead of our own.
1377 final String instantSsaid;
1378 final long token = Binder.clearCallingIdentity();
1379 try {
1380 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1381 owningUserId);
1382 } catch (RemoteException e) {
1383 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1384 return null;
1385 } finally {
1386 Binder.restoreCallingIdentity(token);
1387 }
Svet Ganov96c99462017-05-05 14:27:13 -07001388
1389 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1390 SETTINGS_TYPE_SSAID, owningUserId);
1391
Chad Brubaker0d277a72017-04-12 16:56:53 -07001392 if (instantSsaid != null) {
1393 // Use the stored value if it is still valid.
1394 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001395 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001396 }
1397 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001398 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1399 true, callingPkg.packageName);
1400 if (!success) {
1401 throw new IllegalStateException("Failed to update instant app android id");
1402 }
Svet Ganov96c99462017-05-05 14:27:13 -07001403 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1404 owningUserId, name);
1405 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001406 }
Mark Rathjend891f012017-01-19 04:10:37 +00001407
1408 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001409 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001410 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1411 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001412 }
1413
Svet Ganov96c99462017-05-05 14:27:13 -07001414 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1415 }
1416
1417 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1418 // SSAID settings are located in a dedicated table for internal bookkeeping
1419 // but for the world they reside in the secure table, so adjust the key here.
1420 // We have a special name when looking it up but want the world to see it as
1421 // "android_id".
1422 if (ssaidSetting != null) {
1423 return settingsState.new Setting(ssaidSetting) {
1424 @Override
1425 public int getKey() {
1426 final int userId = getUserIdFromKey(super.getKey());
1427 return makeKey(SETTINGS_TYPE_SECURE, userId);
1428 }
1429
1430 @Override
1431 public String getName() {
1432 return Settings.Secure.ANDROID_ID;
1433 }
1434 };
1435 }
1436 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001437 }
1438
Kweku Adams5e0052b2019-02-22 15:17:52 -08001439 private Setting getLocationModeSetting(int owningUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001440 synchronized (mLock) {
1441 final Setting setting = getGlobalSetting(
1442 Global.LOCATION_GLOBAL_KILL_SWITCH);
1443 if (!"1".equals(setting.getValue())) {
1444 return null;
1445 }
1446 // Global kill-switch is enabled. Return an empty value.
1447 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1448 SETTINGS_TYPE_SECURE, owningUserId);
1449 return settingsState.new Setting(
Kweku Adams5e0052b2019-02-22 15:17:52 -08001450 Secure.LOCATION_MODE,
Makoto Onuki0000d322017-11-28 16:31:47 -08001451 "", // value
1452 "", // tag
1453 "", // default value
1454 "", // package name
1455 false, // from system
1456 "0" // id
1457 ) {
1458 @Override
1459 public boolean update(String value, boolean setDefault, String packageName,
1460 String tag, boolean forceNonSystemPackage) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001461 Slog.wtf(LOG_TAG, "update shouldn't be called on this instance.");
Makoto Onuki0000d322017-11-28 16:31:47 -08001462 return false;
1463 }
1464 };
1465 }
1466 }
1467
Svetoslav Ganove080da92016-12-21 17:10:35 -08001468 private boolean insertSecureSetting(String name, String value, String tag,
1469 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001470 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001471 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001472 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1473 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001474 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001475 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1476 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001477 }
1478
Svet Ganov53a441c2016-04-19 19:38:00 -07001479 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001480 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001481 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1482 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001483 }
1484
Svetoslav Ganove080da92016-12-21 17:10:35 -08001485 return mutateSecureSetting(name, null, null, false, requestingUserId,
1486 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001487 }
1488
Svetoslav Ganove080da92016-12-21 17:10:35 -08001489 private boolean updateSecureSetting(String name, String value, String tag,
1490 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001491 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001492 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001493 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1494 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001495 }
1496
Svetoslav Ganove080da92016-12-21 17:10:35 -08001497 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1498 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001499 }
1500
Svetoslav Ganove080da92016-12-21 17:10:35 -08001501 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1502 if (DEBUG) {
1503 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1504 + mode + ", " + tag + ")");
1505 }
1506
1507 mutateSecureSetting(null, null, tag, false, requestingUserId,
1508 MUTATION_OPERATION_RESET, false, mode);
1509 }
1510
1511 private boolean mutateSecureSetting(String name, String value, String tag,
1512 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1513 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001514 // Make sure the caller can change the settings.
1515 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1516
Svetoslav683914b2015-01-15 14:22:26 -08001517 // Resolve the userId on whose behalf the call is made.
1518 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1519
Makoto Onuki28da2e32015-11-20 11:30:44 -08001520 // If this is a setting that is currently restricted for this user, do not allow
1521 // unrestricting changes.
Christopher Tate65fb2e42019-10-11 17:00:23 -07001522 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001523 return false;
1524 }
1525
1526 // Determine the owning user as some profile settings are cloned from the parent.
1527 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1528
1529 // Only the owning user can change the setting.
1530 if (owningUserId != callingUserId) {
1531 return false;
1532 }
1533
Svetoslav683914b2015-01-15 14:22:26 -08001534 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001535 synchronized (mLock) {
Soonil Nagarkar10b19602019-09-10 15:46:32 -07001536 // Special cases for location providers (sigh).
1537 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1538 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1539 forceNotify);
1540 }
1541
Svetoslav7ec28e82015-05-20 17:01:10 -07001542 switch (operation) {
1543 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001544 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001545 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001546 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001547 }
Svetoslav683914b2015-01-15 14:22:26 -08001548
Svetoslav7ec28e82015-05-20 17:01:10 -07001549 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001550 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001551 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001552 }
Svetoslav683914b2015-01-15 14:22:26 -08001553
Svetoslav7ec28e82015-05-20 17:01:10 -07001554 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001555 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001556 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001557 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001558 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001559
1560 case MUTATION_OPERATION_RESET: {
1561 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1562 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1563 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001564 }
1565 }
1566
1567 return false;
1568 }
1569
Svetoslav7ec28e82015-05-20 17:01:10 -07001570 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001571 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001572 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001573 }
1574
1575 // Resolve the userId on whose behalf the call is made.
1576 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1577
Svetoslav7ec28e82015-05-20 17:01:10 -07001578 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001579 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001580
Svetoslav7ec28e82015-05-20 17:01:10 -07001581 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001582
Svetoslav7ec28e82015-05-20 17:01:10 -07001583 String[] normalizedProjection = normalizeProjection(projection);
1584 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001585
Svetoslav7ec28e82015-05-20 17:01:10 -07001586 for (int i = 0; i < nameCount; i++) {
1587 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001588
Svetoslav7ec28e82015-05-20 17:01:10 -07001589 // Determine the owning user as some profile settings are cloned from the parent.
1590 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1591 name);
Svetoslav683914b2015-01-15 14:22:26 -08001592
Svetoslav7ec28e82015-05-20 17:01:10 -07001593 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001594 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001595 appendSettingToCursor(result, setting);
1596 }
1597
1598 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001599 }
Svetoslav683914b2015-01-15 14:22:26 -08001600 }
1601
Svetoslav7ec28e82015-05-20 17:01:10 -07001602 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001603 if (DEBUG) {
1604 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1605 }
1606
1607 // Resolve the userId on whose behalf the call is made.
1608 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1609
Chad Brubakera6830e72017-04-28 17:34:36 -07001610 // Ensure the caller can access the setting.
1611 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001612
Svetoslav683914b2015-01-15 14:22:26 -08001613 // Determine the owning user as some profile settings are cloned from the parent.
1614 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1615
1616 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001617 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001618 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001619 }
Svetoslav683914b2015-01-15 14:22:26 -08001620 }
1621
Svetoslav7ec28e82015-05-20 17:01:10 -07001622 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001623 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001624 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001625 + requestingUserId + ")");
1626 }
1627
Svetoslav7ec28e82015-05-20 17:01:10 -07001628 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001629 }
1630
Svetoslav7ec28e82015-05-20 17:01:10 -07001631 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001632 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001633 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001634 }
1635
Svetoslav7ec28e82015-05-20 17:01:10 -07001636 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001637 }
1638
Svetoslav7ec28e82015-05-20 17:01:10 -07001639 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001640 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001641 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001642 + requestingUserId + ")");
1643 }
1644
Svetoslav7ec28e82015-05-20 17:01:10 -07001645 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001646 }
1647
Svetoslav7ec28e82015-05-20 17:01:10 -07001648 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001649 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001650 if (!hasWriteSecureSettingsPermission()) {
1651 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1652 // operation is allowed for the calling package through appops.
1653 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1654 Binder.getCallingUid(), getCallingPackage(), true)) {
1655 return false;
1656 }
Svetoslav683914b2015-01-15 14:22:26 -08001657 }
1658
Svetoslav683914b2015-01-15 14:22:26 -08001659 // Resolve the userId on whose behalf the call is made.
1660 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1661
Christopher Tate65fb2e42019-10-11 17:00:23 -07001662 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
yuemingw1d13eae2018-01-30 17:27:54 +00001663 return false;
1664 }
1665
Svetoslavd8d25e02015-11-20 13:09:26 -08001666 // Enforce what the calling package can mutate the system settings.
1667 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1668
Svetoslav683914b2015-01-15 14:22:26 -08001669 // Determine the owning user as some profile settings are cloned from the parent.
1670 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1671
1672 // Only the owning user id can change the setting.
1673 if (owningUserId != callingUserId) {
1674 return false;
1675 }
1676
Jeff Sharkey413573a2016-02-22 17:52:45 -07001677 // Invalidate any relevant cache files
1678 String cacheName = null;
1679 if (Settings.System.RINGTONE.equals(name)) {
1680 cacheName = Settings.System.RINGTONE_CACHE;
1681 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1682 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1683 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1684 cacheName = Settings.System.ALARM_ALERT_CACHE;
1685 }
1686 if (cacheName != null) {
1687 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001688 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001689 cacheFile.delete();
1690 }
1691
Svetoslav683914b2015-01-15 14:22:26 -08001692 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001693 synchronized (mLock) {
1694 switch (operation) {
1695 case MUTATION_OPERATION_INSERT: {
1696 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001697 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001698 owningUserId, name, value, null, false, getCallingPackage(),
1699 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001700 }
1701
1702 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001703 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001704 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001705 }
1706
1707 case MUTATION_OPERATION_UPDATE: {
1708 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001709 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001710 owningUserId, name, value, null, false, getCallingPackage(),
1711 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001712 }
Svetoslav683914b2015-01-15 14:22:26 -08001713 }
1714
Svetoslav7ec28e82015-05-20 17:01:10 -07001715 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001716 }
Svetoslav683914b2015-01-15 14:22:26 -08001717 }
1718
Billy Lau6ad2d662015-07-18 00:26:58 +01001719 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001720 // Write secure settings is a more protected permission. If caller has it we are good.
1721 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1722 == PackageManager.PERMISSION_GRANTED) {
1723 return true;
1724 }
1725
Svetoslavf41334b2015-06-23 12:06:03 -07001726 return false;
1727 }
1728
Svetoslav683914b2015-01-15 14:22:26 -08001729 private void validateSystemSettingValue(String name, String value) {
Al Sutton91f89d02019-08-16 12:56:57 +01001730 Validator validator = SystemSettingsValidators.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001731 if (validator != null && !validator.validate(value)) {
1732 throw new IllegalArgumentException("Invalid value: " + value
1733 + " for setting: " + name);
1734 }
1735 }
1736
Alex Klyubin1991f572017-03-03 14:08:36 -08001737 /**
1738 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1739 */
1740 private boolean isSecureSettingAccessible(String name, int callingUserId,
1741 int owningUserId) {
1742 // Special case for location (sigh).
1743 // This check is not inside the name-based checks below because this method performs checks
1744 // only if the calling user ID is not the same as the owning user ID.
1745 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1746 return false;
1747 }
1748
1749 switch (name) {
1750 case "bluetooth_address":
1751 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1752 // address in this secure setting. Secure settings can normally be read by any app,
1753 // which thus enables them to bypass the recently introduced restrictions on access
1754 // to device identifiers.
1755 // To mitigate this we make this setting available only to callers privileged to see
1756 // this device's MAC addresses, same as through public API
1757 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1758 return getContext().checkCallingOrSelfPermission(
1759 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1760 default:
1761 return true;
1762 }
1763 }
1764
Svetoslav683914b2015-01-15 14:22:26 -08001765 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1766 int owningUserId) {
1767 // Optimization - location providers are restricted only for managed profiles.
1768 if (callingUserId == owningUserId) {
1769 return false;
1770 }
1771 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1772 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1773 new UserHandle(callingUserId))) {
1774 return true;
1775 }
1776 return false;
1777 }
1778
Svetoslav683914b2015-01-15 14:22:26 -08001779 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1780 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1781 }
1782
1783 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001784 final int parentId;
1785 // Resolves dependency if setting has a dependency and the calling user has a parent
1786 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1787 && (parentId = getGroupParentLocked(userId)) != userId) {
1788 // The setting has a dependency and the profile has a parent
1789 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001790 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1791 final long token = Binder.clearCallingIdentity();
1792 try {
1793 Setting settingObj = getSecureSetting(dependency, userId);
1794 if (settingObj != null && settingObj.getValue().equals("1")) {
1795 return parentId;
1796 }
1797 } finally {
1798 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001799 }
1800 }
Svetoslav683914b2015-01-15 14:22:26 -08001801 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1802 }
1803
1804 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1805 final int parentId = getGroupParentLocked(userId);
1806 if (parentId != userId && keys.contains(name)) {
1807 return parentId;
1808 }
1809 return userId;
1810 }
1811
Svetoslavf41334b2015-06-23 12:06:03 -07001812 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001813 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001814 // System/root/shell can mutate whatever secure settings they want.
1815 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001816 final int appId = UserHandle.getAppId(callingUid);
1817 if (appId == android.os.Process.SYSTEM_UID
1818 || appId == Process.SHELL_UID
1819 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001820 return;
1821 }
1822
1823 switch (operation) {
1824 case MUTATION_OPERATION_INSERT:
1825 // Insert updates.
1826 case MUTATION_OPERATION_UPDATE: {
1827 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1828 return;
1829 }
1830
1831 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001832 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001833
1834 // Privileged apps can do whatever they want.
1835 if ((packageInfo.applicationInfo.privateFlags
1836 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1837 return;
1838 }
1839
1840 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1841 packageInfo.applicationInfo.targetSdkVersion, name);
1842 } break;
1843
1844 case MUTATION_OPERATION_DELETE: {
1845 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1846 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1847 throw new IllegalArgumentException("You cannot delete system defined"
1848 + " secure settings.");
1849 }
1850
1851 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001852 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001853
1854 // Privileged apps can do whatever they want.
1855 if ((packageInfo.applicationInfo.privateFlags &
1856 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1857 return;
1858 }
1859
1860 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1861 packageInfo.applicationInfo.targetSdkVersion, name);
1862 } break;
1863 }
1864 }
1865
Todd Kennedybe0b8892017-02-15 14:13:52 -08001866 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001867 switch (settingsType) {
1868 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001869 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001870 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001871 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001872 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001873 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001874 default:
1875 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1876 }
1877 }
1878
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001879 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1880 switch (settingsType) {
1881 case SETTINGS_TYPE_GLOBAL:
1882 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1883 case SETTINGS_TYPE_SYSTEM:
1884 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1885 case SETTINGS_TYPE_SECURE:
1886 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1887 default:
1888 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1889 }
1890 }
1891
Andreas Gampeb58893072018-09-05 16:52:31 -07001892 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001893 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001894 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1895 // in the current form.
1896 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001897 }
1898
Chad Brubakera6830e72017-04-28 17:34:36 -07001899 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001900 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1901 return;
1902 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001903 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001904 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001905 return;
1906 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001907 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1908 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001909 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1910 // breakage in the current form.
1911 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1912 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001913 }
1914 }
1915
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001916 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1917 // We always use the callingUid for this lookup. This means that if hypothetically an
1918 // app was installed in user A with cross user and in user B as an Instant App
1919 // the app in A would be able to see all the settings in user B. However since cross
1920 // user is a system permission and the app must be uninstalled in B and then installed as
1921 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001922 ApplicationInfo ai = null;
1923 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001924 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1925 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001926 } catch (RemoteException ignored) {
1927 }
1928 if (ai == null) {
1929 throw new IllegalStateException("Failed to lookup info for package "
1930 + getCallingPackage());
1931 }
1932 return ai;
1933 }
1934
Xiaohui Chen43765b72015-08-31 10:57:33 -07001935 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001936 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001937 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1938 getCallingPackage(), 0, userId);
1939 if (packageInfo != null) {
1940 return packageInfo;
1941 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001942 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001943 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001944 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001945 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001946 }
1947
1948 private int getGroupParentLocked(int userId) {
1949 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001950 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001951 return userId;
1952 }
1953 // We are in the same process with the user manager and the returned
1954 // user info is a cached instance, so just look up instead of cache.
1955 final long identity = Binder.clearCallingIdentity();
1956 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001957 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001958 UserInfo userInfo = mUserManager.getProfileParent(userId);
1959 return (userInfo != null) ? userInfo.id : userId;
1960 } finally {
1961 Binder.restoreCallingIdentity(identity);
1962 }
1963 }
1964
Svetoslav683914b2015-01-15 14:22:26 -08001965 private void enforceWritePermission(String permission) {
1966 if (getContext().checkCallingOrSelfPermission(permission)
1967 != PackageManager.PERMISSION_GRANTED) {
1968 throw new SecurityException("Permission denial: writing to settings requires:"
1969 + permission);
1970 }
1971 }
1972
1973 /*
1974 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1975 * This setting contains a list of the currently enabled location providers.
1976 * But helper functions in android.providers.Settings can enable or disable
1977 * a single provider by using a "+" or "-" prefix before the provider name.
1978 *
yuemingw1d13eae2018-01-30 17:27:54 +00001979 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1980 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1981 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001982 *
Svetoslav683914b2015-01-15 14:22:26 -08001983 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001984 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001985 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001986 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1987 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001988 if (TextUtils.isEmpty(value)) {
1989 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001990 }
Maggie83e03f52018-03-16 12:22:20 -07001991 Setting oldSetting = getSecureSetting(
1992 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1993 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001994 return false;
1995 }
Maggie83e03f52018-03-16 12:22:20 -07001996 String oldProviders = oldSetting.getValue();
1997 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1998 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1999 Set<String> newProvidersSet = new ArraySet<>();
2000 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002001
Maggie83e03f52018-03-16 12:22:20 -07002002 String[] providerUpdates = value.split(",");
2003 boolean inputError = false;
2004 for (String provider : providerUpdates) {
2005 // do not update location_providers_allowed when input is invalid
2006 if (TextUtils.isEmpty(provider)) {
2007 inputError = true;
2008 break;
Svetoslav683914b2015-01-15 14:22:26 -08002009 }
Maggie83e03f52018-03-16 12:22:20 -07002010 final char prefix = provider.charAt(0);
2011 // do not update location_providers_allowed when input is invalid
2012 if (prefix != '+' && prefix != '-') {
2013 inputError = true;
2014 break;
Svetoslav683914b2015-01-15 14:22:26 -08002015 }
Maggie83e03f52018-03-16 12:22:20 -07002016 // skip prefix
2017 provider = provider.substring(1);
2018 if (prefix == '+') {
2019 newProvidersSet.add(provider);
2020 } else if (prefix == '-') {
2021 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002022 }
Maggie83e03f52018-03-16 12:22:20 -07002023 }
2024 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2025 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002026 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002027 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002028 mSettingsRegistry.notifyForSettingsChange(
2029 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002030 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2031 }
Svetoslav683914b2015-01-15 14:22:26 -08002032 return false;
2033 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002034 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002035 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2036 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002037 }
2038
Svetoslav683914b2015-01-15 14:22:26 -08002039 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2040 int targetSdkVersion, String name) {
2041 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2042 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2043 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2044 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2045 + " This will soon become an error.");
2046 } else {
2047 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2048 + " This will soon become an error.");
2049 }
2050 } else {
2051 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2052 throw new IllegalArgumentException("You cannot change private secure settings.");
2053 } else {
2054 throw new IllegalArgumentException("You cannot keep your settings in"
2055 + " the secure settings.");
2056 }
2057 }
2058 }
2059
2060 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2061 if (requestingUserId == UserHandle.getCallingUserId()) {
2062 return requestingUserId;
2063 }
2064 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2065 Binder.getCallingUid(), requestingUserId, false, true,
2066 "get/set setting for user", null);
2067 }
2068
Matt Pape793b15c2019-10-07 13:17:20 -07002069 private Bundle packageValueForCallResult(Setting setting, boolean trackingGeneration) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002070 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002071 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002072 return NULL_SETTING_BUNDLE;
2073 }
2074 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002075 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002076 Bundle result = new Bundle();
2077 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002078 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002079
Svetoslav Ganove080da92016-12-21 17:10:35 -08002080 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002081 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002082 }
2083
Matt Pape793b15c2019-10-07 13:17:20 -07002084 private Bundle packageValuesForCallResult(HashMap<String, String> keyValues,
2085 boolean trackingGeneration) {
2086 Bundle result = new Bundle();
2087 result.putSerializable(Settings.NameValueTable.VALUE, keyValues);
2088 if (trackingGeneration) {
2089 synchronized (mLock) {
2090 mSettingsRegistry.mGenerationRegistry.addGenerationData(result,
2091 mSettingsRegistry.getSettingsLocked(
2092 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM).mKey);
2093 }
2094 }
2095
2096 return result;
2097 }
2098
Svetoslav683914b2015-01-15 14:22:26 -08002099 private static int getRequestingUserId(Bundle args) {
2100 final int callingUserId = UserHandle.getCallingUserId();
2101 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2102 : callingUserId;
2103 }
2104
Svet Ganov53a441c2016-04-19 19:38:00 -07002105 private boolean isTrackingGeneration(Bundle args) {
2106 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2107 }
2108
Svetoslav683914b2015-01-15 14:22:26 -08002109 private static String getSettingValue(Bundle args) {
2110 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2111 }
2112
Svetoslav Ganove080da92016-12-21 17:10:35 -08002113 private static String getSettingTag(Bundle args) {
2114 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2115 }
2116
Matt Pape6bfc62e2018-11-28 13:16:03 -08002117 private static String getSettingPrefix(Bundle args) {
Matt Papec6001532019-10-24 15:50:32 -07002118 return (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002119 }
2120
Svetoslav Ganove080da92016-12-21 17:10:35 -08002121 private static boolean getSettingMakeDefault(Bundle args) {
2122 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2123 }
2124
2125 private static int getResetModeEnforcingPermission(Bundle args) {
2126 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2127 switch (mode) {
2128 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2129 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2130 throw new SecurityException("Only system, shell/root on a "
2131 + "debuggable build can reset to untrusted defaults");
2132 }
2133 return mode;
2134 }
2135 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2136 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2137 throw new SecurityException("Only system, shell/root on a "
2138 + "debuggable build can reset untrusted changes");
2139 }
2140 return mode;
2141 }
2142 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2143 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2144 throw new SecurityException("Only system, shell/root on a "
2145 + "debuggable build can reset to trusted defaults");
2146 }
2147 return mode;
2148 }
2149 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2150 return mode;
2151 }
2152 }
2153 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2154 }
2155
2156 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2157 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2158 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2159 && (appId == SHELL_UID || appId == ROOT_UID));
2160 }
2161
Svetoslav683914b2015-01-15 14:22:26 -08002162 private static String getValidTableOrThrow(Uri uri) {
2163 if (uri.getPathSegments().size() > 0) {
2164 String table = uri.getPathSegments().get(0);
2165 if (DatabaseHelper.isValidTable(table)) {
2166 return table;
2167 }
2168 throw new IllegalArgumentException("Bad root path: " + table);
2169 }
2170 throw new IllegalArgumentException("Invalid URI:" + uri);
2171 }
2172
2173 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002174 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002175 return new MatrixCursor(projection, 0);
2176 }
2177 MatrixCursor cursor = new MatrixCursor(projection, 1);
2178 appendSettingToCursor(cursor, setting);
2179 return cursor;
2180 }
2181
2182 private static String[] normalizeProjection(String[] projection) {
2183 if (projection == null) {
2184 return ALL_COLUMNS;
2185 }
2186
2187 final int columnCount = projection.length;
2188 for (int i = 0; i < columnCount; i++) {
2189 String column = projection[i];
2190 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2191 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002192 }
2193 }
2194
Svetoslav683914b2015-01-15 14:22:26 -08002195 return projection;
2196 }
2197
2198 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002199 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002200 return;
2201 }
Svetoslav683914b2015-01-15 14:22:26 -08002202 final int columnCount = cursor.getColumnCount();
2203
2204 String[] values = new String[columnCount];
2205
2206 for (int i = 0; i < columnCount; i++) {
2207 String column = cursor.getColumnName(i);
2208
2209 switch (column) {
2210 case Settings.NameValueTable._ID: {
2211 values[i] = setting.getId();
2212 } break;
2213
2214 case Settings.NameValueTable.NAME: {
2215 values[i] = setting.getName();
2216 } break;
2217
2218 case Settings.NameValueTable.VALUE: {
2219 values[i] = setting.getValue();
2220 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002221 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002222 }
2223
Svetoslav683914b2015-01-15 14:22:26 -08002224 cursor.addRow(values);
2225 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002226
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002227 private static boolean isKeyValid(String key) {
2228 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2229 }
2230
Matt Pape7b1c6cd2019-01-04 08:10:41 -08002231 private String resolveCallingPackage() {
2232 switch (Binder.getCallingUid()) {
2233 case Process.ROOT_UID: {
2234 return "root";
2235 }
2236
2237 case Process.SHELL_UID: {
2238 return "com.android.shell";
2239 }
2240
2241 default: {
2242 return getCallingPackage();
2243 }
2244 }
2245 }
2246
Svetoslav683914b2015-01-15 14:22:26 -08002247 private static final class Arguments {
2248 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2249 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2250
2251 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2252 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2253
2254 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2255 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2256
2257 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2258 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2259
2260 public final String table;
2261 public final String name;
2262
2263 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2264 final int segmentSize = uri.getPathSegments().size();
2265 switch (segmentSize) {
2266 case 1: {
2267 if (where != null
2268 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2269 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2270 && whereArgs.length == 1) {
2271 name = whereArgs[0];
2272 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002273 return;
Svetoslav683914b2015-01-15 14:22:26 -08002274 } else if (where != null
2275 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2276 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2277 final int startIndex = Math.max(where.indexOf("'"),
2278 where.indexOf("\"")) + 1;
2279 final int endIndex = Math.max(where.lastIndexOf("'"),
2280 where.lastIndexOf("\""));
2281 name = where.substring(startIndex, endIndex);
2282 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002283 return;
Svetoslav683914b2015-01-15 14:22:26 -08002284 } else if (supportAll && where == null && whereArgs == null) {
2285 name = null;
2286 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002287 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002288 }
Svetoslav683914b2015-01-15 14:22:26 -08002289 } break;
2290
Svetoslav28494652015-02-12 14:11:42 -08002291 case 2: {
2292 if (where == null && whereArgs == null) {
2293 name = uri.getPathSegments().get(1);
2294 table = computeTableForSetting(uri, name);
2295 return;
2296 }
2297 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002298 }
Svetoslav28494652015-02-12 14:11:42 -08002299
2300 EventLogTags.writeUnsupportedSettingsQuery(
2301 uri.toSafeString(), where, Arrays.toString(whereArgs));
2302 String message = String.format( "Supported SQL:\n"
2303 + " uri content://some_table/some_property with null where and where args\n"
2304 + " uri content://some_table with query name=? and single name as arg\n"
2305 + " uri content://some_table with query name=some_name and null args\n"
2306 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2307 Arrays.toString(whereArgs));
2308 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002309 }
2310
Svetoslav28494652015-02-12 14:11:42 -08002311 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002312 String table = getValidTableOrThrow(uri);
2313
2314 if (name != null) {
2315 if (sSystemMovedToSecureSettings.contains(name)) {
2316 table = TABLE_SECURE;
2317 }
2318
2319 if (sSystemMovedToGlobalSettings.contains(name)) {
2320 table = TABLE_GLOBAL;
2321 }
2322
2323 if (sSecureMovedToGlobalSettings.contains(name)) {
2324 table = TABLE_GLOBAL;
2325 }
2326
2327 if (sGlobalMovedToSecureSettings.contains(name)) {
2328 table = TABLE_SECURE;
2329 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002330 }
Svetoslav683914b2015-01-15 14:22:26 -08002331
2332 return table;
2333 }
2334 }
2335
2336 final class SettingsRegistry {
2337 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2338
Svetoslav683914b2015-01-15 14:22:26 -08002339 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2340 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2341 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002342 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002343 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002344
2345 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002346
2347 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2348
Svet Ganov53a441c2016-04-19 19:38:00 -07002349 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002350
Svetoslav7e0683b2015-08-03 16:02:52 -07002351 private final Handler mHandler;
2352
Svet Ganov53a441c2016-04-19 19:38:00 -07002353 private final BackupManager mBackupManager;
2354
Amith Yamasani39452022017-03-21 15:23:47 -07002355 private String mSettingsCreationBuildId;
2356
Svetoslav683914b2015-01-15 14:22:26 -08002357 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002358 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002359 mGenerationRegistry = new GenerationRegistry(mLock);
2360 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002361 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002362 syncSsaidTableOnStart();
2363 }
2364
2365 private void generateUserKeyLocked(int userId) {
2366 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002367 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002368 final SecureRandom rand = new SecureRandom();
2369 rand.nextBytes(keyBytes);
2370
2371 // Convert to string for storage in settings table.
Neil Fuller3447fb42019-04-08 22:03:14 +01002372 final String userKey = HexEncoding.encodeToString(keyBytes, true /* upperCase */);
Mark Rathjend891f012017-01-19 04:10:37 +00002373
2374 // Store the key in the ssaid table.
2375 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2376 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2377 true, SettingsState.SYSTEM_PACKAGE_NAME);
2378
2379 if (!success) {
2380 throw new IllegalStateException("Ssaid settings not accessible");
2381 }
2382 }
2383
Mark Rathjen7599f132017-01-23 14:15:54 -08002384 private byte[] getLengthPrefix(byte[] data) {
2385 return ByteBuffer.allocate(4).putInt(data.length).array();
2386 }
2387
Christopher Tateb218e762017-04-05 16:34:07 -07002388 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002389 // Read the user's key from the ssaid table.
2390 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002391 if (userKeySetting == null || userKeySetting.isNull()
2392 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002393 // Lazy initialize and store the user key.
2394 generateUserKeyLocked(userId);
2395 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002396 if (userKeySetting == null || userKeySetting.isNull()
2397 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002398 throw new IllegalStateException("User key not accessible");
2399 }
2400 }
2401 final String userKey = userKeySetting.getValue();
Neil Fuller3447fb42019-04-08 22:03:14 +01002402 if (userKey == null || userKey.length() % 2 != 0) {
2403 throw new IllegalStateException("User key invalid");
2404 }
Mark Rathjend891f012017-01-19 04:10:37 +00002405
2406 // Convert the user's key back to a byte array.
Neil Fuller3447fb42019-04-08 22:03:14 +01002407 final byte[] keyBytes = HexEncoding.decode(userKey);
Mark Rathjen7599f132017-01-23 14:15:54 -08002408
2409 // Validate that the key is of expected length.
2410 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
Neil Fuller3447fb42019-04-08 22:03:14 +01002411 if (keyBytes.length != 16 && keyBytes.length != 32) {
Mark Rathjend891f012017-01-19 04:10:37 +00002412 throw new IllegalStateException("User key invalid");
2413 }
2414
Mark Rathjen7599f132017-01-23 14:15:54 -08002415 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002416 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002417 m = Mac.getInstance("HmacSHA256");
2418 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002419 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002420 throw new IllegalStateException("HmacSHA256 is not available", e);
2421 } catch (InvalidKeyException e) {
2422 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002423 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002424
Mark Rathjenf42dd912017-06-05 19:04:34 -07002425 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002426 for (int i = 0; i < callingPkg.signatures.length; i++) {
2427 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002428 m.update(getLengthPrefix(sig), 0, 4);
2429 m.update(sig);
2430 }
Mark Rathjend891f012017-01-19 04:10:37 +00002431
2432 // Convert result to a string for storage in settings table. Only want first 64 bits.
Neil Fuller3447fb42019-04-08 22:03:14 +01002433 final String ssaid = HexEncoding.encodeToString(m.doFinal(), false /* upperCase */)
2434 .substring(0, 16);
Mark Rathjend891f012017-01-19 04:10:37 +00002435
2436 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002437 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002438 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2439 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002440 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002441
2442 if (!success) {
2443 throw new IllegalStateException("Ssaid settings not accessible");
2444 }
2445
2446 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2447 }
2448
2449 public void syncSsaidTableOnStart() {
2450 synchronized (mLock) {
2451 // Verify that each user's packages and ssaid's are in sync.
2452 for (UserInfo user : mUserManager.getUsers(true)) {
2453 // Get all uids for the user's packages.
2454 final List<PackageInfo> packages;
2455 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002456 packages = mPackageManager.getInstalledPackages(
2457 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2458 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002459 } catch (RemoteException e) {
2460 throw new IllegalStateException("Package manager not available");
2461 }
2462 final Set<String> appUids = new HashSet<>();
2463 for (PackageInfo info : packages) {
2464 appUids.add(Integer.toString(info.applicationInfo.uid));
2465 }
2466
2467 // Get all uids currently stored in the user's ssaid table.
2468 final Set<String> ssaidUids = new HashSet<>(
2469 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2470 ssaidUids.remove(SSAID_USER_KEY);
2471
2472 // Perform a set difference for the appUids and ssaidUids.
2473 ssaidUids.removeAll(appUids);
2474
2475 // If there are ssaidUids left over they need to be removed from the table.
2476 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2477 user.id);
2478 for (String uid : ssaidUids) {
2479 ssaidSettings.deleteSettingLocked(uid);
2480 }
2481 }
2482 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002483 }
2484
Svetoslav683914b2015-01-15 14:22:26 -08002485 public List<String> getSettingsNamesLocked(int type, int userId) {
2486 final int key = makeKey(type, userId);
2487 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002488 if (settingsState == null) {
2489 return new ArrayList<String>();
2490 }
Svetoslav683914b2015-01-15 14:22:26 -08002491 return settingsState.getSettingNamesLocked();
2492 }
2493
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002494 public SparseBooleanArray getKnownUsersLocked() {
2495 SparseBooleanArray users = new SparseBooleanArray();
2496 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2497 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2498 }
2499 return users;
2500 }
2501
Kweku Adamsb0886f32017-10-31 15:32:09 -07002502 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002503 public SettingsState getSettingsLocked(int type, int userId) {
2504 final int key = makeKey(type, userId);
2505 return peekSettingsStateLocked(key);
2506 }
2507
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002508 public boolean ensureSettingsForUserLocked(int userId) {
2509 // First make sure this user actually exists.
2510 if (mUserManager.getUserInfo(userId) == null) {
2511 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2512 return false;
2513 }
2514
Svetoslav683914b2015-01-15 14:22:26 -08002515 // Migrate the setting for this user if needed.
2516 migrateLegacySettingsForUserIfNeededLocked(userId);
2517
Matt Pape1b31a332018-10-17 09:58:28 -07002518 // Ensure config settings loaded if owner.
2519 if (userId == UserHandle.USER_SYSTEM) {
2520 final int configKey
2521 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2522 ensureSettingsStateLocked(configKey);
2523 }
2524
Svetoslav683914b2015-01-15 14:22:26 -08002525 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002526 if (userId == UserHandle.USER_SYSTEM) {
2527 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002528 ensureSettingsStateLocked(globalKey);
2529 }
2530
2531 // Ensure secure settings loaded.
2532 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2533 ensureSettingsStateLocked(secureKey);
2534
2535 // Make sure the secure settings have an Android id set.
2536 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2537 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2538
2539 // Ensure system settings loaded.
2540 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2541 ensureSettingsStateLocked(systemKey);
2542
Mark Rathjend891f012017-01-19 04:10:37 +00002543 // Ensure secure settings loaded.
2544 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2545 ensureSettingsStateLocked(ssaidKey);
2546
Svetoslav683914b2015-01-15 14:22:26 -08002547 // Upgrade the settings to the latest version.
2548 UpgradeController upgrader = new UpgradeController(userId);
2549 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002550 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002551 }
2552
2553 private void ensureSettingsStateLocked(int key) {
2554 if (mSettingsStates.get(key) == null) {
2555 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002556 SettingsState settingsState = new SettingsState(getContext(), mLock,
2557 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002558 mSettingsStates.put(key, settingsState);
2559 }
2560 }
2561
2562 public void removeUserStateLocked(int userId, boolean permanently) {
2563 // We always keep the global settings in memory.
2564
2565 // Nuke system settings.
2566 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2567 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2568 if (systemSettingsState != null) {
2569 if (permanently) {
2570 mSettingsStates.remove(systemKey);
2571 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002572 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002573 systemSettingsState.destroyLocked(new Runnable() {
2574 @Override
2575 public void run() {
2576 mSettingsStates.remove(systemKey);
2577 }
2578 });
2579 }
2580 }
2581
2582 // Nuke secure settings.
2583 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2584 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2585 if (secureSettingsState != null) {
2586 if (permanently) {
2587 mSettingsStates.remove(secureKey);
2588 secureSettingsState.destroyLocked(null);
2589 } else {
2590 secureSettingsState.destroyLocked(new Runnable() {
2591 @Override
2592 public void run() {
2593 mSettingsStates.remove(secureKey);
2594 }
2595 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002596 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002597 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002598
Mark Rathjend891f012017-01-19 04:10:37 +00002599 // Nuke ssaid settings.
2600 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2601 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2602 if (ssaidSettingsState != null) {
2603 if (permanently) {
2604 mSettingsStates.remove(ssaidKey);
2605 ssaidSettingsState.destroyLocked(null);
2606 } else {
2607 ssaidSettingsState.destroyLocked(new Runnable() {
2608 @Override
2609 public void run() {
2610 mSettingsStates.remove(ssaidKey);
2611 }
2612 });
2613 }
2614 }
2615
Svet Ganov53a441c2016-04-19 19:38:00 -07002616 // Nuke generation tracking data
2617 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002618 }
2619
Svetoslav683914b2015-01-15 14:22:26 -08002620 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002621 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2622 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002623 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2624 packageName, forceNotify, criticalSettings);
2625 }
2626
2627 public boolean insertSettingLocked(int type, int userId, String name, String value,
2628 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2629 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002630 final int key = makeKey(type, userId);
2631
Svetoslav Ganove080da92016-12-21 17:10:35 -08002632 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002633 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002634 if (settingsState != null) {
2635 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002636 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002637 }
Svetoslav683914b2015-01-15 14:22:26 -08002638
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002639 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2640 settingsState.persistSyncLocked();
2641 }
2642
Svet Ganov53a441c2016-04-19 19:38:00 -07002643 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002644 notifyForSettingsChange(key, name);
2645 }
2646 return success;
2647 }
2648
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002649 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2650 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002651 final int key = makeKey(type, userId);
2652
Svetoslav Ganove080da92016-12-21 17:10:35 -08002653 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002654 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002655 if (settingsState != null) {
2656 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002657 }
Svetoslav683914b2015-01-15 14:22:26 -08002658
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002659 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2660 settingsState.persistSyncLocked();
2661 }
2662
Svet Ganov53a441c2016-04-19 19:38:00 -07002663 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002664 notifyForSettingsChange(key, name);
2665 }
2666 return success;
2667 }
2668
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002669 public boolean updateSettingLocked(int type, int userId, String name, String value,
2670 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2671 Set<String> criticalSettings) {
2672 final int key = makeKey(type, userId);
2673
2674 boolean success = false;
2675 SettingsState settingsState = peekSettingsStateLocked(key);
2676 if (settingsState != null) {
2677 success = settingsState.updateSettingLocked(name, value, tag,
2678 makeDefault, packageName);
2679 }
2680
2681 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2682 settingsState.persistSyncLocked();
2683 }
2684
2685 if (forceNotify || success) {
2686 notifyForSettingsChange(key, name);
2687 }
2688
2689 return success;
2690 }
2691
Svetoslav683914b2015-01-15 14:22:26 -08002692 public Setting getSettingLocked(int type, int userId, String name) {
2693 final int key = makeKey(type, userId);
2694
2695 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002696 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002697 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002698 }
Mark Rathjend891f012017-01-19 04:10:37 +00002699
2700 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002701 return settingsState.getSettingLocked(name);
2702 }
2703
Svetoslav Ganove080da92016-12-21 17:10:35 -08002704 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2705 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002706 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2707 }
2708
2709 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2710 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002711 final int key = makeKey(type, userId);
2712 SettingsState settingsState = peekSettingsStateLocked(key);
2713 if (settingsState == null) {
2714 return;
2715 }
2716
2717 switch (mode) {
2718 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2719 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002720 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002721 Setting setting = settingsState.getSettingLocked(name);
2722 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002723 if ((tag != null && !tag.equals(setting.getTag()))
2724 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002725 continue;
2726 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002727 if (settingsState.resetSettingLocked(name)) {
2728 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002729 notifyForSettingsChange(key, name);
2730 }
2731 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002732 if (someSettingChanged) {
2733 settingsState.persistSyncLocked();
2734 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002735 }
2736 } break;
2737
2738 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2739 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002740 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002741 Setting setting = settingsState.getSettingLocked(name);
2742 if (!SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07002743 setting.getPackageName(), INVALID_UID, userId)) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002744 if (prefix != null && !setting.getName().startsWith(prefix)) {
2745 continue;
2746 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002747 if (settingsState.resetSettingLocked(name)) {
2748 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002749 notifyForSettingsChange(key, name);
2750 }
2751 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002752 if (someSettingChanged) {
2753 settingsState.persistSyncLocked();
2754 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002755 }
2756 } break;
2757
2758 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2759 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002760 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002761 Setting setting = settingsState.getSettingLocked(name);
2762 if (!SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07002763 setting.getPackageName(), INVALID_UID, userId)) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002764 if (prefix != null && !setting.getName().startsWith(prefix)) {
2765 continue;
2766 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002767 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002768 if (settingsState.resetSettingLocked(name)) {
2769 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002770 notifyForSettingsChange(key, name);
2771 }
2772 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002773 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002774 notifyForSettingsChange(key, name);
2775 }
2776 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002777 if (someSettingChanged) {
2778 settingsState.persistSyncLocked();
2779 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002780 }
2781 } break;
2782
2783 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2784 for (String name : settingsState.getSettingNamesLocked()) {
2785 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002786 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002787 if (prefix != null && !setting.getName().startsWith(prefix)) {
2788 continue;
2789 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002790 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002791 if (settingsState.resetSettingLocked(name)) {
2792 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002793 notifyForSettingsChange(key, name);
2794 }
2795 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002796 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002797 notifyForSettingsChange(key, name);
2798 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002799 if (someSettingChanged) {
2800 settingsState.persistSyncLocked();
2801 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002802 }
2803 } break;
2804 }
2805 }
2806
Zimuzoc56192c2018-07-25 10:40:01 +01002807 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002808 // Global and secure settings are signature protected. Apps signed
2809 // by the platform certificate are generally not uninstalled and
2810 // the main exception is tests. We trust components signed
2811 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002812
2813 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2814 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002815 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002816 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002817 }
Svetoslav683914b2015-01-15 14:22:26 -08002818 }
2819
Mark Rathjend891f012017-01-19 04:10:37 +00002820 public void onUidRemovedLocked(int uid) {
2821 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2822 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002823 if (ssaidSettings != null) {
2824 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2825 }
Mark Rathjend891f012017-01-19 04:10:37 +00002826 }
2827
Kweku Adamsb0886f32017-10-31 15:32:09 -07002828 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002829 private SettingsState peekSettingsStateLocked(int key) {
2830 SettingsState settingsState = mSettingsStates.get(key);
2831 if (settingsState != null) {
2832 return settingsState;
2833 }
2834
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002835 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2836 return null;
2837 }
Svetoslav683914b2015-01-15 14:22:26 -08002838 return mSettingsStates.get(key);
2839 }
2840
2841 private void migrateAllLegacySettingsIfNeeded() {
2842 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002843 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002844 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002845 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002846 return;
2847 }
2848
Amith Yamasani39452022017-03-21 15:23:47 -07002849 mSettingsCreationBuildId = Build.ID;
2850
Svetoslav683914b2015-01-15 14:22:26 -08002851 final long identity = Binder.clearCallingIdentity();
2852 try {
2853 List<UserInfo> users = mUserManager.getUsers(true);
2854
2855 final int userCount = users.size();
2856 for (int i = 0; i < userCount; i++) {
2857 final int userId = users.get(i).id;
2858
2859 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2860 SQLiteDatabase database = dbHelper.getWritableDatabase();
2861 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2862
2863 // Upgrade to the latest version.
2864 UpgradeController upgrader = new UpgradeController(userId);
2865 upgrader.upgradeIfNeededLocked();
2866
2867 // Drop from memory if not a running user.
2868 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2869 removeUserStateLocked(userId, false);
2870 }
2871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(identity);
2874 }
2875 }
2876 }
2877
2878 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2879 // Every user has secure settings and if no file we need to migrate.
2880 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2881 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002882 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002883 return;
2884 }
2885
2886 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2887 SQLiteDatabase database = dbHelper.getWritableDatabase();
2888
2889 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2890 }
2891
2892 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2893 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002894 // Move over the system settings.
2895 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2896 ensureSettingsStateLocked(systemKey);
2897 SettingsState systemSettings = mSettingsStates.get(systemKey);
2898 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2899 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002900
2901 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002902 // Do this after System settings, since this is the first thing we check when deciding
2903 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002904 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2905 ensureSettingsStateLocked(secureKey);
2906 SettingsState secureSettings = mSettingsStates.get(secureKey);
2907 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2908 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2909 secureSettings.persistSyncLocked();
2910
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002911 // Move over the global settings if owner.
2912 // Do this last, since this is the first thing we check when deciding
2913 // to skip over migration from db to xml for owner user.
2914 if (userId == UserHandle.USER_SYSTEM) {
2915 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2916 ensureSettingsStateLocked(globalKey);
2917 SettingsState globalSettings = mSettingsStates.get(globalKey);
2918 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002919 // If this was just created
2920 if (mSettingsCreationBuildId != null) {
2921 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2922 mSettingsCreationBuildId, null, true,
2923 SettingsState.SYSTEM_PACKAGE_NAME);
2924 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002925 globalSettings.persistSyncLocked();
2926 }
Svetoslav683914b2015-01-15 14:22:26 -08002927
2928 // Drop the database as now all is moved and persisted.
2929 if (DROP_DATABASE_ON_MIGRATION) {
2930 dbHelper.dropDatabase();
2931 } else {
2932 dbHelper.backupDatabase();
2933 }
2934 }
2935
2936 private void migrateLegacySettingsLocked(SettingsState settingsState,
2937 SQLiteDatabase database, String table) {
2938 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2939 queryBuilder.setTables(table);
2940
2941 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2942 null, null, null, null, null);
2943
2944 if (cursor == null) {
2945 return;
2946 }
2947
2948 try {
2949 if (!cursor.moveToFirst()) {
2950 return;
2951 }
2952
2953 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2954 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2955
2956 settingsState.setVersionLocked(database.getVersion());
2957
2958 while (!cursor.isAfterLast()) {
2959 String name = cursor.getString(nameColumnIdx);
2960 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002961 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002962 SettingsState.SYSTEM_PACKAGE_NAME);
2963 cursor.moveToNext();
2964 }
2965 } finally {
2966 cursor.close();
2967 }
2968 }
2969
Andreas Gampeb58893072018-09-05 16:52:31 -07002970 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002971 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2972 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2973
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002974 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002975 return;
2976 }
2977
2978 final int userId = getUserIdFromKey(secureSettings.mKey);
2979
2980 final UserInfo user;
2981 final long identity = Binder.clearCallingIdentity();
2982 try {
2983 user = mUserManager.getUserInfo(userId);
2984 } finally {
2985 Binder.restoreCallingIdentity(identity);
2986 }
2987 if (user == null) {
2988 // Can happen due to races when deleting users - treat as benign.
2989 return;
2990 }
2991
2992 String androidId = Long.toHexString(new SecureRandom().nextLong());
2993 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002994 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002995
2996 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2997 + "] for user " + userId);
2998
2999 // Write a drop box entry if it's a restricted profile
3000 if (user.isRestricted()) {
3001 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3002 Context.DROPBOX_SERVICE);
3003 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3004 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3005 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3006 }
3007 }
3008 }
3009
3010 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003011 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003012 mGenerationRegistry.incrementGeneration(key);
3013
Linus Tufvesson93c38552019-05-30 12:47:39 +01003014 if (isGlobalSettingsKey(key) || isConfigSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003015 final long token = Binder.clearCallingIdentity();
3016 try {
Linus Tufvesson93c38552019-05-30 12:47:39 +01003017 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)
3018 && isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003019 // When the global kill switch is updated, send the
3020 // change notification for the location setting.
3021 notifyLocationChangeForRunningUsers();
3022 }
Linus Tufvesson93c38552019-05-30 12:47:39 +01003023 notifySettingChangeForRunningUsers(key, name);
Jeff Sharkey308093f2018-03-25 22:53:29 -06003024 } finally {
3025 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003026 }
Svet Ganov945864c2018-03-22 21:49:10 -07003027 } else {
3028 final int userId = getUserIdFromKey(key);
3029 final Uri uri = getNotificationUriFor(key, name);
3030 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3031 userId, 0, uri).sendToTarget();
3032 if (isSecureSettingsKey(key)) {
3033 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3034 sSecureCloneToManagedSettings);
3035 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3036 sSystemCloneFromParentOnDependency.values());
3037 } else if (isSystemSettingsKey(key)) {
3038 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3039 sSystemCloneToManagedSettings);
3040 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003041 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003042
Svet Ganov945864c2018-03-22 21:49:10 -07003043 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003044 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003045 }
3046
Svet Ganov53a441c2016-04-19 19:38:00 -07003047 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003048 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003049 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003050 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003051 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003052 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003053 final int key = makeKey(type, profileId);
3054 // Increment the generation first, so observers always see the new value
3055 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003056 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003057 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003058 }
3059 }
3060 }
Svetoslav683914b2015-01-15 14:22:26 -08003061 }
3062
Linus Tufvesson93c38552019-05-30 12:47:39 +01003063 private void notifySettingChangeForRunningUsers(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003064 // Important: No need to update generation for each user as there
3065 // is a singleton generation entry for the global settings which
3066 // is already incremented be the caller.
3067 final Uri uri = getNotificationUriFor(key, name);
3068 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3069 for (int i = 0; i < users.size(); i++) {
3070 final int userId = users.get(i).id;
3071 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3072 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3073 userId, 0, uri).sendToTarget();
3074 }
3075 }
3076 }
3077
Makoto Onuki0000d322017-11-28 16:31:47 -08003078 private void notifyLocationChangeForRunningUsers() {
3079 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3080
3081 for (int i = 0; i < users.size(); i++) {
3082 final int userId = users.get(i).id;
3083
3084 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3085 continue;
3086 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003087
Svet Ganov945864c2018-03-22 21:49:10 -07003088 // Increment the generation first, so observers always see the new value
3089 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3090 mGenerationRegistry.incrementGeneration(key);
3091
Kweku Adams5e0052b2019-02-22 15:17:52 -08003092 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_MODE);
Makoto Onuki0000d322017-11-28 16:31:47 -08003093 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3094 userId, 0, uri).sendToTarget();
3095 }
3096 }
3097
Matt Pape1b31a332018-10-17 09:58:28 -07003098 private boolean isConfigSettingsKey(int key) {
3099 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3100 }
3101
Svetoslav683914b2015-01-15 14:22:26 -08003102 private boolean isGlobalSettingsKey(int key) {
3103 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3104 }
3105
3106 private boolean isSystemSettingsKey(int key) {
3107 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3108 }
3109
3110 private boolean isSecureSettingsKey(int key) {
3111 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3112 }
3113
Mark Rathjend891f012017-01-19 04:10:37 +00003114 private boolean isSsaidSettingsKey(int key) {
3115 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3116 }
3117
Svetoslav683914b2015-01-15 14:22:26 -08003118 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003119 if (isConfigSettingsKey(key)) {
3120 final int userId = getUserIdFromKey(key);
3121 return new File(Environment.getUserSystemDirectory(userId),
3122 SETTINGS_FILE_CONFIG);
3123 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003124 final int userId = getUserIdFromKey(key);
3125 return new File(Environment.getUserSystemDirectory(userId),
3126 SETTINGS_FILE_GLOBAL);
3127 } else if (isSystemSettingsKey(key)) {
3128 final int userId = getUserIdFromKey(key);
3129 return new File(Environment.getUserSystemDirectory(userId),
3130 SETTINGS_FILE_SYSTEM);
3131 } else if (isSecureSettingsKey(key)) {
3132 final int userId = getUserIdFromKey(key);
3133 return new File(Environment.getUserSystemDirectory(userId),
3134 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003135 } else if (isSsaidSettingsKey(key)) {
3136 final int userId = getUserIdFromKey(key);
3137 return new File(Environment.getUserSystemDirectory(userId),
3138 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003139 } else {
3140 throw new IllegalArgumentException("Invalid settings key:" + key);
3141 }
3142 }
3143
3144 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003145 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003146 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3147 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003148 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003149 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3150 : Settings.Global.CONTENT_URI;
3151 } else if (isSecureSettingsKey(key)) {
3152 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3153 : Settings.Secure.CONTENT_URI;
3154 } else if (isSystemSettingsKey(key)) {
3155 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3156 : Settings.System.CONTENT_URI;
3157 } else {
3158 throw new IllegalArgumentException("Invalid settings key:" + key);
3159 }
3160 }
3161
3162 private int getMaxBytesPerPackageForType(int type) {
3163 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003164 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003165 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003166 case SETTINGS_TYPE_SECURE:
3167 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003168 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3169 }
3170
3171 default: {
3172 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3173 }
3174 }
3175 }
3176
Svetoslav7e0683b2015-08-03 16:02:52 -07003177 private final class MyHandler extends Handler {
3178 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3179 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3180
3181 public MyHandler(Looper looper) {
3182 super(looper);
3183 }
3184
3185 @Override
3186 public void handleMessage(Message msg) {
3187 switch (msg.what) {
3188 case MSG_NOTIFY_URI_CHANGED: {
3189 final int userId = msg.arg1;
3190 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003191 try {
3192 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3193 } catch (SecurityException e) {
3194 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3195 }
Varun Shah2ecf7ad2019-10-16 12:30:57 -07003196 if (DEBUG) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003197 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3198 }
3199 } break;
3200
3201 case MSG_NOTIFY_DATA_CHANGED: {
3202 mBackupManager.dataChanged();
3203 } break;
3204 }
3205 }
3206 }
3207
Svetoslav683914b2015-01-15 14:22:26 -08003208 private final class UpgradeController {
Beverlyf364d7c2019-10-10 16:44:43 -04003209 private static final int SETTINGS_VERSION = 184;
Svetoslav683914b2015-01-15 14:22:26 -08003210
3211 private final int mUserId;
3212
3213 public UpgradeController(int userId) {
3214 mUserId = userId;
3215 }
3216
3217 public void upgradeIfNeededLocked() {
3218 // The version of all settings for a user is the same (all users have secure).
3219 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003220 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003221
3222 // Try an update from the current state.
3223 final int oldVersion = secureSettings.getVersionLocked();
3224 final int newVersion = SETTINGS_VERSION;
3225
Svet Ganovc9755bc2015-03-28 13:21:22 -07003226 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003227 if (oldVersion == newVersion) {
3228 return;
3229 }
3230
3231 // Try to upgrade.
3232 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3233
3234 // If upgrade failed start from scratch and upgrade.
3235 if (curVersion != newVersion) {
3236 // Drop state we have for this user.
3237 removeUserStateLocked(mUserId, true);
3238
3239 // Recreate the database.
3240 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3241 SQLiteDatabase database = dbHelper.getWritableDatabase();
3242 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3243
3244 // Migrate the settings for this user.
3245 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3246
3247 // Now upgrade should work fine.
3248 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003249
3250 // Make a note what happened, so we don't wonder why data was lost
3251 String reason = "Settings rebuilt! Current version: "
3252 + curVersion + " while expected: " + newVersion;
3253 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003254 Settings.Global.DATABASE_DOWNGRADE_REASON,
3255 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003256 }
3257
3258 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003259 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003260 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003261 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003262 globalSettings.setVersionLocked(newVersion);
3263 }
3264
3265 // Set the secure settings version.
3266 secureSettings.setVersionLocked(newVersion);
3267
3268 // Set the system settings version.
3269 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003270 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003271 systemSettings.setVersionLocked(newVersion);
3272 }
3273
3274 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003275 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003276 }
3277
3278 private SettingsState getSecureSettingsLocked(int userId) {
3279 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3280 }
3281
Mark Rathjend891f012017-01-19 04:10:37 +00003282 private SettingsState getSsaidSettingsLocked(int userId) {
3283 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3284 }
3285
Svetoslav683914b2015-01-15 14:22:26 -08003286 private SettingsState getSystemSettingsLocked(int userId) {
3287 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3288 }
3289
Jeff Brown503cffc2015-03-26 18:08:51 -07003290 /**
3291 * You must perform all necessary mutations to bring the settings
3292 * for this user from the old to the new version. When you add a new
3293 * upgrade step you *must* update SETTINGS_VERSION.
3294 *
3295 * This is an example of moving a setting from secure to global.
3296 *
3297 * // v119: Example settings changes.
3298 * if (currentVersion == 118) {
3299 * if (userId == UserHandle.USER_OWNER) {
3300 * // Remove from the secure settings.
3301 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3302 * String name = "example_setting_to_move";
3303 * String value = secureSettings.getSetting(name);
3304 * secureSettings.deleteSetting(name);
3305 *
3306 * // Add to the global settings.
3307 * SettingsState globalSettings = getGlobalSettingsLocked();
3308 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3309 * }
3310 *
3311 * // Update the current version.
3312 * currentVersion = 119;
3313 * }
3314 */
Svetoslav683914b2015-01-15 14:22:26 -08003315 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3316 if (DEBUG) {
3317 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3318 + oldVersion + " to version: " + newVersion);
3319 }
3320
Jeff Brown503cffc2015-03-26 18:08:51 -07003321 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003322
John Spurlocke11ae112015-05-11 16:09:03 -04003323 // v119: Reset zen + ringer mode.
3324 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003325 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003326 final SettingsState globalSettings = getGlobalSettingsLocked();
3327 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003328 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3329 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003330 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003331 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3332 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003333 }
3334 currentVersion = 119;
3335 }
3336
Jason Monk27bbb2d2015-03-31 16:46:39 -04003337 // v120: Add double tap to wake setting.
3338 if (currentVersion == 119) {
3339 SettingsState secureSettings = getSecureSettingsLocked(userId);
3340 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3341 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003342 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003343 SettingsState.SYSTEM_PACKAGE_NAME);
3344
3345 currentVersion = 120;
3346 }
3347
Svetoslav7e0683b2015-08-03 16:02:52 -07003348 if (currentVersion == 120) {
3349 // Before 121, we used a different string encoding logic. We just bump the
3350 // version here; SettingsState knows how to handle pre-version 120 files.
3351 currentVersion = 121;
3352 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003353
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003354 if (currentVersion == 121) {
3355 // Version 122: allow OEMs to set a default payment component in resources.
3356 // Note that we only write the default if no default has been set;
3357 // if there is, we just leave the default at whatever it currently is.
3358 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3359 String defaultComponent = (getContext().getResources().getString(
3360 R.string.def_nfc_payment_component));
3361 Setting currentSetting = secureSettings.getSettingLocked(
3362 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3363 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003364 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003365 secureSettings.insertSettingLocked(
3366 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003367 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003368 }
3369 currentVersion = 122;
3370 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003371
3372 if (currentVersion == 122) {
3373 // Version 123: Adding a default value for the ability to add a user from
3374 // the lock screen.
3375 if (userId == UserHandle.USER_SYSTEM) {
3376 final SettingsState globalSettings = getGlobalSettingsLocked();
3377 Setting currentSetting = globalSettings.getSettingLocked(
3378 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003379 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003380 globalSettings.insertSettingLocked(
3381 Settings.Global.ADD_USERS_WHEN_LOCKED,
3382 getContext().getResources().getBoolean(
3383 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003384 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003385 }
3386 }
3387 currentVersion = 123;
3388 }
Bryce Leebd179282015-12-17 19:01:37 -08003389
3390 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003391 final SettingsState globalSettings = getGlobalSettingsLocked();
3392 String defaultDisabledProfiles = (getContext().getResources().getString(
3393 R.string.def_bluetooth_disabled_profiles));
3394 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003395 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003396 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003397 }
3398
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003399 if (currentVersion == 124) {
3400 // Version 124: allow OEMs to set a default value for whether IME should be
3401 // shown when a physical keyboard is connected.
3402 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3403 Setting currentSetting = secureSettings.getSettingLocked(
3404 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003405 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003406 secureSettings.insertSettingLocked(
3407 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3408 getContext().getResources().getBoolean(
3409 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003410 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003411 }
3412 currentVersion = 125;
3413 }
3414
Ruben Brunk98576cf2016-03-07 18:54:28 -08003415 if (currentVersion == 125) {
3416 // Version 125: Allow OEMs to set the default VR service.
3417 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3418
3419 Setting currentSetting = secureSettings.getSettingLocked(
3420 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003421 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003422 ArraySet<ComponentName> l =
3423 SystemConfig.getInstance().getDefaultVrComponents();
3424
3425 if (l != null && !l.isEmpty()) {
3426 StringBuilder b = new StringBuilder();
3427 boolean start = true;
3428 for (ComponentName c : l) {
3429 if (!start) {
3430 b.append(':');
3431 }
3432 b.append(c.flattenToString());
3433 start = false;
3434 }
3435 secureSettings.insertSettingLocked(
3436 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003437 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003438 }
3439
3440 }
3441 currentVersion = 126;
3442 }
3443
Daniel U02ba6122016-04-01 18:41:42 +01003444 if (currentVersion == 126) {
3445 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3446 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3447 if (mUserManager.isManagedProfile(userId)) {
3448 final SettingsState systemSecureSettings =
3449 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3450
3451 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3452 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003453 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003454 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3455 secureSettings.insertSettingLocked(
3456 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003457 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003458 SettingsState.SYSTEM_PACKAGE_NAME);
3459 }
3460
3461 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3462 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003463 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003464 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3465 secureSettings.insertSettingLocked(
3466 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003467 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003468 SettingsState.SYSTEM_PACKAGE_NAME);
3469 }
3470 }
3471 currentVersion = 127;
3472 }
3473
Steven Ngdc20ba62016-04-26 18:19:04 +01003474 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003475 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003476 currentVersion = 128;
3477 }
3478
Julia Reynolds1f721e12016-07-11 08:50:58 -04003479 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003480 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003481 currentVersion = 129;
3482 }
3483
Dan Sandler71f85e92016-07-20 13:46:05 -04003484 if (currentVersion == 129) {
3485 // default longpress timeout changed from 500 to 400. If unchanged from the old
3486 // default, update to the new default.
3487 final SettingsState systemSecureSettings =
3488 getSecureSettingsLocked(userId);
3489 final String oldValue = systemSecureSettings.getSettingLocked(
3490 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3491 if (TextUtils.equals("500", oldValue)) {
3492 systemSecureSettings.insertSettingLocked(
3493 Settings.Secure.LONG_PRESS_TIMEOUT,
3494 String.valueOf(getContext().getResources().getInteger(
3495 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003496 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003497 }
3498 currentVersion = 130;
3499 }
3500
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003501 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003502 // Split Ambient settings
3503 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3504 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3505 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3506
3507 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003508 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003509 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003510 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003511 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003512 }
3513 currentVersion = 131;
3514 }
3515
3516 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003517 // Initialize new multi-press timeout to default value
3518 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3519 final String oldValue = systemSecureSettings.getSettingLocked(
3520 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3521 if (TextUtils.equals(null, oldValue)) {
3522 systemSecureSettings.insertSettingLocked(
3523 Settings.Secure.MULTI_PRESS_TIMEOUT,
3524 String.valueOf(getContext().getResources().getInteger(
3525 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003526 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003527 }
3528
Adrian Roos69741a22016-10-21 14:49:17 -07003529 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003530 }
3531
Adrian Roos69741a22016-10-21 14:49:17 -07003532 if (currentVersion == 132) {
3533 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003534 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3535 String defaultSyncParentSounds = (getContext().getResources()
3536 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3537 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003538 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3539 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003540 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003541 }
3542
Adrian Roos69741a22016-10-21 14:49:17 -07003543 if (currentVersion == 133) {
3544 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003545 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003546 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3547 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003548 String defaultEndButtonBehavior = Integer.toString(getContext()
3549 .getResources().getInteger(R.integer.def_end_button_behavior));
3550 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003551 defaultEndButtonBehavior, null, true,
3552 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003553 }
Adrian Roos69741a22016-10-21 14:49:17 -07003554 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003555 }
3556
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003557 if (currentVersion == 134) {
3558 // Remove setting that specifies if magnification values should be preserved.
3559 // This setting defaulted to true and never has a UI.
3560 getSecureSettingsLocked(userId).deleteSettingLocked(
3561 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3562 currentVersion = 135;
3563 }
3564
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003565 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003566 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003567 currentVersion = 136;
3568 }
3569
Mark Rathjend891f012017-01-19 04:10:37 +00003570 if (currentVersion == 136) {
3571 // Version 136: Store legacy SSAID for all apps currently installed on the
3572 // device as first step in migrating SSAID to be unique per application.
3573
3574 final boolean isUpgrade;
3575 try {
Svet Ganovd8eb8b22019-04-05 18:52:08 -07003576 isUpgrade = mPackageManager.isDeviceUpgrading();
Mark Rathjend891f012017-01-19 04:10:37 +00003577 } catch (RemoteException e) {
3578 throw new IllegalStateException("Package manager not available");
3579 }
3580 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3581 // user data or first boot on a new device should use new ssaid generation.
3582 if (isUpgrade) {
3583 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003584 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3585 userId, Settings.Secure.ANDROID_ID);
3586 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3587 || legacySsaidSetting.getValue() == null) {
3588 throw new IllegalStateException("Legacy ssaid not accessible");
3589 }
3590 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003591
3592 // Fill each uid with the legacy ssaid to be backwards compatible.
3593 final List<PackageInfo> packages;
3594 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003595 packages = mPackageManager.getInstalledPackages(
3596 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3597 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003598 } catch (RemoteException e) {
3599 throw new IllegalStateException("Package manager not available");
3600 }
3601
3602 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3603 for (PackageInfo info : packages) {
3604 // Check if the UID already has an entry in the table.
3605 final String uid = Integer.toString(info.applicationInfo.uid);
3606 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3607
3608 if (ssaid.isNull() || ssaid.getValue() == null) {
3609 // Android Id doesn't exist for this package so create it.
3610 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3611 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003612 if (DEBUG) {
3613 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3614 }
Mark Rathjend891f012017-01-19 04:10:37 +00003615 }
3616 }
3617 }
3618
3619 currentVersion = 137;
3620 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003621 if (currentVersion == 137) {
3622 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3623 // default value set to 1. The user can no longer change the value of this
3624 // setting through the UI.
3625 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3626 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003627 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3628 && secureSetting.getSettingLocked(
3629 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3630
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003631 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3632 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003633 // For managed profiles with profile owners, DevicePolicyManagerService
3634 // may want to set the user restriction in this case
3635 secureSetting.insertSettingLocked(
3636 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3637 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003638 }
3639 currentVersion = 138;
3640 }
Mark Rathjend891f012017-01-19 04:10:37 +00003641
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003642 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003643 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003644 currentVersion = 139;
3645 }
3646
Phil Weaver385912e2017-02-10 10:06:56 -08003647 if (currentVersion == 139) {
3648 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3649 // the user can no longer change the value of this setting through the UI.
3650 // Force to true.
3651 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3652 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3653 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3654 currentVersion = 140;
3655 }
3656
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003657 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003658 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003659 currentVersion = 141;
3660 }
3661
Svet Ganov13701552017-02-23 12:45:17 -08003662 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003663 // This implementation was incorrectly setting the current value of
3664 // settings changed by non-system packages as the default which default
3665 // is set by the system. We add a new upgrade step at the end to properly
3666 // handle this case which would also fix incorrect changes made by the
3667 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003668 currentVersion = 142;
3669 }
3670
Stephen Chen5d0922f2017-03-27 10:28:04 -07003671 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003672 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003673 if (userId == UserHandle.USER_SYSTEM) {
3674 final SettingsState globalSettings = getGlobalSettingsLocked();
3675 Setting currentSetting = globalSettings.getSettingLocked(
3676 Settings.Global.WIFI_WAKEUP_ENABLED);
3677 if (currentSetting.isNull()) {
3678 globalSettings.insertSettingLocked(
3679 Settings.Global.WIFI_WAKEUP_ENABLED,
3680 getContext().getResources().getBoolean(
3681 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3682 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3683 }
3684 }
3685
3686 currentVersion = 143;
3687 }
3688
Felipe Lemeff355092017-04-03 12:55:02 -07003689 if (currentVersion == 143) {
3690 // Version 144: Set a default value for Autofill service.
3691 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3692 final Setting currentSetting = secureSettings
3693 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3694 if (currentSetting.isNull()) {
3695 final String defaultValue = getContext().getResources().getString(
3696 com.android.internal.R.string.config_defaultAutofillService);
3697 if (defaultValue != null) {
3698 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3699 + "for user " + userId);
3700 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3701 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3702 }
3703 }
3704
3705 currentVersion = 144;
3706 }
3707
Jeremy Joslin45caa252017-05-04 11:22:46 -07003708 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003709 // Version 145: Removed
3710 currentVersion = 145;
3711 }
3712
3713 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003714 // Version 146: In step 142 we had a bug where incorrectly
3715 // some settings were considered system set and as a result
3716 // made the default and marked as the default being set by
3717 // the system. Here reevaluate the default and default system
3718 // set flags. This would both fix corruption by the old impl
3719 // of step 142 and also properly handle devices which never
3720 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003721 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003722 SettingsState globalSettings = getGlobalSettingsLocked();
3723 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3724 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003725 }
3726
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003727 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3728 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3729 secureSettings.persistSyncLocked();
3730
3731 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3732 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3733 systemSettings.persistSyncLocked();
3734
Amin Shaikh86367962017-06-07 08:58:22 -07003735 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003736 }
3737
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003738 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003739 // Version 147: Removed. (This version previously allowed showing the
3740 // "wifi_wakeup_available" setting).
3741 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003742 currentVersion = 147;
3743 }
3744
3745 if (currentVersion == 147) {
3746 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003747 if (userId == UserHandle.USER_SYSTEM) {
3748 final SettingsState globalSettings = getGlobalSettingsLocked();
3749 final Setting currentSetting = globalSettings.getSettingLocked(
3750 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3751 if (currentSetting.isNull()) {
3752 globalSettings.insertSettingLocked(
3753 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3754 getContext().getResources().getBoolean(
3755 R.bool.def_restrict_background_data) ? "1" : "0",
3756 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3757 }
3758 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003759 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003760 }
3761
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003762 if (currentVersion == 148) {
3763 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3764 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3765 final String oldValue = systemSecureSettings.getSettingLocked(
3766 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3767 if (TextUtils.equals(null, oldValue)) {
3768 final String defaultValue = getContext().getResources().getString(
3769 R.string.def_backup_manager_constants);
3770 if (!TextUtils.isEmpty(defaultValue)) {
3771 systemSecureSettings.insertSettingLocked(
3772 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3773 true, SettingsState.SYSTEM_PACKAGE_NAME);
3774 }
3775 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003776 currentVersion = 149;
3777 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003778
3779 if (currentVersion == 149) {
3780 // Version 150: Set a default value for mobile data always on
3781 final SettingsState globalSettings = getGlobalSettingsLocked();
3782 final Setting currentSetting = globalSettings.getSettingLocked(
3783 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3784 if (currentSetting.isNull()) {
3785 globalSettings.insertSettingLocked(
3786 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3787 getContext().getResources().getBoolean(
3788 R.bool.def_mobile_data_always_on) ? "1" : "0",
3789 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3790 }
3791
3792 currentVersion = 150;
3793 }
3794
Mike Digman4af4a6f2018-01-16 14:49:38 -08003795 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003796 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003797 currentVersion = 151;
3798 }
3799
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003800 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003801 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3802 // by default but it is now no longer configurable).
3803 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003804 currentVersion = 152;
3805 }
3806
Joe LaPenna250d7842018-01-25 10:19:42 -08003807 if (currentVersion == 152) {
3808 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3809 currentVersion = 153;
3810 }
3811
Ben Linb4df8bc2018-01-29 11:48:20 -08003812 if (currentVersion == 153) {
3813 // Version 154: Read notification badge configuration from config.
3814 // If user has already set the value, don't do anything.
3815 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3816 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3817 Settings.Secure.NOTIFICATION_BADGING);
3818 if (showNotificationBadges.isNull()) {
3819 final boolean defaultValue = getContext().getResources().getBoolean(
3820 com.android.internal.R.bool.config_notificationBadging);
3821 systemSecureSettings.insertSettingLocked(
3822 Secure.NOTIFICATION_BADGING,
3823 defaultValue ? "1" : "0",
3824 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3825 }
3826 currentVersion = 154;
3827 }
3828
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003829 if (currentVersion == 154) {
3830 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3831 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3832 final String oldValue = systemSecureSettings.getSettingLocked(
3833 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3834 if (TextUtils.equals(null, oldValue)) {
3835 final String defaultValue = getContext().getResources().getString(
3836 R.string.def_backup_local_transport_parameters);
3837 if (!TextUtils.isEmpty(defaultValue)) {
3838 systemSecureSettings.insertSettingLocked(
3839 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3840 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3841 }
3842
3843 }
3844 currentVersion = 155;
3845 }
3846
Beverlyda904812018-03-02 09:55:30 -05003847 if (currentVersion == 155) {
Beverlyf364d7c2019-10-10 16:44:43 -04003848 // Version 156: migrated to version 184
Beverlyda904812018-03-02 09:55:30 -05003849 currentVersion = 156;
3850 }
3851
Beverly09da25f2018-02-26 09:17:07 -05003852 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003853 // Version 157: Set a default value for zen duration,
3854 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003855 final SettingsState globalSettings = getGlobalSettingsLocked();
3856 final Setting currentSetting = globalSettings.getSettingLocked(
3857 Global.ZEN_DURATION);
3858 if (currentSetting.isNull()) {
3859 String defaultZenDuration = Integer.toString(getContext()
3860 .getResources().getInteger(R.integer.def_zen_duration));
3861 globalSettings.insertSettingLocked(
3862 Global.ZEN_DURATION, defaultZenDuration,
3863 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3864 }
Beverly09da25f2018-02-26 09:17:07 -05003865 currentVersion = 157;
3866 }
Annie Mengd069a882018-03-13 15:31:40 +00003867
3868 if (currentVersion == 157) {
3869 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3870 final SettingsState globalSettings = getGlobalSettingsLocked();
3871 final String oldValue = globalSettings.getSettingLocked(
3872 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3873 if (TextUtils.equals(null, oldValue)) {
3874 final String defaultValue = getContext().getResources().getString(
3875 R.string.def_backup_agent_timeout_parameters);
3876 if (!TextUtils.isEmpty(defaultValue)) {
3877 globalSettings.insertSettingLocked(
3878 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3879 null, true,
3880 SettingsState.SYSTEM_PACKAGE_NAME);
3881 }
3882 }
3883 currentVersion = 158;
3884 }
Roshan Pius9c396672018-03-02 14:54:13 -08003885
3886 if (currentVersion == 158) {
3887 // Remove setting that specifies wifi bgscan throttling params
3888 getGlobalSettingsLocked().deleteSettingLocked(
3889 "wifi_scan_background_throttle_interval_ms");
3890 getGlobalSettingsLocked().deleteSettingLocked(
3891 "wifi_scan_background_throttle_package_whitelist");
3892 currentVersion = 159;
3893 }
3894
Pavel Grafovc5c97302018-03-19 13:37:15 +00003895 if (currentVersion == 159) {
3896 // Version 160: Hiding notifications from the lockscreen is only available as
3897 // primary user option, profiles can only make them redacted. If a profile was
3898 // configured to not show lockscreen notifications, ensure that at the very
3899 // least these will be come hidden.
3900 if (mUserManager.isManagedProfile(userId)) {
3901 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3902 Setting showNotifications = secureSettings.getSettingLocked(
3903 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3904 // The default value is "1", check if user has turned it off.
3905 if ("0".equals(showNotifications.getValue())) {
3906 secureSettings.insertSettingLocked(
3907 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3908 null /* tag */, false /* makeDefault */,
3909 SettingsState.SYSTEM_PACKAGE_NAME);
3910 }
3911 // The setting is no longer valid for managed profiles, it should be
3912 // treated as if it was set to "1".
3913 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3914 }
3915 currentVersion = 160;
3916 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003917
3918 if (currentVersion == 160) {
3919 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003920 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003921 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3922 final SettingsState globalSettings = getGlobalSettingsLocked();
3923
3924 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003925 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3926 if (TextUtils.equals(null, oldValue)) {
3927 globalSettings.insertSettingLocked(
3928 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3929 Integer.toString(getContext().getResources().getInteger(
3930 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3931 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3932 }
3933
3934 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003935 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3936 if (TextUtils.equals(null, oldValue)) {
3937 globalSettings.insertSettingLocked(
3938 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3939 Integer.toString(getContext().getResources().getInteger(
3940 R.integer.def_sound_trigger_detection_service_op_timeout)),
3941 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3942 }
3943 currentVersion = 161;
3944 }
3945
Mike Digman55272862018-02-20 14:35:17 -08003946 if (currentVersion == 161) {
3947 // Version 161: Add a gesture for silencing phones
3948 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3949 final Setting currentSetting = secureSettings.getSettingLocked(
3950 Secure.VOLUME_HUSH_GESTURE);
3951 if (currentSetting.isNull()) {
3952 secureSettings.insertSettingLocked(
3953 Secure.VOLUME_HUSH_GESTURE,
3954 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3955 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3956 }
3957
3958 currentVersion = 162;
3959 }
3960
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003961 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003962 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003963 currentVersion = 163;
3964 }
3965
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003966 if (currentVersion == 163) {
3967 // Version 163: Update default value of
3968 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3969 final SettingsState settings = getGlobalSettingsLocked();
3970 final Setting currentSetting = settings.getSettingLocked(
3971 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3972 if (currentSetting.isDefaultFromSystem()) {
3973 settings.insertSettingLocked(
3974 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3975 Integer.toString(getContext().getResources().getInteger(
3976 R.integer
3977 .def_max_sound_trigger_detection_service_ops_per_day)),
3978 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3979 }
3980
3981 currentVersion = 164;
3982 }
3983
Julia Reynolds76bfa602018-04-23 09:38:47 -04003984 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003985 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003986 currentVersion = 165;
3987 }
3988
Beverly301e92a2018-04-27 09:43:05 -04003989 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003990 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3991 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003992 currentVersion = 166;
3993 }
3994
Beverly38fcfd02018-05-18 17:33:40 -04003995 if (currentVersion == 166) {
3996 // Version 166: add default values for hush gesture used and manual ringer
3997 // toggle
3998 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3999 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4000 Secure.HUSH_GESTURE_USED);
4001 if (currentHushUsedSetting.isNull()) {
4002 secureSettings.insertSettingLocked(
4003 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4004 SettingsState.SYSTEM_PACKAGE_NAME);
4005 }
4006
4007 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4008 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4009 if (currentRingerToggleCountSetting.isNull()) {
4010 secureSettings.insertSettingLocked(
4011 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4012 SettingsState.SYSTEM_PACKAGE_NAME);
4013 }
4014 currentVersion = 167;
4015 }
4016
Beverly155c9d22018-05-23 18:03:23 -04004017 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004018 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4019 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004020 currentVersion = 168;
4021 }
4022
Michael Wright0e9eeee2018-05-26 00:31:20 +01004023 if (currentVersion == 168) {
4024 // Version 168: by default, vibrate for phone calls
4025 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4026 final Setting currentSetting = systemSettings.getSettingLocked(
4027 Settings.System.VIBRATE_WHEN_RINGING);
4028 if (currentSetting.isNull()) {
4029 systemSettings.insertSettingLocked(
4030 Settings.System.VIBRATE_WHEN_RINGING,
4031 getContext().getResources().getBoolean(
4032 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4033 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4034 }
4035 currentVersion = 169;
4036 }
4037
Nadav Barf9f115d2018-06-24 10:06:50 +03004038 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004039 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4040 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4041 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004042
Beverly91d0a632018-07-02 16:45:00 -04004043 final SettingsState globalSettings = getGlobalSettingsLocked();
4044 final Setting globalZenDuration = globalSettings.getSettingLocked(
4045 Global.ZEN_DURATION);
4046
4047 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4048 final Setting secureZenDuration = secureSettings.getSettingLocked(
4049 Secure.ZEN_DURATION);
4050
4051 // ZEN_DURATION
4052 if (!globalZenDuration.isNull()) {
4053 secureSettings.insertSettingLocked(
4054 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4055 SettingsState.SYSTEM_PACKAGE_NAME);
4056
4057 // set global zen duration setting to null since it's deprecated
4058 globalSettings.insertSettingLocked(
4059 Global.ZEN_DURATION, null, null, true,
4060 SettingsState.SYSTEM_PACKAGE_NAME);
4061 } else if (secureZenDuration.isNull()) {
4062 String defaultZenDuration = Integer.toString(getContext()
4063 .getResources().getInteger(R.integer.def_zen_duration));
4064 secureSettings.insertSettingLocked(
4065 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4066 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004067 }
Beverly91d0a632018-07-02 16:45:00 -04004068
4069 // SHOW_ZEN_SETTINGS_SUGGESTION
4070 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4071 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4072 if (currentShowZenSettingSuggestion.isNull()) {
4073 secureSettings.insertSettingLocked(
4074 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4075 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4076 }
4077
4078 // ZEN_SETTINGS_UPDATED
4079 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4080 Secure.ZEN_SETTINGS_UPDATED);
4081 if (currentUpdatedSetting.isNull()) {
4082 secureSettings.insertSettingLocked(
4083 Secure.ZEN_SETTINGS_UPDATED, "0",
4084 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4085 }
4086
4087 // ZEN_SETTINGS_SUGGESTION_VIEWED
4088 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4089 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4090 if (currentSettingSuggestionViewed.isNull()) {
4091 secureSettings.insertSettingLocked(
4092 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4093 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4094 }
4095
Nadav Barf9f115d2018-06-24 10:06:50 +03004096 currentVersion = 170;
4097 }
4098
Beverly91d0a632018-07-02 16:45:00 -04004099 if (currentVersion == 170) {
4100 // Version 170: Set the default value for Secure Settings:
4101 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4102
4103 final SettingsState globalSettings = getGlobalSettingsLocked();
4104 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4105
4106 // CHARGING_SOUNDS_ENABLED
4107 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4108 Global.CHARGING_SOUNDS_ENABLED);
4109 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4110 Secure.CHARGING_SOUNDS_ENABLED);
4111
4112 if (!globalChargingSoundEnabled.isNull()) {
Beverlyff9c5872019-01-02 15:44:00 -05004113 if (secureChargingSoundsEnabled.isNull()) {
4114 secureSettings.insertSettingLocked(
4115 Secure.CHARGING_SOUNDS_ENABLED,
4116 globalChargingSoundEnabled.getValue(), null, false,
4117 SettingsState.SYSTEM_PACKAGE_NAME);
4118 }
Beverly91d0a632018-07-02 16:45:00 -04004119
4120 // set global charging_sounds_enabled setting to null since it's deprecated
4121 globalSettings.insertSettingLocked(
4122 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4123 SettingsState.SYSTEM_PACKAGE_NAME);
4124 } else if (secureChargingSoundsEnabled.isNull()) {
4125 String defChargingSoundsEnabled = getContext().getResources()
4126 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4127 secureSettings.insertSettingLocked(
4128 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4129 true, SettingsState.SYSTEM_PACKAGE_NAME);
4130 }
4131
4132 // CHARGING_VIBRATION_ENABLED
4133 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4134 Secure.CHARGING_VIBRATION_ENABLED);
4135
4136 if (secureChargingVibrationEnabled.isNull()) {
4137 String defChargingVibrationEnabled = getContext().getResources()
4138 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4139 secureSettings.insertSettingLocked(
4140 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4141 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4142 }
4143
4144 currentVersion = 171;
4145 }
4146
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004147 if (currentVersion == 171) {
4148 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4149 // be muted.
4150 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4151 final Setting currentSetting = systemSettings.getSettingLocked(
4152 Settings.System.MUTE_STREAMS_AFFECTED);
4153 if (!currentSetting.isNull()) {
4154 try {
4155 int currentSettingIntegerValue = Integer.parseInt(
4156 currentSetting.getValue());
4157 if ((currentSettingIntegerValue
4158 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4159 systemSettings.insertSettingLocked(
4160 Settings.System.MUTE_STREAMS_AFFECTED,
4161 Integer.toString(
4162 currentSettingIntegerValue
4163 | (1 << AudioManager.STREAM_VOICE_CALL)),
4164 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4165 }
4166 } catch (NumberFormatException e) {
4167 // remove the setting in case it is not a valid integer
4168 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4169 + "setting, removing setting", e);
4170 systemSettings.deleteSettingLocked(
4171 Settings.System.MUTE_STREAMS_AFFECTED);
4172 }
4173
4174 }
4175 currentVersion = 172;
4176 }
4177
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004178 if (currentVersion == 172) {
4179 // Version 172: Set the default value for Secure Settings: LOCATION_MODE
4180
4181 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4182
4183 final Setting locationMode = secureSettings.getSettingLocked(
4184 Secure.LOCATION_MODE);
4185
4186 if (locationMode.isNull()) {
4187 final Setting locationProvidersAllowed = secureSettings.getSettingLocked(
4188 Secure.LOCATION_PROVIDERS_ALLOWED);
4189
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004190 final int defLocationMode;
4191 if (locationProvidersAllowed.isNull()) {
4192 defLocationMode = getContext().getResources().getInteger(
4193 R.integer.def_location_mode);
4194 } else {
4195 defLocationMode =
4196 !TextUtils.isEmpty(locationProvidersAllowed.getValue())
4197 ? Secure.LOCATION_MODE_ON
4198 : Secure.LOCATION_MODE_OFF;
4199 }
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004200 secureSettings.insertSettingLocked(
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004201 Secure.LOCATION_MODE, Integer.toString(defLocationMode),
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004202 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4203 }
4204
4205 currentVersion = 173;
4206 }
4207
Beverly4179f992019-02-08 11:34:16 -05004208 if (currentVersion == 173) {
4209 // Version 173: Set the default value for Secure Settings: NOTIFICATION_BUBBLES
Lyn Hanb739fa62019-06-27 18:41:11 -07004210 // Removed. Moved NOTIFICATION_BUBBLES to Global Settings.
Beverly4179f992019-02-08 11:34:16 -05004211 currentVersion = 174;
4212 }
4213
Yiwen Chen0305b572019-03-05 11:26:59 -08004214 if (currentVersion == 174) {
4215 // Version 174: Set the default value for Global Settings: APPLY_RAMPING_RINGER
4216
4217 final SettingsState globalSettings = getGlobalSettingsLocked();
4218
4219 Setting currentRampingRingerSetting = globalSettings.getSettingLocked(
4220 Settings.Global.APPLY_RAMPING_RINGER);
4221 if (currentRampingRingerSetting.isNull()) {
4222 globalSettings.insertSettingLocked(
4223 Settings.Global.APPLY_RAMPING_RINGER,
4224 getContext().getResources().getBoolean(
4225 R.bool.def_apply_ramping_ringer) ? "1" : "0", null,
4226 true, SettingsState.SYSTEM_PACKAGE_NAME);
4227 }
4228
4229 currentVersion = 175;
4230 }
4231
wilsonshih5d999e22019-03-20 11:50:42 +08004232 if (currentVersion == 175) {
4233 // Version 175: Set the default value for System Settings:
4234 // RING_VIBRATION_INTENSITY. If the notification vibration intensity has been
4235 // set and ring vibration intensity hasn't, the ring vibration intensity should
4236 // followed notification vibration intensity.
4237
4238 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4239
4240 Setting notificationVibrationIntensity = systemSettings.getSettingLocked(
4241 Settings.System.NOTIFICATION_VIBRATION_INTENSITY);
4242
4243 Setting ringVibrationIntensity = systemSettings.getSettingLocked(
4244 Settings.System.RING_VIBRATION_INTENSITY);
4245
4246 if (!notificationVibrationIntensity.isNull()
4247 && ringVibrationIntensity.isNull()) {
4248 systemSettings.insertSettingLocked(
4249 Settings.System.RING_VIBRATION_INTENSITY,
4250 notificationVibrationIntensity.getValue(),
4251 null , true, SettingsState.SYSTEM_PACKAGE_NAME);
4252 }
4253
4254 currentVersion = 176;
4255 }
4256
Winson Chungd9f2fb32019-03-05 11:10:12 -08004257 if (currentVersion == 176) {
4258 // Version 176: Migrate the existing swipe up setting into the resource overlay
Winson Chung3d5d3b32019-04-24 16:52:47 -07004259 // for the navigation bar interaction mode. We do so only if the
4260 // setting is set.
Winson Chungd9f2fb32019-03-05 11:10:12 -08004261
Winson Chungd9f2fb32019-03-05 11:10:12 -08004262 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4263 final Setting swipeUpSetting = secureSettings.getSettingLocked(
Winson Chung85e74592019-03-06 11:49:22 -08004264 "swipe_up_to_switch_apps_enabled");
Winson Chung3d5d3b32019-04-24 16:52:47 -07004265 if (swipeUpSetting != null && !swipeUpSetting.isNull()
4266 && swipeUpSetting.getValue().equals("1")) {
4267 final IOverlayManager overlayManager = IOverlayManager.Stub.asInterface(
4268 ServiceManager.getService(Context.OVERLAY_SERVICE));
Winson Chungd9f2fb32019-03-05 11:10:12 -08004269 try {
Winson Chung3d5d3b32019-04-24 16:52:47 -07004270 overlayManager.setEnabledExclusiveInCategory(
4271 NAV_BAR_MODE_2BUTTON_OVERLAY, UserHandle.USER_CURRENT);
Winson Chungd9f2fb32019-03-05 11:10:12 -08004272 } catch (RemoteException e) {
4273 throw new IllegalStateException(
4274 "Failed to set nav bar interaction mode overlay");
4275 }
4276 }
4277
4278 currentVersion = 177;
4279 }
4280
Edgar Wangeb8bddb2019-04-19 17:29:49 +08004281 if (currentVersion == 177) {
4282 // Version 177: Set the default value for Secure Settings: AWARE_ENABLED
4283
4284 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4285
4286 final Setting awareEnabled = secureSettings.getSettingLocked(
4287 Secure.AWARE_ENABLED);
4288
4289 if (awareEnabled.isNull()) {
4290 final boolean defAwareEnabled = getContext().getResources().getBoolean(
4291 R.bool.def_aware_enabled);
4292 secureSettings.insertSettingLocked(
4293 Secure.AWARE_ENABLED, defAwareEnabled ? "1" : "0",
4294 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4295 }
4296
4297 currentVersion = 178;
4298 }
4299
Edgar Wangdabc41e2019-05-07 18:53:31 +08004300 if (currentVersion == 178) {
4301 // Version 178: Set the default value for Secure Settings:
4302 // SKIP_GESTURE & SILENCE_GESTURE
4303
4304 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4305
4306 final Setting skipGesture = secureSettings.getSettingLocked(
4307 Secure.SKIP_GESTURE);
4308
4309 if (skipGesture.isNull()) {
4310 final boolean defSkipGesture = getContext().getResources().getBoolean(
4311 R.bool.def_skip_gesture);
4312 secureSettings.insertSettingLocked(
4313 Secure.SKIP_GESTURE, defSkipGesture ? "1" : "0",
4314 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4315 }
4316
4317 final Setting silenceGesture = secureSettings.getSettingLocked(
4318 Secure.SILENCE_GESTURE);
4319
4320 if (silenceGesture.isNull()) {
4321 final boolean defSilenceGesture = getContext().getResources().getBoolean(
4322 R.bool.def_silence_gesture);
4323 secureSettings.insertSettingLocked(
4324 Secure.SILENCE_GESTURE, defSilenceGesture ? "1" : "0",
4325 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4326 }
4327
4328 currentVersion = 179;
4329 }
4330
Mady Mellor95e879a2019-05-06 08:50:06 -07004331 if (currentVersion == 179) {
4332 // Version 178: Reset the default for Secure Settings: NOTIFICATION_BUBBLES
4333 // This is originally set in version 173, however, the default value changed
Lyn Hanb739fa62019-06-27 18:41:11 -07004334 // so this step is to ensure the value is updated to the correct default.
Mady Mellor95e879a2019-05-06 08:50:06 -07004335
Lyn Hanb739fa62019-06-27 18:41:11 -07004336 // Removed. Moved NOTIFICATION_BUBBLES to Global Settings.
Mady Mellor95e879a2019-05-06 08:50:06 -07004337 currentVersion = 180;
4338 }
Winson Chungd9f2fb32019-03-05 11:10:12 -08004339
Edgar Wang4870e4b2019-05-15 19:14:43 +08004340 if (currentVersion == 180) {
4341 // Version 180: Set the default value for Secure Settings: AWARE_LOCK_ENABLED
4342
4343 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4344
4345 final Setting awareLockEnabled = secureSettings.getSettingLocked(
4346 Secure.AWARE_LOCK_ENABLED);
4347
4348 if (awareLockEnabled.isNull()) {
4349 final boolean defAwareLockEnabled = getContext().getResources().getBoolean(
4350 R.bool.def_aware_lock_enabled);
4351 secureSettings.insertSettingLocked(
4352 Secure.AWARE_LOCK_ENABLED, defAwareLockEnabled ? "1" : "0",
4353 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4354 }
4355
4356 currentVersion = 181;
4357 }
4358
Eric Laurent02153e62019-06-12 17:20:03 -07004359 if (currentVersion == 181) {
4360 // Version cd : by default, add STREAM_BLUETOOTH_SCO to list of streams that can
4361 // be muted.
4362 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4363 final Setting currentSetting = systemSettings.getSettingLocked(
4364 Settings.System.MUTE_STREAMS_AFFECTED);
4365 if (!currentSetting.isNull()) {
4366 try {
4367 int currentSettingIntegerValue = Integer.parseInt(
4368 currentSetting.getValue());
4369 if ((currentSettingIntegerValue
4370 & (1 << AudioManager.STREAM_BLUETOOTH_SCO)) == 0) {
4371 systemSettings.insertSettingLocked(
4372 Settings.System.MUTE_STREAMS_AFFECTED,
4373 Integer.toString(
4374 currentSettingIntegerValue
4375 | (1 << AudioManager.STREAM_BLUETOOTH_SCO)),
4376 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4377 }
4378 } catch (NumberFormatException e) {
4379 // remove the setting in case it is not a valid integer
4380 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4381 + "setting, removing setting", e);
4382 systemSettings.deleteSettingLocked(
4383 Settings.System.MUTE_STREAMS_AFFECTED);
4384 }
4385
4386 }
4387 currentVersion = 182;
4388 }
4389
Lyn Hanb739fa62019-06-27 18:41:11 -07004390 if (currentVersion == 182) {
4391 // Remove secure bubble settings.
Mady Mellorfa9556a2019-09-19 11:10:31 -07004392 getSecureSettingsLocked(userId).deleteSettingLocked("notification_bubbles");
Lyn Hanb739fa62019-06-27 18:41:11 -07004393
4394 // Add global bubble settings.
4395 getGlobalSettingsLocked().insertSettingLocked(Global.NOTIFICATION_BUBBLES,
4396 getContext().getResources().getBoolean(
4397 R.bool.def_notification_bubbles) ? "1" : "0", null /* tag */,
4398 true /* makeDefault */, SettingsState.SYSTEM_PACKAGE_NAME);
4399
4400 currentVersion = 183;
4401 }
4402
Beverlyf364d7c2019-10-10 16:44:43 -04004403 if (currentVersion == 183) {
4404 // Version 184: Set default values for WIRELESS_CHARGING_STARTED_SOUND
4405 // and CHARGING_STARTED_SOUND
4406 final SettingsState globalSettings = getGlobalSettingsLocked();
4407
4408 final String oldValueWireless = globalSettings.getSettingLocked(
4409 Global.WIRELESS_CHARGING_STARTED_SOUND).getValue();
4410 final String oldValueWired = globalSettings.getSettingLocked(
4411 Global.CHARGING_STARTED_SOUND).getValue();
4412
4413 final String defaultValueWireless = getContext().getResources().getString(
4414 R.string.def_wireless_charging_started_sound);
4415 final String defaultValueWired = getContext().getResources().getString(
4416 R.string.def_charging_started_sound);
4417
4418 // wireless charging sound
4419 if (oldValueWireless == null
4420 || TextUtils.equals(oldValueWireless, defaultValueWired)) {
4421 if (!TextUtils.isEmpty(defaultValueWireless)) {
4422 globalSettings.insertSettingLocked(
4423 Global.WIRELESS_CHARGING_STARTED_SOUND, defaultValueWireless,
4424 null /* tag */, true /* makeDefault */,
4425 SettingsState.SYSTEM_PACKAGE_NAME);
4426 } else if (!TextUtils.isEmpty(defaultValueWired)) {
4427 // if the wireless sound is empty, use the wired charging sound
4428 globalSettings.insertSettingLocked(
4429 Global.WIRELESS_CHARGING_STARTED_SOUND, defaultValueWired,
4430 null /* tag */, true /* makeDefault */,
4431 SettingsState.SYSTEM_PACKAGE_NAME);
4432 }
4433 }
4434
4435 // wired charging sound
4436 if (oldValueWired == null && !TextUtils.isEmpty(defaultValueWired)) {
4437 globalSettings.insertSettingLocked(
4438 Global.CHARGING_STARTED_SOUND, defaultValueWired,
4439 null /* tag */, true /* makeDefault */,
4440 SettingsState.SYSTEM_PACKAGE_NAME);
4441 }
4442 currentVersion = 184;
4443 }
4444
Felipe Lemeff355092017-04-03 12:55:02 -07004445 // vXXX: Add new settings above this point.
4446
Dan Sandler71f85e92016-07-20 13:46:05 -04004447 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004448 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004449 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004450 + currentVersion +
4451 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4452 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004453 if (DEBUG) {
4454 throw new RuntimeException("db upgrade error");
4455 }
4456 }
4457
Jeff Brown503cffc2015-03-26 18:08:51 -07004458 // Return the current version.
4459 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004460 }
4461 }
Svet Ganov13701552017-02-23 12:45:17 -08004462
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004463 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4464 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004465 List<String> names = settings.getSettingNamesLocked();
4466 final int nameCount = names.size();
4467 for (int i = 0; i < nameCount; i++) {
4468 String name = names.get(i);
4469 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004470
4471 // In the upgrade case we pretend the call is made from the app
4472 // that made the last change to the setting to properly determine
4473 // whether the call has been made by a system component.
4474 int callingUid = -1;
4475 try {
4476 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4477 } catch (RemoteException e) {
4478 /* ignore - handled below */
4479 }
4480 if (callingUid < 0) {
4481 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4482 continue;
4483 }
4484 try {
4485 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07004486 setting.getPackageName(), callingUid, userId);
Svet Ganov13701552017-02-23 12:45:17 -08004487 if (systemSet) {
4488 settings.insertSettingLocked(name, setting.getValue(),
4489 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004490 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4491 // We had a bug where changes by non-system packages were marked
4492 // as system made and as a result set as the default. Therefore, if
4493 // the package changed the setting last is not a system one but the
4494 // setting is marked as its default coming from the system we clear
4495 // the default and clear the system set flag.
4496 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004497 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004498 } catch (IllegalStateException e) {
4499 // If the package goes over its quota during the upgrade, don't
4500 // crash but just log the error as the system does the upgrade.
4501 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4502
Svet Ganov13701552017-02-23 12:45:17 -08004503 }
4504 }
4505 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004506 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004507}