blob: 1072076382058ff1249c018cd18a758eee462c95 [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;
Rhed Jao129d4192019-11-28 17:28:53 +080023import static android.provider.Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_MAGNIFICATION_CONTROLLER;
Winson Chungd9f2fb32019-03-05 11:10:12 -080024import static android.view.WindowManagerPolicyConstants.NAV_BAR_MODE_2BUTTON_OVERLAY;
yuemingw1d13eae2018-01-30 17:27:54 +000025
Svetoslav683914b2015-01-15 14:22:26 -080026import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080027import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070028import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070029import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070030import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080031import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070032import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080033import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.ContentValues;
36import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070037import android.content.Intent;
38import android.content.IntentFilter;
Winson Chungd9f2fb32019-03-05 11:10:12 -080039import android.content.om.IOverlayManager;
Svetoslav683914b2015-01-15 14:22:26 -080040import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070041import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070044import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070045import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070046import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080047import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.database.sqlite.SQLiteDatabase;
49import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040051import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070053import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080054import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080055import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070056import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080057import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070058import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070059import android.os.HandlerThread;
Christopher Tate65fb2e42019-10-11 17:00:23 -070060import android.os.IUserRestrictionsListener;
Svetoslav7e0683b2015-08-03 16:02:52 -070061import android.os.Looper;
62import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070064import android.os.Process;
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +000065import android.os.RemoteCallback;
Xiaohui Chen43765b72015-08-31 10:57:33 -070066import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070067import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070068import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070069import android.os.UserHandle;
70import android.os.UserManager;
Matt Pape1278d1c2018-12-11 13:03:49 -080071import android.provider.DeviceConfig;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010073import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080074import android.provider.Settings.Secure;
Al Sutton91f89d02019-08-16 12:56:57 +010075import android.provider.settings.validators.SystemSettingsValidators;
Al Suttonb0067fb2019-08-16 10:34:46 +010076import android.provider.settings.validators.Validator;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070077import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010078import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080079import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070080import android.util.Slog;
81import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070082import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080083import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040084
Svetoslav683914b2015-01-15 14:22:26 -080085import com.android.internal.annotations.GuardedBy;
86import com.android.internal.content.PackageMonitor;
87import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080088import com.android.providers.settings.SettingsState.Setting;
Ruben Brunk98576cf2016-03-07 18:54:28 -080089import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040090
Irina Dumitrescue3696872019-01-09 16:07:59 +000091import com.google.android.collect.Sets;
92
Neil Fuller3447fb42019-04-08 22:03:14 +010093import libcore.util.HexEncoding;
94
Svetoslav683914b2015-01-15 14:22:26 -080095import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080096import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080097import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080098import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import java.nio.ByteBuffer;
100import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +0000101import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -0800102import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700103import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -0800104import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +0000105import java.util.Collection;
Matt Pape4bd0a6a2019-11-19 12:17:45 -0800106import java.util.Collections;
Matt Pape6bfc62e2018-11-28 13:16:03 -0800107import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +0000108import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -0800109import java.util.List;
Andre Lago3fa139c2016-08-04 13:53:44 +0100110import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800111import java.util.Set;
112import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000113
Mark Rathjen7599f132017-01-23 14:15:54 -0800114import javax.crypto.Mac;
115import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116
Svetoslav Ganove080da92016-12-21 17:10:35 -0800117
Svetoslav683914b2015-01-15 14:22:26 -0800118/**
119 * <p>
120 * This class is a content provider that publishes the system settings.
121 * It can be accessed via the content provider APIs or via custom call
122 * commands. The latter is a bit faster and is the preferred way to access
123 * the platform settings.
124 * </p>
125 * <p>
126 * There are three settings types, global (with signature level protection
127 * and shared across users), secure (with signature permission level
128 * protection and per user), and system (with dangerous permission level
129 * protection and per user). Global settings are stored under the device owner.
130 * Each of these settings is represented by a {@link
131 * com.android.providers.settings.SettingsState} object mapped to an integer
132 * key derived from the setting type in the most significant bits and user
133 * id in the least significant bits. Settings are synchronously loaded on
134 * instantiation of a SettingsState and asynchronously persisted on mutation.
135 * Settings are stored in the user specific system directory.
136 * </p>
137 * <p>
138 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
139 * and get a warning. Targeting higher API version prohibits this as the
140 * system settings are not a place for apps to save their state. When a package
141 * is removed the settings it added are deleted. Apps cannot delete system
142 * settings added by the platform. System settings values are validated to
143 * ensure the clients do not put bad values. Global and secure settings are
144 * changed only by trusted parties, therefore no validation is performed. Also
145 * there is a limit on the amount of app specific settings that can be added
146 * to prevent unlimited growth of the system process memory footprint.
147 * </p>
148 */
149@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700150public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700151 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700152
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700153 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800154
155 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700156
Christopher Tate06efb532012-08-24 15:29:27 -0700157 private static final String TABLE_SYSTEM = "system";
158 private static final String TABLE_SECURE = "secure";
159 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800160
161 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private static final String TABLE_FAVORITES = "favorites";
163 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800164 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
165 private static final String TABLE_BOOKMARKS = "bookmarks";
166 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Svetoslav683914b2015-01-15 14:22:26 -0800168 // The set of removed legacy tables.
169 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700170 static {
Svetoslav683914b2015-01-15 14:22:26 -0800171 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
172 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
173 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
174 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
175 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
176 }
Christopher Tate06efb532012-08-24 15:29:27 -0700177
Svetoslav683914b2015-01-15 14:22:26 -0800178 private static final int MUTATION_OPERATION_INSERT = 1;
179 private static final int MUTATION_OPERATION_DELETE = 2;
180 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800181 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400182
Svetoslav683914b2015-01-15 14:22:26 -0800183 private static final String[] ALL_COLUMNS = new String[] {
184 Settings.NameValueTable._ID,
185 Settings.NameValueTable.NAME,
186 Settings.NameValueTable.VALUE
187 };
188
Makoto Onuki53f0e022017-11-29 13:51:01 -0800189 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
190 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
191 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
192 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700193 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700194
195 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
196 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700197
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800198 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800199 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800200
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700201 // Overlay specified settings whitelisted for Instant Apps
202 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
203 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
204 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
205
206 static {
207 for (String name : Resources.getSystem().getStringArray(
208 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
209 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
210 }
211 for (String name : Resources.getSystem().getStringArray(
212 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
213 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
214 }
215 for (String name : Resources.getSystem().getStringArray(
216 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
217 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
218 }
219 }
220
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800221 // Changes to these global settings are synchronously persisted
222 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
223 static {
224 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
225 }
226
227 // Changes to these secure settings are synchronously persisted
228 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
229 static {
230 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
231 }
232
Svetoslav683914b2015-01-15 14:22:26 -0800233 // Per user secure settings that moved to the for all users global settings.
234 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
235 static {
236 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700237 }
238
Svetoslav683914b2015-01-15 14:22:26 -0800239 // Per user system settings that moved to the for all users global settings.
240 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
241 static {
242 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700243 }
244
Svetoslav683914b2015-01-15 14:22:26 -0800245 // Per user system settings that moved to the per user secure settings.
246 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
247 static {
248 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249 }
250
Svetoslav683914b2015-01-15 14:22:26 -0800251 // Per all users global settings that moved to the per user secure settings.
252 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
253 static {
254 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255 }
256
Svetoslav683914b2015-01-15 14:22:26 -0800257 // Per user secure settings that are cloned for the managed profiles of the user.
258 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
259 static {
260 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700261 }
262
Svetoslav683914b2015-01-15 14:22:26 -0800263 // Per user system settings that are cloned for the managed profiles of the user.
264 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
265 static {
266 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400267 }
268
Andre Lago3fa139c2016-08-04 13:53:44 +0100269 // Per user system settings that are cloned from the profile's parent when a dependency
270 // in {@link Settings.Secure} is set to "1".
271 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
272 static {
273 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
274 }
275
Svetoslav683914b2015-01-15 14:22:26 -0800276 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700277
Svetoslav683914b2015-01-15 14:22:26 -0800278 @GuardedBy("mLock")
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +0000279 private RemoteCallback mConfigMonitorCallback;
280
281 @GuardedBy("mLock")
Svetoslav683914b2015-01-15 14:22:26 -0800282 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700283
Svet Ganova8f90262016-05-10 08:44:48 -0700284 @GuardedBy("mLock")
285 private HandlerThread mHandlerThread;
286
Makoto Onuki73360ab2017-03-17 11:50:13 -0700287 @GuardedBy("mLock")
288 private Handler mHandler;
289
Svetoslav7ec28e82015-05-20 17:01:10 -0700290 // We have to call in the user manager with no lock held,
291 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800292
Svetoslav7ec28e82015-05-20 17:01:10 -0700293 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700294 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700295
Svet Ganov53a441c2016-04-19 19:38:00 -0700296 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800297 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700298 }
299
300 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800301 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700302 }
303
304 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800305 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700306 }
307
308 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800309 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700310 }
311
312 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800313 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700314 }
315
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700316 @Override
317 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800318 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000319
Svetoslav683914b2015-01-15 14:22:26 -0800320 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700321 mUserManager = UserManager.get(getContext());
322 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700323 mHandlerThread = new HandlerThread(LOG_TAG,
324 Process.THREAD_PRIORITY_BACKGROUND);
325 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700326 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800327 mSettingsRegistry = new SettingsRegistry();
328 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700329 mHandler.post(() -> {
330 registerBroadcastReceivers();
331 startWatchingUserRestrictionChanges();
332 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700333 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800334 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700335 return true;
336 }
337
Svetoslav683914b2015-01-15 14:22:26 -0800338 @Override
339 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700340 final int requestingUserId = getRequestingUserId(args);
341 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700342 case Settings.CALL_METHOD_GET_CONFIG: {
343 Setting setting = getConfigSetting(name);
344 return packageValueForCallResult(setting, isTrackingGeneration(args));
345 }
346
Svetoslav7ec28e82015-05-20 17:01:10 -0700347 case Settings.CALL_METHOD_GET_GLOBAL: {
348 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700349 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800350 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700351
352 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800353 Setting setting = getSecureSetting(name, requestingUserId,
354 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700355 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700356 }
357
358 case Settings.CALL_METHOD_GET_SYSTEM: {
359 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700360 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700361 }
362
Matt Pape1b31a332018-10-17 09:58:28 -0700363 case Settings.CALL_METHOD_PUT_CONFIG: {
364 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700365 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800366 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700367 break;
368 }
369
Svetoslav7ec28e82015-05-20 17:01:10 -0700370 case Settings.CALL_METHOD_PUT_GLOBAL: {
371 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800372 String tag = getSettingTag(args);
373 final boolean makeDefault = getSettingMakeDefault(args);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +0000374 final boolean overrideableByRestore = getSettingOverrideableByRestore(args);
375 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false,
376 overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -0700377 break;
378 }
379
380 case Settings.CALL_METHOD_PUT_SECURE: {
381 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800382 String tag = getSettingTag(args);
383 final boolean makeDefault = getSettingMakeDefault(args);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +0000384 final boolean overrideableByRestore = getSettingOverrideableByRestore(args);
385 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false,
386 overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -0700387 break;
388 }
389
390 case Settings.CALL_METHOD_PUT_SYSTEM: {
391 String value = getSettingValue(args);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +0000392 boolean overrideableByRestore = getSettingOverrideableByRestore(args);
393 insertSystemSetting(name, value, requestingUserId, overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -0700394 break;
395 }
396
Matt Pape4bd0a6a2019-11-19 12:17:45 -0800397 case Settings.CALL_METHOD_SET_ALL_CONFIG: {
398 String prefix = getSettingPrefix(args);
399 Map<String, String> flags = getSettingFlags(args);
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +0000400 Bundle result = new Bundle();
401 result.putBoolean(Settings.KEY_CONFIG_SET_RETURN,
402 setAllConfigSettings(prefix, flags));
403 return result;
Matt Pape4bd0a6a2019-11-19 12:17:45 -0800404 }
405
Matt Pape1b31a332018-10-17 09:58:28 -0700406 case Settings.CALL_METHOD_RESET_CONFIG: {
407 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800408 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800409 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700410 break;
411 }
412
Svetoslav Ganove080da92016-12-21 17:10:35 -0800413 case Settings.CALL_METHOD_RESET_GLOBAL: {
414 final int mode = getResetModeEnforcingPermission(args);
415 String tag = getSettingTag(args);
416 resetGlobalSetting(requestingUserId, mode, tag);
417 break;
418 }
419
420 case Settings.CALL_METHOD_RESET_SECURE: {
421 final int mode = getResetModeEnforcingPermission(args);
422 String tag = getSettingTag(args);
423 resetSecureSetting(requestingUserId, mode, tag);
424 break;
425 }
426
Matt Pape6bfc62e2018-11-28 13:16:03 -0800427 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800428 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800429 Bundle result = new Bundle();
430 result.putInt(RESULT_ROWS_DELETED, rows);
431 return result;
432 }
433
434 case Settings.CALL_METHOD_DELETE_GLOBAL: {
435 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
436 Bundle result = new Bundle();
437 result.putInt(RESULT_ROWS_DELETED, rows);
438 return result;
439 }
440
Matt Pape6bfc62e2018-11-28 13:16:03 -0800441 case Settings.CALL_METHOD_DELETE_SECURE: {
442 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
443 Bundle result = new Bundle();
444 result.putInt(RESULT_ROWS_DELETED, rows);
445 return result;
446 }
447
448 case Settings.CALL_METHOD_DELETE_SYSTEM: {
449 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
450 Bundle result = new Bundle();
451 result.putInt(RESULT_ROWS_DELETED, rows);
452 return result;
453 }
454
455 case Settings.CALL_METHOD_LIST_CONFIG: {
456 String prefix = getSettingPrefix(args);
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +0000457 Bundle result = packageValuesForCallResult(getAllConfigFlags(prefix),
Matt Pape793b15c2019-10-07 13:17:20 -0700458 isTrackingGeneration(args));
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +0000459 reportDeviceConfigAccess(prefix);
460 return result;
461 }
462
463 case Settings.CALL_METHOD_REGISTER_MONITOR_CALLBACK_CONFIG: {
464 RemoteCallback callback = args.getParcelable(
465 Settings.CALL_METHOD_MONITOR_CALLBACK_KEY);
466 setMonitorCallback(callback);
467 break;
Matt Pape6bfc62e2018-11-28 13:16:03 -0800468 }
469
470 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800471 Bundle result = new Bundle();
472 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800473 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800474 return result;
475 }
476
477 case Settings.CALL_METHOD_LIST_SECURE: {
478 Bundle result = new Bundle();
479 result.putStringArrayList(RESULT_SETTINGS_LIST,
480 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
481 return result;
482 }
483
Matt Pape6bfc62e2018-11-28 13:16:03 -0800484 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800485 Bundle result = new Bundle();
486 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800487 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800488 return result;
489 }
490
Svetoslav7ec28e82015-05-20 17:01:10 -0700491 default: {
492 Slog.w(LOG_TAG, "call() with invalid method: " + method);
493 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700494 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700495
Christopher Tate06efb532012-08-24 15:29:27 -0700496 return null;
497 }
498
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800499 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800500 public String getType(Uri uri) {
501 Arguments args = new Arguments(uri, null, null, true);
502 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700503 return "vnd.android.cursor.dir/" + args.table;
504 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700505 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506 }
507 }
508
509 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800510 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
511 String order) {
512 if (DEBUG) {
513 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514 }
515
Svetoslav683914b2015-01-15 14:22:26 -0800516 Arguments args = new Arguments(uri, where, whereArgs, true);
517 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700518
Svetoslav683914b2015-01-15 14:22:26 -0800519 // If a legacy table that is gone, done.
520 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
521 return new MatrixCursor(normalizedProjection, 0);
522 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700523
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 switch (args.table) {
525 case TABLE_GLOBAL: {
526 if (args.name != null) {
527 Setting setting = getGlobalSetting(args.name);
528 return packageSettingForQuery(setting, normalizedProjection);
529 } else {
530 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700531 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700532 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700533
Svetoslav7ec28e82015-05-20 17:01:10 -0700534 case TABLE_SECURE: {
535 final int userId = UserHandle.getCallingUserId();
536 if (args.name != null) {
537 Setting setting = getSecureSetting(args.name, userId);
538 return packageSettingForQuery(setting, normalizedProjection);
539 } else {
540 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800541 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700542 }
Svetoslav683914b2015-01-15 14:22:26 -0800543
Svetoslav7ec28e82015-05-20 17:01:10 -0700544 case TABLE_SYSTEM: {
545 final int userId = UserHandle.getCallingUserId();
546 if (args.name != null) {
547 Setting setting = getSystemSetting(args.name, userId);
548 return packageSettingForQuery(setting, normalizedProjection);
549 } else {
550 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800551 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 }
Svetoslav683914b2015-01-15 14:22:26 -0800553
Svetoslav7ec28e82015-05-20 17:01:10 -0700554 default: {
555 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700556 }
557 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700558 }
559
Nicholas Sauer72500532018-11-21 10:30:58 -0800560 private ArrayList<String> buildSettingsList(Cursor cursor) {
561 final ArrayList<String> lines = new ArrayList<String>();
562 try {
563 while (cursor != null && cursor.moveToNext()) {
564 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
565 }
566 } finally {
567 if (cursor != null) {
568 cursor.close();
569 }
570 }
571 return lines;
572 }
573
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700574 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800575 public Uri insert(Uri uri, ContentValues values) {
576 if (DEBUG) {
577 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700578 }
579
Svetoslav683914b2015-01-15 14:22:26 -0800580 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700581
Svetoslav683914b2015-01-15 14:22:26 -0800582 // If a legacy table that is gone, done.
583 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 return null;
585 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586
Svetoslav683914b2015-01-15 14:22:26 -0800587 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700588 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800589 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700590 }
591
Svetoslav683914b2015-01-15 14:22:26 -0800592 String value = values.getAsString(Settings.Secure.VALUE);
593
Svetoslav7ec28e82015-05-20 17:01:10 -0700594 switch (table) {
595 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800596 if (insertGlobalSetting(name, value, null, false,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +0000597 UserHandle.getCallingUserId(), false,
598 /* overrideableByRestore */ false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700599 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700600 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700601 } break;
602
603 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800604 if (insertSecureSetting(name, value, null, false,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +0000605 UserHandle.getCallingUserId(), false,
606 /* overrideableByRestore */ false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700607 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
608 }
609 } break;
610
611 case TABLE_SYSTEM: {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +0000612 if (insertSystemSetting(name, value, UserHandle.getCallingUserId(),
613 /* overridableByRestore */ false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700614 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
615 }
616 } break;
617
618 default: {
619 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700620 }
621 }
622
Svetoslav683914b2015-01-15 14:22:26 -0800623 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700624 }
625
626 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800627 public int bulkInsert(Uri uri, ContentValues[] allValues) {
628 if (DEBUG) {
629 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700631
Svetoslav683914b2015-01-15 14:22:26 -0800632 int insertionCount = 0;
633 final int valuesCount = allValues.length;
634 for (int i = 0; i < valuesCount; i++) {
635 ContentValues values = allValues[i];
636 if (insert(uri, values) != null) {
637 insertionCount++;
638 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700639 }
Svetoslav683914b2015-01-15 14:22:26 -0800640
641 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700642 }
643
644 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800645 public int delete(Uri uri, String where, String[] whereArgs) {
646 if (DEBUG) {
647 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700649
Svetoslav683914b2015-01-15 14:22:26 -0800650 Arguments args = new Arguments(uri, where, whereArgs, false);
651
652 // If a legacy table that is gone, done.
653 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
654 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700655 }
Svetoslav683914b2015-01-15 14:22:26 -0800656
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700657 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800658 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700659 }
Svetoslav683914b2015-01-15 14:22:26 -0800660
Svetoslav7ec28e82015-05-20 17:01:10 -0700661 switch (args.table) {
662 case TABLE_GLOBAL: {
663 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700664 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700665 }
Svetoslav683914b2015-01-15 14:22:26 -0800666
Svetoslav7ec28e82015-05-20 17:01:10 -0700667 case TABLE_SECURE: {
668 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700669 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700670 }
Svetoslav683914b2015-01-15 14:22:26 -0800671
Svetoslav7ec28e82015-05-20 17:01:10 -0700672 case TABLE_SYSTEM: {
673 final int userId = UserHandle.getCallingUserId();
674 return deleteSystemSetting(args.name, userId) ? 1 : 0;
675 }
676
677 default: {
678 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800679 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700680 }
Svetoslav683914b2015-01-15 14:22:26 -0800681 }
682
683 @Override
684 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
685 if (DEBUG) {
686 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700687 }
Svetoslav683914b2015-01-15 14:22:26 -0800688
689 Arguments args = new Arguments(uri, where, whereArgs, false);
690
691 // If a legacy table that is gone, done.
692 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
693 return 0;
694 }
695
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700696 String name = values.getAsString(Settings.Secure.NAME);
697 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800698 return 0;
699 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700700 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800701
Svetoslav7ec28e82015-05-20 17:01:10 -0700702 switch (args.table) {
703 case TABLE_GLOBAL: {
704 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800705 return updateGlobalSetting(args.name, value, null, false,
706 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700707 }
Svetoslav683914b2015-01-15 14:22:26 -0800708
Svetoslav7ec28e82015-05-20 17:01:10 -0700709 case TABLE_SECURE: {
710 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800711 return updateSecureSetting(args.name, value, null, false,
712 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700713 }
Svetoslav683914b2015-01-15 14:22:26 -0800714
Svetoslav7ec28e82015-05-20 17:01:10 -0700715 case TABLE_SYSTEM: {
716 final int userId = UserHandle.getCallingUserId();
717 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
718 }
Svetoslav683914b2015-01-15 14:22:26 -0800719
Svetoslav7ec28e82015-05-20 17:01:10 -0700720 default: {
721 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800722 }
723 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700724 }
725
726 @Override
727 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100728 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
729 if (userId != UserHandle.getCallingUserId()) {
730 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
731 "Access files from the settings of another user");
732 }
733 uri = ContentProvider.getUriWithoutUserId(uri);
734
Andre Lago3fa139c2016-08-04 13:53:44 +0100735 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700736 final String cacheName;
737 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100738 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700739 cacheName = Settings.System.RINGTONE_CACHE;
740 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100741 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700742 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
743 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100744 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700745 cacheName = Settings.System.ALARM_ALERT_CACHE;
746 } else {
747 throw new FileNotFoundException("Direct file access no longer supported; "
748 + "ringtone playback is available through android.media.Ringtone");
749 }
750
Andre Lago3fa139c2016-08-04 13:53:44 +0100751 int actualCacheOwner;
752 // Redirect cache to parent if ringtone setting is owned by profile parent
753 synchronized (mLock) {
754 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
755 cacheRingtoneSetting);
756 }
757 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700758 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
759 }
760
761 private File getRingtoneCacheDir(int userId) {
762 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
763 cacheDir.mkdir();
764 SELinux.restorecon(cacheDir);
765 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700766 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800767
Eugene Suslad72c3972016-12-27 15:49:30 -0800768 /**
769 * Dump all settings as a proto buf.
770 *
771 * @param fd The file to dump to
772 */
773 void dumpProto(@NonNull FileDescriptor fd) {
774 ProtoOutputStream proto = new ProtoOutputStream(fd);
775
776 synchronized (mLock) {
777 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800778 }
779
780 proto.flush();
781 }
782
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700783 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800784 synchronized (mLock) {
785 final long identity = Binder.clearCallingIdentity();
786 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700787 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800788 final int userCount = users.size();
789 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700790 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800791 }
792 } finally {
793 Binder.restoreCallingIdentity(identity);
794 }
795 }
796 }
797
Andreas Gampeb58893072018-09-05 16:52:31 -0700798 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700799 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700800 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700801 pw.println("CONFIG SETTINGS (user " + userId + ")");
802 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
803 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
804 if (configSettings != null) {
805 dumpSettingsLocked(configSettings, pw);
806 pw.println();
807 configSettings.dumpHistoricalOperations(pw);
808 }
809
Svetoslavb505ccc2015-02-17 12:41:04 -0800810 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700811 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
812 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700813 if (globalSettings != null) {
814 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 pw.println();
816 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700817 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800818 }
819
820 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700821 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
822 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700823 if (secureSettings != null) {
824 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800825 pw.println();
826 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700827 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700828
Svetoslavb505ccc2015-02-17 12:41:04 -0800829 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700830 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
831 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700832 if (systemSettings != null) {
833 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800834 pw.println();
835 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700836 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800837 }
838
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700839 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
840 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800841
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700842 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800843
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700844 for (int i = 0; i < nameCount; i++) {
845 String name = names.get(i);
846 Setting setting = settingsState.getSettingLocked(name);
847 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
848 pw.print(" name:"); pw.print(toDumpString(name));
849 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800850 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700851 }
852 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800853 if (setting.getDefaultValue() != null) {
854 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800855 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 }
857 if (setting.getTag() != null) {
858 pw.print(" tag:"); pw.print(setting.getTag());
859 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800860 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700861 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800862 }
863
Svetoslav7e0683b2015-08-03 16:02:52 -0700864 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700865 if (s != null) {
866 return s;
867 }
868 return "{null}";
869 }
870
Svetoslav683914b2015-01-15 14:22:26 -0800871 private void registerBroadcastReceivers() {
872 IntentFilter userFilter = new IntentFilter();
873 userFilter.addAction(Intent.ACTION_USER_REMOVED);
874 userFilter.addAction(Intent.ACTION_USER_STOPPED);
875
876 getContext().registerReceiver(new BroadcastReceiver() {
877 @Override
878 public void onReceive(Context context, Intent intent) {
879 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700880 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800881
882 switch (intent.getAction()) {
883 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700884 synchronized (mLock) {
885 mSettingsRegistry.removeUserStateLocked(userId, true);
886 }
Svetoslav683914b2015-01-15 14:22:26 -0800887 } break;
888
889 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700890 synchronized (mLock) {
891 mSettingsRegistry.removeUserStateLocked(userId, false);
892 }
Svetoslav683914b2015-01-15 14:22:26 -0800893 } break;
894 }
895 }
896 }, userFilter);
897
898 PackageMonitor monitor = new PackageMonitor() {
899 @Override
900 public void onPackageRemoved(String packageName, int uid) {
901 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100902 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800903 UserHandle.getUserId(uid));
904 }
905 }
Mark Rathjend891f012017-01-19 04:10:37 +0000906
907 @Override
908 public void onUidRemoved(int uid) {
909 synchronized (mLock) {
910 mSettingsRegistry.onUidRemovedLocked(uid);
911 }
912 }
Zimuzoc56192c2018-07-25 10:40:01 +0100913
914 @Override
915 public void onPackageDataCleared(String packageName, int uid) {
916 synchronized (mLock) {
917 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
918 UserHandle.getUserId(uid));
919 }
920 }
Svetoslav683914b2015-01-15 14:22:26 -0800921 };
922
923 // package changes
924 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
925 UserHandle.ALL, true);
926 }
927
Svet Ganov53a441c2016-04-19 19:38:00 -0700928 private void startWatchingUserRestrictionChanges() {
929 // TODO: The current design of settings looking different based on user restrictions
930 // should be reworked to keep them separate and system code should check the setting
931 // first followed by checking the user restriction before performing an operation.
Christopher Tate65fb2e42019-10-11 17:00:23 -0700932 IUserRestrictionsListener listener = new IUserRestrictionsListener.Stub() {
933 @Override
934 public void onUserRestrictionsChanged(int userId,
935 Bundle newRestrictions, Bundle prevRestrictions) {
936 Set<String> changedRestrictions =
937 getRestrictionDiff(prevRestrictions, newRestrictions);
938 // We are changing the settings affected by restrictions to their current
939 // value with a forced update to ensure that all cross profile dependencies
940 // are taken into account. Also make sure the settings update to.. the same
941 // value passes the security checks, so clear binder calling id.
942 if (changedRestrictions.contains(UserManager.DISALLOW_SHARE_LOCATION)) {
943 final long identity = Binder.clearCallingIdentity();
944 try {
945 synchronized (mLock) {
946 Setting setting = getSecureSetting(
947 Settings.Secure.LOCATION_MODE, userId);
948 updateSecureSetting(Settings.Secure.LOCATION_MODE,
949 setting != null ? setting.getValue() : null, null,
950 true, userId, true);
951 setting = getSecureSetting(
952 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
953 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
954 setting != null ? setting.getValue() : null, null,
955 true, userId, true);
956 }
957 } finally {
958 Binder.restoreCallingIdentity(identity);
Svet Ganov53a441c2016-04-19 19:38:00 -0700959 }
Christopher Tate65fb2e42019-10-11 17:00:23 -0700960 }
961 if (changedRestrictions.contains(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
962 || changedRestrictions.contains(
963 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
964 final long identity = Binder.clearCallingIdentity();
965 try {
966 synchronized (mLock) {
967 Setting setting = getGlobalSetting(
968 Settings.Global.INSTALL_NON_MARKET_APPS);
969 String value = setting != null ? setting.getValue() : null;
970 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
971 value, null, true, userId, true);
972 }
973 } finally {
974 Binder.restoreCallingIdentity(identity);
975 }
976 }
977 if (changedRestrictions.contains(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
978 final long identity = Binder.clearCallingIdentity();
979 try {
980 synchronized (mLock) {
981 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
982 String value = setting != null ? setting.getValue() : null;
983 updateGlobalSetting(Settings.Global.ADB_ENABLED,
984 value, null, true, userId, true);
985 }
986 } finally {
987 Binder.restoreCallingIdentity(identity);
988 }
989 }
990 if (changedRestrictions.contains(UserManager.ENSURE_VERIFY_APPS)) {
991 final long identity = Binder.clearCallingIdentity();
992 try {
993 synchronized (mLock) {
Christopher Tate65fb2e42019-10-11 17:00:23 -0700994 Setting include = getGlobalSetting(
995 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
996 String includeValue = include != null ? include.getValue() : null;
997 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
998 includeValue, null, true, userId, true);
999 }
1000 } finally {
1001 Binder.restoreCallingIdentity(identity);
1002 }
1003 }
1004 if (changedRestrictions.contains(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
1005 final long identity = Binder.clearCallingIdentity();
1006 try {
1007 synchronized (mLock) {
1008 Setting setting = getGlobalSetting(
1009 Settings.Global.PREFERRED_NETWORK_MODE);
1010 String value = setting != null ? setting.getValue() : null;
1011 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
1012 value, null, true, userId, true);
1013 }
1014 } finally {
1015 Binder.restoreCallingIdentity(identity);
1016 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001017 }
1018 }
Christopher Tate65fb2e42019-10-11 17:00:23 -07001019 };
1020 mUserManager.addUserRestrictionsListener(listener);
Svet Ganov53a441c2016-04-19 19:38:00 -07001021 }
1022
Irina Dumitrescue3696872019-01-09 16:07:59 +00001023 private static Set<String> getRestrictionDiff(Bundle prevRestrictions, Bundle newRestrictions) {
1024 Set<String> restrictionNames = Sets.newArraySet();
1025 restrictionNames.addAll(prevRestrictions.keySet());
1026 restrictionNames.addAll(newRestrictions.keySet());
1027 Set<String> diff = Sets.newArraySet();
1028 for (String restrictionName : restrictionNames) {
1029 if (prevRestrictions.getBoolean(restrictionName) != newRestrictions.getBoolean(
1030 restrictionName)) {
1031 diff.add(restrictionName);
1032 }
1033 }
1034 return diff;
1035 }
1036
Matt Pape1b31a332018-10-17 09:58:28 -07001037 private Setting getConfigSetting(String name) {
1038 if (DEBUG) {
1039 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1040 }
1041
Stanislav Zholnin55799502019-03-08 14:54:55 +00001042 DeviceConfig.enforceReadPermission(getContext(), /*namespace=*/name.split("/")[0]);
Matt Pape1b31a332018-10-17 09:58:28 -07001043
1044 // Get the value.
1045 synchronized (mLock) {
1046 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1047 UserHandle.USER_SYSTEM, name);
1048 }
1049 }
1050
Matt Papec1323dc2018-12-11 12:32:42 -08001051 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001052 if (DEBUG) {
1053 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001054 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001055 }
Matt Papec1323dc2018-12-11 12:32:42 -08001056 return mutateConfigSetting(name, value, null, makeDefault,
1057 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001058 }
1059
Matt Pape4bd0a6a2019-11-19 12:17:45 -08001060 private boolean setAllConfigSettings(String prefix, Map<String, String> keyValues) {
1061 if (DEBUG) {
1062 Slog.v(LOG_TAG, "setAllConfigSettings for prefix: " + prefix);
1063 }
1064
1065 enforceWritePermission(Manifest.permission.WRITE_DEVICE_CONFIG);
1066
1067 synchronized (mLock) {
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +00001068 final int key = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1069 return mSettingsRegistry.setConfigSettingsLocked(key, prefix, keyValues,
1070 resolveCallingPackage());
Matt Pape4bd0a6a2019-11-19 12:17:45 -08001071 }
1072 }
1073
Matt Papec1323dc2018-12-11 12:32:42 -08001074 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001075 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001076 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001077 }
Matt Papec1323dc2018-12-11 12:32:42 -08001078 return mutateConfigSetting(name, null, null, false,
1079 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001080 }
1081
Matt Papec1323dc2018-12-11 12:32:42 -08001082 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001083 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001084 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001085 }
Matt Papec1323dc2018-12-11 12:32:42 -08001086 mutateConfigSetting(null, null, prefix, false,
1087 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001088 }
1089
Matt Pape6bfc62e2018-11-28 13:16:03 -08001090 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001091 boolean makeDefault, int operation, int mode) {
Stanislav Zholnin5a25a842019-03-13 14:43:26 +00001092 enforceWritePermission(Manifest.permission.WRITE_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001093
Matt Pape1b31a332018-10-17 09:58:28 -07001094 // Perform the mutation.
1095 synchronized (mLock) {
1096 switch (operation) {
1097 case MUTATION_OPERATION_INSERT: {
1098 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001099 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001100 resolveCallingPackage(), false, null,
1101 /* overrideableByRestore */ false);
Matt Pape1b31a332018-10-17 09:58:28 -07001102 }
1103
Matt Pape6bfc62e2018-11-28 13:16:03 -08001104 case MUTATION_OPERATION_DELETE: {
1105 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001106 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001107 }
1108
Matt Pape1b31a332018-10-17 09:58:28 -07001109 case MUTATION_OPERATION_RESET: {
1110 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001111 UserHandle.USER_SYSTEM, resolveCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001112 } return true;
1113 }
1114 }
1115
1116 return false;
1117 }
1118
Matt Pape793b15c2019-10-07 13:17:20 -07001119 private HashMap<String, String> getAllConfigFlags(@Nullable String prefix) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001120 if (DEBUG) {
1121 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1122 }
1123
Matt Pape91beb9c2019-10-17 15:20:34 -07001124 DeviceConfig.enforceReadPermission(getContext(),
1125 prefix != null ? prefix.split("/")[0] : null);
1126
Matt Pape6bfc62e2018-11-28 13:16:03 -08001127 synchronized (mLock) {
1128 // Get the settings.
1129 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1130 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001131 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1132 UserHandle.USER_SYSTEM);
1133
1134 final int nameCount = names.size();
Matt Pape793b15c2019-10-07 13:17:20 -07001135 HashMap<String, String> flagsToValues = new HashMap<>(names.size());
Matt Pape6bfc62e2018-11-28 13:16:03 -08001136
1137 for (int i = 0; i < nameCount; i++) {
1138 String name = names.get(i);
1139 Setting setting = settingsState.getSettingLocked(name);
1140 if (prefix == null || setting.getName().startsWith(prefix)) {
1141 flagsToValues.put(setting.getName(), setting.getValue());
1142 }
1143 }
1144
1145 return flagsToValues;
1146 }
1147 }
1148
Svetoslav7ec28e82015-05-20 17:01:10 -07001149 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001150 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001151 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001152 }
1153
Svetoslav7ec28e82015-05-20 17:01:10 -07001154 synchronized (mLock) {
1155 // Get the settings.
1156 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001157 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001158
Chad Brubaker97bccee2017-01-05 15:51:41 -08001159 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1160 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001161
Svetoslav7ec28e82015-05-20 17:01:10 -07001162 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001163
Svetoslav7ec28e82015-05-20 17:01:10 -07001164 String[] normalizedProjection = normalizeProjection(projection);
1165 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001166
Svetoslav7ec28e82015-05-20 17:01:10 -07001167 // Anyone can get the global settings, so no security checks.
1168 for (int i = 0; i < nameCount; i++) {
1169 String name = names.get(i);
1170 Setting setting = settingsState.getSettingLocked(name);
1171 appendSettingToCursor(result, setting);
1172 }
1173
1174 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001175 }
Svetoslav683914b2015-01-15 14:22:26 -08001176 }
1177
Svetoslav7ec28e82015-05-20 17:01:10 -07001178 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001179 if (DEBUG) {
1180 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1181 }
1182
Chad Brubakera6830e72017-04-28 17:34:36 -07001183 // Ensure the caller can access the setting.
1184 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1185
Svetoslav683914b2015-01-15 14:22:26 -08001186 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001187 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001188 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001189 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001190 }
Svetoslav683914b2015-01-15 14:22:26 -08001191 }
1192
Svetoslav Ganove080da92016-12-21 17:10:35 -08001193 private boolean updateGlobalSetting(String name, String value, String tag,
1194 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001195 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001196 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1197 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1198 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001200 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1201 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001202 }
1203
Svetoslav Ganove080da92016-12-21 17:10:35 -08001204 private boolean insertGlobalSetting(String name, String value, String tag,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001205 boolean makeDefault, int requestingUserId, boolean forceNotify,
1206 boolean overrideableByRestore) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001208 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1209 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1210 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001211 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001212 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001213 MUTATION_OPERATION_INSERT, forceNotify, 0, overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -07001214 }
1215
Svet Ganov53a441c2016-04-19 19:38:00 -07001216 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001217 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001218 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1219 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001220 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001221 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1222 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001223 }
1224
Svetoslav Ganove080da92016-12-21 17:10:35 -08001225 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1226 if (DEBUG) {
1227 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1228 + mode + ", " + tag + ")");
1229 }
1230 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1231 MUTATION_OPERATION_RESET, false, mode);
1232 }
1233
Christopher Tate65fb2e42019-10-11 17:00:23 -07001234 private boolean isSettingRestrictedForUser(String name, int userId,
1235 String value, int callerUid) {
1236 final long oldId = Binder.clearCallingIdentity();
1237 try {
1238 return (name != null
1239 && mUserManager.isSettingRestrictedForUser(name, userId, value, callerUid));
1240 } finally {
1241 Binder.restoreCallingIdentity(oldId);
1242 }
1243 }
1244
Svetoslav Ganove080da92016-12-21 17:10:35 -08001245 private boolean mutateGlobalSetting(String name, String value, String tag,
1246 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1247 int mode) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001248 // overrideableByRestore = false as by default settings values shouldn't be overrideable by
1249 // restore.
1250 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId, operation,
1251 forceNotify, mode, /* overrideableByRestore */ false);
1252 }
1253
1254 private boolean mutateGlobalSetting(String name, String value, String tag,
1255 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1256 int mode, boolean overrideableByRestore) {
Svetoslav683914b2015-01-15 14:22:26 -08001257 // Make sure the caller can change the settings - treated as secure.
1258 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1259
Svetoslav683914b2015-01-15 14:22:26 -08001260 // Resolve the userId on whose behalf the call is made.
1261 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1262
Makoto Onuki28da2e32015-11-20 11:30:44 -08001263 // If this is a setting that is currently restricted for this user, do not allow
1264 // unrestricting changes.
Christopher Tate65fb2e42019-10-11 17:00:23 -07001265 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001266 return false;
1267 }
1268
1269 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001270 synchronized (mLock) {
1271 switch (operation) {
1272 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001273 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1274 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001275 getCallingPackage(), forceNotify,
1276 CRITICAL_GLOBAL_SETTINGS, overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -07001277 }
Svetoslav683914b2015-01-15 14:22:26 -08001278
Svetoslav7ec28e82015-05-20 17:01:10 -07001279 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001280 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001281 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001282 }
Svetoslav683914b2015-01-15 14:22:26 -08001283
Svetoslav7ec28e82015-05-20 17:01:10 -07001284 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001285 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1286 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001287 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001288 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001289
1290 case MUTATION_OPERATION_RESET: {
1291 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1292 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1293 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001294 }
1295 }
1296
1297 return false;
1298 }
1299
Christopher Tateb218e762017-04-05 16:34:07 -07001300 private PackageInfo getCallingPackageInfo(int userId) {
1301 try {
1302 return mPackageManager.getPackageInfo(getCallingPackage(),
1303 PackageManager.GET_SIGNATURES, userId);
1304 } catch (RemoteException e) {
1305 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1306 }
1307 }
1308
Svetoslav7ec28e82015-05-20 17:01:10 -07001309 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001310 if (DEBUG) {
1311 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1312 }
1313
1314 // Resolve the userId on whose behalf the call is made.
1315 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1316
Christopher Tateb218e762017-04-05 16:34:07 -07001317 // The relevant "calling package" userId will be the owning userId for some
1318 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1319 // up front who the effective "new SSAID" user ID for that settings name will be.
1320 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1321 Settings.Secure.ANDROID_ID);
1322 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1323
Svetoslav7ec28e82015-05-20 17:01:10 -07001324 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001325 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001326
Svetoslav7ec28e82015-05-20 17:01:10 -07001327 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001328
Svetoslav7ec28e82015-05-20 17:01:10 -07001329 String[] normalizedProjection = normalizeProjection(projection);
1330 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001331
Svetoslav7ec28e82015-05-20 17:01:10 -07001332 for (int i = 0; i < nameCount; i++) {
1333 String name = names.get(i);
1334 // Determine the owning user as some profile settings are cloned from the parent.
1335 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1336 name);
Svetoslav683914b2015-01-15 14:22:26 -08001337
Alex Klyubin1991f572017-03-03 14:08:36 -08001338 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1339 // This caller is not permitted to access this setting. Pretend the setting
1340 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001341 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001342 }
Svetoslav683914b2015-01-15 14:22:26 -08001343
Mark Rathjen7599f132017-01-23 14:15:54 -08001344 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001345 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1346 final Setting setting;
1347 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001348 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001349 } else {
1350 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1351 name);
1352 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001353 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001354 }
1355
Svetoslav7ec28e82015-05-20 17:01:10 -07001356 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001357 }
Svetoslav683914b2015-01-15 14:22:26 -08001358 }
1359
Svetoslav7ec28e82015-05-20 17:01:10 -07001360 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001361 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1362 }
1363
1364 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001365 if (DEBUG) {
1366 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1367 }
1368
1369 // Resolve the userId on whose behalf the call is made.
1370 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1371
Chad Brubakera6830e72017-04-28 17:34:36 -07001372 // Ensure the caller can access the setting.
1373 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1374
Svetoslav683914b2015-01-15 14:22:26 -08001375 // Determine the owning user as some profile settings are cloned from the parent.
1376 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1377
Alex Klyubin1991f572017-03-03 14:08:36 -08001378 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1379 // This caller is not permitted to access this setting. Pretend the setting doesn't
1380 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001381 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1382 owningUserId);
1383 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001384 }
1385
Christopher Tateb218e762017-04-05 16:34:07 -07001386 // As of Android O, the SSAID is read from an app-specific entry in table
1387 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1388 if (isNewSsaidSetting(name)) {
1389 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1390 synchronized (mLock) {
1391 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001392 }
Christopher Tateb218e762017-04-05 16:34:07 -07001393 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001394 if (enableOverride) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001395 if (Secure.LOCATION_MODE.equals(name)) {
1396 final Setting overridden = getLocationModeSetting(owningUserId);
Makoto Onuki0000d322017-11-28 16:31:47 -08001397 if (overridden != null) {
1398 return overridden;
1399 }
1400 }
1401 }
Mark Rathjend891f012017-01-19 04:10:37 +00001402
Christopher Tateb218e762017-04-05 16:34:07 -07001403 // Not the SSAID; do a straight lookup
1404 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001405 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001406 owningUserId, name);
1407 }
Svetoslav683914b2015-01-15 14:22:26 -08001408 }
1409
Mark Rathjend891f012017-01-19 04:10:37 +00001410 private boolean isNewSsaidSetting(String name) {
1411 return Settings.Secure.ANDROID_ID.equals(name)
1412 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1413 }
1414
Andreas Gampeb58893072018-09-05 16:52:31 -07001415 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001416 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001417 // Get uid of caller (key) used to store ssaid value
1418 String name = Integer.toString(
1419 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1420
1421 if (DEBUG) {
1422 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1423 }
1424
1425 // Retrieve the ssaid from the table if present.
1426 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1427 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001428 // If the app is an Instant App use its stored SSAID instead of our own.
1429 final String instantSsaid;
1430 final long token = Binder.clearCallingIdentity();
1431 try {
1432 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1433 owningUserId);
1434 } catch (RemoteException e) {
1435 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1436 return null;
1437 } finally {
1438 Binder.restoreCallingIdentity(token);
1439 }
Svet Ganov96c99462017-05-05 14:27:13 -07001440
1441 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1442 SETTINGS_TYPE_SSAID, owningUserId);
1443
Chad Brubaker0d277a72017-04-12 16:56:53 -07001444 if (instantSsaid != null) {
1445 // Use the stored value if it is still valid.
1446 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001447 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001448 }
1449 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001450 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1451 true, callingPkg.packageName);
1452 if (!success) {
1453 throw new IllegalStateException("Failed to update instant app android id");
1454 }
Svet Ganov96c99462017-05-05 14:27:13 -07001455 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1456 owningUserId, name);
1457 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001458 }
Mark Rathjend891f012017-01-19 04:10:37 +00001459
1460 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001461 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001462 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1463 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001464 }
1465
Svet Ganov96c99462017-05-05 14:27:13 -07001466 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1467 }
1468
1469 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1470 // SSAID settings are located in a dedicated table for internal bookkeeping
1471 // but for the world they reside in the secure table, so adjust the key here.
1472 // We have a special name when looking it up but want the world to see it as
1473 // "android_id".
1474 if (ssaidSetting != null) {
1475 return settingsState.new Setting(ssaidSetting) {
1476 @Override
1477 public int getKey() {
1478 final int userId = getUserIdFromKey(super.getKey());
1479 return makeKey(SETTINGS_TYPE_SECURE, userId);
1480 }
1481
1482 @Override
1483 public String getName() {
1484 return Settings.Secure.ANDROID_ID;
1485 }
1486 };
1487 }
1488 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001489 }
1490
Kweku Adams5e0052b2019-02-22 15:17:52 -08001491 private Setting getLocationModeSetting(int owningUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001492 synchronized (mLock) {
1493 final Setting setting = getGlobalSetting(
1494 Global.LOCATION_GLOBAL_KILL_SWITCH);
1495 if (!"1".equals(setting.getValue())) {
1496 return null;
1497 }
1498 // Global kill-switch is enabled. Return an empty value.
1499 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1500 SETTINGS_TYPE_SECURE, owningUserId);
1501 return settingsState.new Setting(
Kweku Adams5e0052b2019-02-22 15:17:52 -08001502 Secure.LOCATION_MODE,
Makoto Onuki0000d322017-11-28 16:31:47 -08001503 "", // value
1504 "", // tag
1505 "", // default value
1506 "", // package name
1507 false, // from system
1508 "0" // id
1509 ) {
1510 @Override
1511 public boolean update(String value, boolean setDefault, String packageName,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001512 String tag, boolean forceNonSystemPackage, boolean overrideableByRestore) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001513 Slog.wtf(LOG_TAG, "update shouldn't be called on this instance.");
Makoto Onuki0000d322017-11-28 16:31:47 -08001514 return false;
1515 }
1516 };
1517 }
1518 }
1519
Svetoslav Ganove080da92016-12-21 17:10:35 -08001520 private boolean insertSecureSetting(String name, String value, String tag,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001521 boolean makeDefault, int requestingUserId, boolean forceNotify,
1522 boolean overrideableByRestore) {
Svetoslav683914b2015-01-15 14:22:26 -08001523 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001524 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001525 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1526 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001527 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001528 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001529 MUTATION_OPERATION_INSERT, forceNotify, 0, overrideableByRestore);
Svetoslav683914b2015-01-15 14:22:26 -08001530 }
1531
Svet Ganov53a441c2016-04-19 19:38:00 -07001532 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001533 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001534 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1535 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001536 }
1537
Svetoslav Ganove080da92016-12-21 17:10:35 -08001538 return mutateSecureSetting(name, null, null, false, requestingUserId,
1539 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001540 }
1541
Svetoslav Ganove080da92016-12-21 17:10:35 -08001542 private boolean updateSecureSetting(String name, String value, String tag,
1543 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001544 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001545 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001546 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1547 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001548 }
1549
Svetoslav Ganove080da92016-12-21 17:10:35 -08001550 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1551 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001552 }
1553
Svetoslav Ganove080da92016-12-21 17:10:35 -08001554 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1555 if (DEBUG) {
1556 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1557 + mode + ", " + tag + ")");
1558 }
1559
1560 mutateSecureSetting(null, null, tag, false, requestingUserId,
1561 MUTATION_OPERATION_RESET, false, mode);
1562 }
1563
1564 private boolean mutateSecureSetting(String name, String value, String tag,
1565 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1566 int mode) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001567 // overrideableByRestore = false as by default settings values shouldn't be overrideable by
1568 // restore.
1569 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId, operation,
1570 forceNotify, mode, /* overrideableByRestore */ false);
1571 }
1572
1573 private boolean mutateSecureSetting(String name, String value, String tag,
1574 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1575 int mode, boolean overrideableByRestore) {
Svetoslav683914b2015-01-15 14:22:26 -08001576 // Make sure the caller can change the settings.
1577 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1578
Svetoslav683914b2015-01-15 14:22:26 -08001579 // Resolve the userId on whose behalf the call is made.
1580 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1581
Makoto Onuki28da2e32015-11-20 11:30:44 -08001582 // If this is a setting that is currently restricted for this user, do not allow
1583 // unrestricting changes.
Christopher Tate65fb2e42019-10-11 17:00:23 -07001584 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001585 return false;
1586 }
1587
1588 // Determine the owning user as some profile settings are cloned from the parent.
1589 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1590
1591 // Only the owning user can change the setting.
1592 if (owningUserId != callingUserId) {
1593 return false;
1594 }
1595
Svetoslav683914b2015-01-15 14:22:26 -08001596 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001597 synchronized (mLock) {
Soonil Nagarkar10b19602019-09-10 15:46:32 -07001598 // Special cases for location providers (sigh).
1599 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1600 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1601 forceNotify);
1602 }
1603
Svetoslav7ec28e82015-05-20 17:01:10 -07001604 switch (operation) {
1605 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001606 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001607 owningUserId, name, value, tag, makeDefault,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001608 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS,
1609 overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -07001610 }
Svetoslav683914b2015-01-15 14:22:26 -08001611
Svetoslav7ec28e82015-05-20 17:01:10 -07001612 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001613 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001614 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001615 }
Svetoslav683914b2015-01-15 14:22:26 -08001616
Svetoslav7ec28e82015-05-20 17:01:10 -07001617 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001618 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001619 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001620 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001621 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001622
1623 case MUTATION_OPERATION_RESET: {
1624 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1625 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1626 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001627 }
1628 }
1629
1630 return false;
1631 }
1632
Svetoslav7ec28e82015-05-20 17:01:10 -07001633 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001634 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001635 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001636 }
1637
1638 // Resolve the userId on whose behalf the call is made.
1639 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1640
Svetoslav7ec28e82015-05-20 17:01:10 -07001641 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001642 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001643
Svetoslav7ec28e82015-05-20 17:01:10 -07001644 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001645
Svetoslav7ec28e82015-05-20 17:01:10 -07001646 String[] normalizedProjection = normalizeProjection(projection);
1647 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001648
Svetoslav7ec28e82015-05-20 17:01:10 -07001649 for (int i = 0; i < nameCount; i++) {
1650 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001651
Svetoslav7ec28e82015-05-20 17:01:10 -07001652 // Determine the owning user as some profile settings are cloned from the parent.
1653 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1654 name);
Svetoslav683914b2015-01-15 14:22:26 -08001655
Svetoslav7ec28e82015-05-20 17:01:10 -07001656 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001657 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001658 appendSettingToCursor(result, setting);
1659 }
1660
1661 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001662 }
Svetoslav683914b2015-01-15 14:22:26 -08001663 }
1664
Svetoslav7ec28e82015-05-20 17:01:10 -07001665 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001666 if (DEBUG) {
1667 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1668 }
1669
1670 // Resolve the userId on whose behalf the call is made.
1671 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1672
Chad Brubakera6830e72017-04-28 17:34:36 -07001673 // Ensure the caller can access the setting.
1674 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001675
Svetoslav683914b2015-01-15 14:22:26 -08001676 // Determine the owning user as some profile settings are cloned from the parent.
1677 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1678
1679 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001680 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001681 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001682 }
Svetoslav683914b2015-01-15 14:22:26 -08001683 }
1684
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001685 private boolean insertSystemSetting(String name, String value, int requestingUserId,
1686 boolean overrideableByRestore) {
Svetoslav683914b2015-01-15 14:22:26 -08001687 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001688 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001689 + requestingUserId + ")");
1690 }
1691
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001692 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
1693 overrideableByRestore);
Svetoslav683914b2015-01-15 14:22:26 -08001694 }
1695
Svetoslav7ec28e82015-05-20 17:01:10 -07001696 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001697 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001698 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001699 }
1700
Svetoslav7ec28e82015-05-20 17:01:10 -07001701 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001702 }
1703
Svetoslav7ec28e82015-05-20 17:01:10 -07001704 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001705 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001706 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001707 + requestingUserId + ")");
1708 }
1709
Svetoslav7ec28e82015-05-20 17:01:10 -07001710 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001711 }
1712
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001713 private boolean mutateSystemSetting(String name, String value, int runAsUserId, int operation) {
1714 // overrideableByRestore = false as by default settings values shouldn't be overrideable by
1715 // restore.
1716 return mutateSystemSetting(name, value, runAsUserId, operation,
1717 /* overrideableByRestore */ false);
1718 }
1719
1720 private boolean mutateSystemSetting(String name, String value, int runAsUserId, int operation,
1721 boolean overrideableByRestore) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001722 if (!hasWriteSecureSettingsPermission()) {
1723 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1724 // operation is allowed for the calling package through appops.
1725 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1726 Binder.getCallingUid(), getCallingPackage(), true)) {
1727 return false;
1728 }
Svetoslav683914b2015-01-15 14:22:26 -08001729 }
1730
Svetoslav683914b2015-01-15 14:22:26 -08001731 // Resolve the userId on whose behalf the call is made.
1732 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1733
Christopher Tate65fb2e42019-10-11 17:00:23 -07001734 if (isSettingRestrictedForUser(name, callingUserId, value, Binder.getCallingUid())) {
yuemingw1d13eae2018-01-30 17:27:54 +00001735 return false;
1736 }
1737
Svetoslavd8d25e02015-11-20 13:09:26 -08001738 // Enforce what the calling package can mutate the system settings.
1739 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1740
Svetoslav683914b2015-01-15 14:22:26 -08001741 // Determine the owning user as some profile settings are cloned from the parent.
1742 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1743
1744 // Only the owning user id can change the setting.
1745 if (owningUserId != callingUserId) {
1746 return false;
1747 }
1748
Jeff Sharkey413573a2016-02-22 17:52:45 -07001749 // Invalidate any relevant cache files
1750 String cacheName = null;
1751 if (Settings.System.RINGTONE.equals(name)) {
1752 cacheName = Settings.System.RINGTONE_CACHE;
1753 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1754 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1755 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1756 cacheName = Settings.System.ALARM_ALERT_CACHE;
1757 }
1758 if (cacheName != null) {
1759 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001760 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001761 cacheFile.delete();
1762 }
1763
Svetoslav683914b2015-01-15 14:22:26 -08001764 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001765 synchronized (mLock) {
1766 switch (operation) {
1767 case MUTATION_OPERATION_INSERT: {
1768 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001769 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001770 owningUserId, name, value, null, false, getCallingPackage(),
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00001771 false, null, overrideableByRestore);
Svetoslav7ec28e82015-05-20 17:01:10 -07001772 }
1773
1774 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001775 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001776 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001777 }
1778
1779 case MUTATION_OPERATION_UPDATE: {
1780 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001781 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001782 owningUserId, name, value, null, false, getCallingPackage(),
1783 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001784 }
Svetoslav683914b2015-01-15 14:22:26 -08001785 }
1786
Svetoslav7ec28e82015-05-20 17:01:10 -07001787 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001788 }
Svetoslav683914b2015-01-15 14:22:26 -08001789 }
1790
Billy Lau6ad2d662015-07-18 00:26:58 +01001791 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001792 // Write secure settings is a more protected permission. If caller has it we are good.
1793 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1794 == PackageManager.PERMISSION_GRANTED) {
1795 return true;
1796 }
1797
Svetoslavf41334b2015-06-23 12:06:03 -07001798 return false;
1799 }
1800
Svetoslav683914b2015-01-15 14:22:26 -08001801 private void validateSystemSettingValue(String name, String value) {
Al Sutton91f89d02019-08-16 12:56:57 +01001802 Validator validator = SystemSettingsValidators.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001803 if (validator != null && !validator.validate(value)) {
1804 throw new IllegalArgumentException("Invalid value: " + value
1805 + " for setting: " + name);
1806 }
1807 }
1808
Alex Klyubin1991f572017-03-03 14:08:36 -08001809 /**
1810 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1811 */
1812 private boolean isSecureSettingAccessible(String name, int callingUserId,
1813 int owningUserId) {
1814 // Special case for location (sigh).
1815 // This check is not inside the name-based checks below because this method performs checks
1816 // only if the calling user ID is not the same as the owning user ID.
1817 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1818 return false;
1819 }
1820
1821 switch (name) {
1822 case "bluetooth_address":
1823 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1824 // address in this secure setting. Secure settings can normally be read by any app,
1825 // which thus enables them to bypass the recently introduced restrictions on access
1826 // to device identifiers.
1827 // To mitigate this we make this setting available only to callers privileged to see
1828 // this device's MAC addresses, same as through public API
1829 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1830 return getContext().checkCallingOrSelfPermission(
1831 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1832 default:
1833 return true;
1834 }
1835 }
1836
Svetoslav683914b2015-01-15 14:22:26 -08001837 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1838 int owningUserId) {
1839 // Optimization - location providers are restricted only for managed profiles.
1840 if (callingUserId == owningUserId) {
1841 return false;
1842 }
1843 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1844 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1845 new UserHandle(callingUserId))) {
1846 return true;
1847 }
1848 return false;
1849 }
1850
Svetoslav683914b2015-01-15 14:22:26 -08001851 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1852 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1853 }
1854
1855 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001856 final int parentId;
1857 // Resolves dependency if setting has a dependency and the calling user has a parent
1858 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1859 && (parentId = getGroupParentLocked(userId)) != userId) {
1860 // The setting has a dependency and the profile has a parent
1861 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001862 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1863 final long token = Binder.clearCallingIdentity();
1864 try {
1865 Setting settingObj = getSecureSetting(dependency, userId);
1866 if (settingObj != null && settingObj.getValue().equals("1")) {
1867 return parentId;
1868 }
1869 } finally {
1870 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001871 }
1872 }
Svetoslav683914b2015-01-15 14:22:26 -08001873 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1874 }
1875
1876 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1877 final int parentId = getGroupParentLocked(userId);
1878 if (parentId != userId && keys.contains(name)) {
1879 return parentId;
1880 }
1881 return userId;
1882 }
1883
Svetoslavf41334b2015-06-23 12:06:03 -07001884 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001885 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001886 // System/root/shell can mutate whatever secure settings they want.
1887 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001888 final int appId = UserHandle.getAppId(callingUid);
1889 if (appId == android.os.Process.SYSTEM_UID
1890 || appId == Process.SHELL_UID
1891 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001892 return;
1893 }
1894
1895 switch (operation) {
1896 case MUTATION_OPERATION_INSERT:
1897 // Insert updates.
1898 case MUTATION_OPERATION_UPDATE: {
1899 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1900 return;
1901 }
1902
1903 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001904 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001905
1906 // Privileged apps can do whatever they want.
1907 if ((packageInfo.applicationInfo.privateFlags
1908 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1909 return;
1910 }
1911
1912 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1913 packageInfo.applicationInfo.targetSdkVersion, name);
1914 } break;
1915
1916 case MUTATION_OPERATION_DELETE: {
1917 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1918 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1919 throw new IllegalArgumentException("You cannot delete system defined"
1920 + " secure settings.");
1921 }
1922
1923 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001924 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001925
1926 // Privileged apps can do whatever they want.
1927 if ((packageInfo.applicationInfo.privateFlags &
1928 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1929 return;
1930 }
1931
1932 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1933 packageInfo.applicationInfo.targetSdkVersion, name);
1934 } break;
1935 }
1936 }
1937
Todd Kennedybe0b8892017-02-15 14:13:52 -08001938 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001939 switch (settingsType) {
1940 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001941 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001942 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001943 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001944 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001945 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001946 default:
1947 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1948 }
1949 }
1950
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001951 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1952 switch (settingsType) {
1953 case SETTINGS_TYPE_GLOBAL:
1954 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1955 case SETTINGS_TYPE_SYSTEM:
1956 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1957 case SETTINGS_TYPE_SECURE:
1958 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1959 default:
1960 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1961 }
1962 }
1963
Andreas Gampeb58893072018-09-05 16:52:31 -07001964 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001965 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001966 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1967 // in the current form.
1968 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001969 }
1970
Chad Brubakera6830e72017-04-28 17:34:36 -07001971 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001972 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1973 return;
1974 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001975 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001976 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001977 return;
1978 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001979 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1980 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001981 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1982 // breakage in the current form.
1983 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1984 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001985 }
1986 }
1987
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001988 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1989 // We always use the callingUid for this lookup. This means that if hypothetically an
1990 // app was installed in user A with cross user and in user B as an Instant App
1991 // the app in A would be able to see all the settings in user B. However since cross
1992 // user is a system permission and the app must be uninstalled in B and then installed as
1993 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001994 ApplicationInfo ai = null;
1995 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001996 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1997 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001998 } catch (RemoteException ignored) {
1999 }
2000 if (ai == null) {
2001 throw new IllegalStateException("Failed to lookup info for package "
2002 + getCallingPackage());
2003 }
2004 return ai;
2005 }
2006
Xiaohui Chen43765b72015-08-31 10:57:33 -07002007 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08002008 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08002009 PackageInfo packageInfo = mPackageManager.getPackageInfo(
2010 getCallingPackage(), 0, userId);
2011 if (packageInfo != null) {
2012 return packageInfo;
2013 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07002014 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08002015 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08002016 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08002017 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08002018 }
2019
2020 private int getGroupParentLocked(int userId) {
2021 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002022 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002023 return userId;
2024 }
2025 // We are in the same process with the user manager and the returned
2026 // user info is a cached instance, so just look up instead of cache.
2027 final long identity = Binder.clearCallingIdentity();
2028 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07002029 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08002030 UserInfo userInfo = mUserManager.getProfileParent(userId);
2031 return (userInfo != null) ? userInfo.id : userId;
2032 } finally {
2033 Binder.restoreCallingIdentity(identity);
2034 }
2035 }
2036
Svetoslav683914b2015-01-15 14:22:26 -08002037 private void enforceWritePermission(String permission) {
2038 if (getContext().checkCallingOrSelfPermission(permission)
2039 != PackageManager.PERMISSION_GRANTED) {
2040 throw new SecurityException("Permission denial: writing to settings requires:"
2041 + permission);
2042 }
2043 }
2044
2045 /*
2046 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2047 * This setting contains a list of the currently enabled location providers.
2048 * But helper functions in android.providers.Settings can enable or disable
2049 * a single provider by using a "+" or "-" prefix before the provider name.
2050 *
yuemingw1d13eae2018-01-30 17:27:54 +00002051 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2052 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2053 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002054 *
Svetoslav683914b2015-01-15 14:22:26 -08002055 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002056 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002057 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002058 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2059 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002060 if (TextUtils.isEmpty(value)) {
2061 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002062 }
Maggie83e03f52018-03-16 12:22:20 -07002063 Setting oldSetting = getSecureSetting(
2064 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2065 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002066 return false;
2067 }
Maggie83e03f52018-03-16 12:22:20 -07002068 String oldProviders = oldSetting.getValue();
2069 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2070 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2071 Set<String> newProvidersSet = new ArraySet<>();
2072 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002073
Maggie83e03f52018-03-16 12:22:20 -07002074 String[] providerUpdates = value.split(",");
2075 boolean inputError = false;
2076 for (String provider : providerUpdates) {
2077 // do not update location_providers_allowed when input is invalid
2078 if (TextUtils.isEmpty(provider)) {
2079 inputError = true;
2080 break;
Svetoslav683914b2015-01-15 14:22:26 -08002081 }
Maggie83e03f52018-03-16 12:22:20 -07002082 final char prefix = provider.charAt(0);
2083 // do not update location_providers_allowed when input is invalid
2084 if (prefix != '+' && prefix != '-') {
2085 inputError = true;
2086 break;
Svetoslav683914b2015-01-15 14:22:26 -08002087 }
Maggie83e03f52018-03-16 12:22:20 -07002088 // skip prefix
2089 provider = provider.substring(1);
2090 if (prefix == '+') {
2091 newProvidersSet.add(provider);
2092 } else if (prefix == '-') {
2093 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002094 }
Maggie83e03f52018-03-16 12:22:20 -07002095 }
2096 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2097 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002098 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002099 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002100 mSettingsRegistry.notifyForSettingsChange(
2101 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002102 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2103 }
Svetoslav683914b2015-01-15 14:22:26 -08002104 return false;
2105 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002106 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002107 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00002108 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS,
2109 /* overrideableByRestore */ false);
Svetoslav683914b2015-01-15 14:22:26 -08002110 }
2111
Svetoslav683914b2015-01-15 14:22:26 -08002112 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2113 int targetSdkVersion, String name) {
2114 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2115 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2116 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2117 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2118 + " This will soon become an error.");
2119 } else {
2120 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2121 + " This will soon become an error.");
2122 }
2123 } else {
2124 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2125 throw new IllegalArgumentException("You cannot change private secure settings.");
2126 } else {
2127 throw new IllegalArgumentException("You cannot keep your settings in"
2128 + " the secure settings.");
2129 }
2130 }
2131 }
2132
2133 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2134 if (requestingUserId == UserHandle.getCallingUserId()) {
2135 return requestingUserId;
2136 }
2137 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2138 Binder.getCallingUid(), requestingUserId, false, true,
2139 "get/set setting for user", null);
2140 }
2141
Matt Pape793b15c2019-10-07 13:17:20 -07002142 private Bundle packageValueForCallResult(Setting setting, boolean trackingGeneration) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002143 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002144 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002145 return NULL_SETTING_BUNDLE;
2146 }
2147 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002148 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002149 Bundle result = new Bundle();
2150 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002151 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002152
Svetoslav Ganove080da92016-12-21 17:10:35 -08002153 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002154 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002155 }
2156
Matt Pape793b15c2019-10-07 13:17:20 -07002157 private Bundle packageValuesForCallResult(HashMap<String, String> keyValues,
2158 boolean trackingGeneration) {
2159 Bundle result = new Bundle();
2160 result.putSerializable(Settings.NameValueTable.VALUE, keyValues);
2161 if (trackingGeneration) {
2162 synchronized (mLock) {
2163 mSettingsRegistry.mGenerationRegistry.addGenerationData(result,
2164 mSettingsRegistry.getSettingsLocked(
2165 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM).mKey);
2166 }
2167 }
2168
2169 return result;
2170 }
2171
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +00002172 private void setMonitorCallback(RemoteCallback callback) {
2173 if (callback == null) {
2174 return;
2175 }
2176 getContext().enforceCallingOrSelfPermission(
2177 Manifest.permission.MONITOR_DEVICE_CONFIG_ACCESS,
2178 "Permission denial: registering for config access requires: "
2179 + Manifest.permission.MONITOR_DEVICE_CONFIG_ACCESS);
2180 synchronized (mLock) {
2181 mConfigMonitorCallback = callback;
2182 }
2183 }
2184
2185 private void reportDeviceConfigAccess(@Nullable String prefix) {
2186 if (prefix == null) {
2187 return;
2188 }
2189 String callingPackage = getCallingPackage();
2190 String namespace = prefix.replace("/", "");
2191 if (DeviceConfig.getPublicNamespaces().contains(namespace)) {
2192 return;
2193 }
2194 synchronized (mLock) {
2195 if (mConfigMonitorCallback != null) {
2196 Bundle callbackResult = new Bundle();
2197 callbackResult.putString(Settings.EXTRA_MONITOR_CALLBACK_TYPE,
2198 Settings.EXTRA_ACCESS_CALLBACK);
2199 callbackResult.putString(Settings.EXTRA_CALLING_PACKAGE, callingPackage);
2200 callbackResult.putString(Settings.EXTRA_NAMESPACE, namespace);
2201 mConfigMonitorCallback.sendResult(callbackResult);
2202 }
2203 }
2204 }
2205
2206 private void reportDeviceConfigUpdate(@Nullable String prefix) {
2207 if (prefix == null) {
2208 return;
2209 }
2210 String namespace = prefix.replace("/", "");
2211 if (DeviceConfig.getPublicNamespaces().contains(namespace)) {
2212 return;
2213 }
2214 synchronized (mLock) {
2215 if (mConfigMonitorCallback != null) {
2216 Bundle callbackResult = new Bundle();
2217 callbackResult.putString(Settings.EXTRA_MONITOR_CALLBACK_TYPE,
2218 Settings.EXTRA_NAMESPACE_UPDATED_CALLBACK);
2219 callbackResult.putString(Settings.EXTRA_NAMESPACE, namespace);
2220 mConfigMonitorCallback.sendResult(callbackResult);
2221 }
2222 }
2223 }
2224
Svetoslav683914b2015-01-15 14:22:26 -08002225 private static int getRequestingUserId(Bundle args) {
2226 final int callingUserId = UserHandle.getCallingUserId();
2227 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2228 : callingUserId;
2229 }
2230
Svet Ganov53a441c2016-04-19 19:38:00 -07002231 private boolean isTrackingGeneration(Bundle args) {
2232 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2233 }
2234
Svetoslav683914b2015-01-15 14:22:26 -08002235 private static String getSettingValue(Bundle args) {
2236 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2237 }
2238
Svetoslav Ganove080da92016-12-21 17:10:35 -08002239 private static String getSettingTag(Bundle args) {
2240 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2241 }
2242
Matt Pape6bfc62e2018-11-28 13:16:03 -08002243 private static String getSettingPrefix(Bundle args) {
Matt Papec6001532019-10-24 15:50:32 -07002244 return (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002245 }
2246
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002247 private static Map<String, String> getSettingFlags(Bundle args) {
2248 return (args != null) ? (HashMap) args.getSerializable(Settings.CALL_METHOD_FLAGS_KEY)
2249 : Collections.emptyMap();
2250 }
2251
Svetoslav Ganove080da92016-12-21 17:10:35 -08002252 private static boolean getSettingMakeDefault(Bundle args) {
2253 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2254 }
2255
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00002256 private static boolean getSettingOverrideableByRestore(Bundle args) {
2257 return (args != null) && args.getBoolean(Settings.CALL_METHOD_OVERRIDEABLE_BY_RESTORE_KEY);
2258 }
2259
Svetoslav Ganove080da92016-12-21 17:10:35 -08002260 private static int getResetModeEnforcingPermission(Bundle args) {
2261 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2262 switch (mode) {
2263 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2264 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2265 throw new SecurityException("Only system, shell/root on a "
2266 + "debuggable build can reset to untrusted defaults");
2267 }
2268 return mode;
2269 }
2270 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2271 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2272 throw new SecurityException("Only system, shell/root on a "
2273 + "debuggable build can reset untrusted changes");
2274 }
2275 return mode;
2276 }
2277 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2278 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2279 throw new SecurityException("Only system, shell/root on a "
2280 + "debuggable build can reset to trusted defaults");
2281 }
2282 return mode;
2283 }
2284 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2285 return mode;
2286 }
2287 }
2288 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2289 }
2290
2291 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2292 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2293 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2294 && (appId == SHELL_UID || appId == ROOT_UID));
2295 }
2296
Svetoslav683914b2015-01-15 14:22:26 -08002297 private static String getValidTableOrThrow(Uri uri) {
2298 if (uri.getPathSegments().size() > 0) {
2299 String table = uri.getPathSegments().get(0);
2300 if (DatabaseHelper.isValidTable(table)) {
2301 return table;
2302 }
2303 throw new IllegalArgumentException("Bad root path: " + table);
2304 }
2305 throw new IllegalArgumentException("Invalid URI:" + uri);
2306 }
2307
2308 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002309 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002310 return new MatrixCursor(projection, 0);
2311 }
2312 MatrixCursor cursor = new MatrixCursor(projection, 1);
2313 appendSettingToCursor(cursor, setting);
2314 return cursor;
2315 }
2316
2317 private static String[] normalizeProjection(String[] projection) {
2318 if (projection == null) {
2319 return ALL_COLUMNS;
2320 }
2321
2322 final int columnCount = projection.length;
2323 for (int i = 0; i < columnCount; i++) {
2324 String column = projection[i];
2325 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2326 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002327 }
2328 }
2329
Svetoslav683914b2015-01-15 14:22:26 -08002330 return projection;
2331 }
2332
2333 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002334 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002335 return;
2336 }
Svetoslav683914b2015-01-15 14:22:26 -08002337 final int columnCount = cursor.getColumnCount();
2338
2339 String[] values = new String[columnCount];
2340
2341 for (int i = 0; i < columnCount; i++) {
2342 String column = cursor.getColumnName(i);
2343
2344 switch (column) {
2345 case Settings.NameValueTable._ID: {
2346 values[i] = setting.getId();
2347 } break;
2348
2349 case Settings.NameValueTable.NAME: {
2350 values[i] = setting.getName();
2351 } break;
2352
2353 case Settings.NameValueTable.VALUE: {
2354 values[i] = setting.getValue();
2355 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002356 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002357 }
2358
Svetoslav683914b2015-01-15 14:22:26 -08002359 cursor.addRow(values);
2360 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002361
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002362 private static boolean isKeyValid(String key) {
2363 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2364 }
2365
Matt Pape7b1c6cd2019-01-04 08:10:41 -08002366 private String resolveCallingPackage() {
2367 switch (Binder.getCallingUid()) {
2368 case Process.ROOT_UID: {
2369 return "root";
2370 }
2371
2372 case Process.SHELL_UID: {
2373 return "com.android.shell";
2374 }
2375
2376 default: {
2377 return getCallingPackage();
2378 }
2379 }
2380 }
2381
Svetoslav683914b2015-01-15 14:22:26 -08002382 private static final class Arguments {
2383 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2384 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2385
2386 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2387 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2388
2389 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2390 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2391
2392 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2393 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2394
2395 public final String table;
2396 public final String name;
2397
2398 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2399 final int segmentSize = uri.getPathSegments().size();
2400 switch (segmentSize) {
2401 case 1: {
2402 if (where != null
2403 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2404 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2405 && whereArgs.length == 1) {
2406 name = whereArgs[0];
2407 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002408 return;
Svetoslav683914b2015-01-15 14:22:26 -08002409 } else if (where != null
2410 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2411 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2412 final int startIndex = Math.max(where.indexOf("'"),
2413 where.indexOf("\"")) + 1;
2414 final int endIndex = Math.max(where.lastIndexOf("'"),
2415 where.lastIndexOf("\""));
2416 name = where.substring(startIndex, endIndex);
2417 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002418 return;
Svetoslav683914b2015-01-15 14:22:26 -08002419 } else if (supportAll && where == null && whereArgs == null) {
2420 name = null;
2421 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002422 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002423 }
Svetoslav683914b2015-01-15 14:22:26 -08002424 } break;
2425
Svetoslav28494652015-02-12 14:11:42 -08002426 case 2: {
2427 if (where == null && whereArgs == null) {
2428 name = uri.getPathSegments().get(1);
2429 table = computeTableForSetting(uri, name);
2430 return;
2431 }
2432 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002433 }
Svetoslav28494652015-02-12 14:11:42 -08002434
2435 EventLogTags.writeUnsupportedSettingsQuery(
2436 uri.toSafeString(), where, Arrays.toString(whereArgs));
2437 String message = String.format( "Supported SQL:\n"
2438 + " uri content://some_table/some_property with null where and where args\n"
2439 + " uri content://some_table with query name=? and single name as arg\n"
2440 + " uri content://some_table with query name=some_name and null args\n"
2441 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2442 Arrays.toString(whereArgs));
2443 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002444 }
2445
Svetoslav28494652015-02-12 14:11:42 -08002446 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002447 String table = getValidTableOrThrow(uri);
2448
2449 if (name != null) {
2450 if (sSystemMovedToSecureSettings.contains(name)) {
2451 table = TABLE_SECURE;
2452 }
2453
2454 if (sSystemMovedToGlobalSettings.contains(name)) {
2455 table = TABLE_GLOBAL;
2456 }
2457
2458 if (sSecureMovedToGlobalSettings.contains(name)) {
2459 table = TABLE_GLOBAL;
2460 }
2461
2462 if (sGlobalMovedToSecureSettings.contains(name)) {
2463 table = TABLE_SECURE;
2464 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002465 }
Svetoslav683914b2015-01-15 14:22:26 -08002466
2467 return table;
2468 }
2469 }
2470
2471 final class SettingsRegistry {
2472 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2473
Svetoslav683914b2015-01-15 14:22:26 -08002474 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2475 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2476 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002477 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002478 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002479
2480 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002481
2482 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2483
Svet Ganov53a441c2016-04-19 19:38:00 -07002484 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002485
Svetoslav7e0683b2015-08-03 16:02:52 -07002486 private final Handler mHandler;
2487
Svet Ganov53a441c2016-04-19 19:38:00 -07002488 private final BackupManager mBackupManager;
2489
Amith Yamasani39452022017-03-21 15:23:47 -07002490 private String mSettingsCreationBuildId;
2491
Svetoslav683914b2015-01-15 14:22:26 -08002492 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002493 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002494 mGenerationRegistry = new GenerationRegistry(mLock);
2495 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002496 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002497 syncSsaidTableOnStart();
2498 }
2499
2500 private void generateUserKeyLocked(int userId) {
2501 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002502 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002503 final SecureRandom rand = new SecureRandom();
2504 rand.nextBytes(keyBytes);
2505
2506 // Convert to string for storage in settings table.
Neil Fuller3447fb42019-04-08 22:03:14 +01002507 final String userKey = HexEncoding.encodeToString(keyBytes, true /* upperCase */);
Mark Rathjend891f012017-01-19 04:10:37 +00002508
2509 // Store the key in the ssaid table.
2510 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2511 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2512 true, SettingsState.SYSTEM_PACKAGE_NAME);
2513
2514 if (!success) {
2515 throw new IllegalStateException("Ssaid settings not accessible");
2516 }
2517 }
2518
Mark Rathjen7599f132017-01-23 14:15:54 -08002519 private byte[] getLengthPrefix(byte[] data) {
2520 return ByteBuffer.allocate(4).putInt(data.length).array();
2521 }
2522
Christopher Tateb218e762017-04-05 16:34:07 -07002523 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002524 // Read the user's key from the ssaid table.
2525 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002526 if (userKeySetting == null || userKeySetting.isNull()
2527 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002528 // Lazy initialize and store the user key.
2529 generateUserKeyLocked(userId);
2530 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002531 if (userKeySetting == null || userKeySetting.isNull()
2532 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002533 throw new IllegalStateException("User key not accessible");
2534 }
2535 }
2536 final String userKey = userKeySetting.getValue();
Neil Fuller3447fb42019-04-08 22:03:14 +01002537 if (userKey == null || userKey.length() % 2 != 0) {
2538 throw new IllegalStateException("User key invalid");
2539 }
Mark Rathjend891f012017-01-19 04:10:37 +00002540
2541 // Convert the user's key back to a byte array.
Neil Fuller3447fb42019-04-08 22:03:14 +01002542 final byte[] keyBytes = HexEncoding.decode(userKey);
Mark Rathjen7599f132017-01-23 14:15:54 -08002543
2544 // Validate that the key is of expected length.
2545 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
Neil Fuller3447fb42019-04-08 22:03:14 +01002546 if (keyBytes.length != 16 && keyBytes.length != 32) {
Mark Rathjend891f012017-01-19 04:10:37 +00002547 throw new IllegalStateException("User key invalid");
2548 }
2549
Mark Rathjen7599f132017-01-23 14:15:54 -08002550 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002551 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002552 m = Mac.getInstance("HmacSHA256");
2553 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002554 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002555 throw new IllegalStateException("HmacSHA256 is not available", e);
2556 } catch (InvalidKeyException e) {
2557 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002558 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002559
Mark Rathjenf42dd912017-06-05 19:04:34 -07002560 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002561 for (int i = 0; i < callingPkg.signatures.length; i++) {
2562 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002563 m.update(getLengthPrefix(sig), 0, 4);
2564 m.update(sig);
2565 }
Mark Rathjend891f012017-01-19 04:10:37 +00002566
2567 // Convert result to a string for storage in settings table. Only want first 64 bits.
Neil Fuller3447fb42019-04-08 22:03:14 +01002568 final String ssaid = HexEncoding.encodeToString(m.doFinal(), false /* upperCase */)
2569 .substring(0, 16);
Mark Rathjend891f012017-01-19 04:10:37 +00002570
2571 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002572 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002573 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2574 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002575 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002576
2577 if (!success) {
2578 throw new IllegalStateException("Ssaid settings not accessible");
2579 }
2580
2581 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2582 }
2583
2584 public void syncSsaidTableOnStart() {
2585 synchronized (mLock) {
2586 // Verify that each user's packages and ssaid's are in sync.
2587 for (UserInfo user : mUserManager.getUsers(true)) {
2588 // Get all uids for the user's packages.
2589 final List<PackageInfo> packages;
2590 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002591 packages = mPackageManager.getInstalledPackages(
2592 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2593 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002594 } catch (RemoteException e) {
2595 throw new IllegalStateException("Package manager not available");
2596 }
2597 final Set<String> appUids = new HashSet<>();
2598 for (PackageInfo info : packages) {
2599 appUids.add(Integer.toString(info.applicationInfo.uid));
2600 }
2601
2602 // Get all uids currently stored in the user's ssaid table.
2603 final Set<String> ssaidUids = new HashSet<>(
2604 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2605 ssaidUids.remove(SSAID_USER_KEY);
2606
2607 // Perform a set difference for the appUids and ssaidUids.
2608 ssaidUids.removeAll(appUids);
2609
2610 // If there are ssaidUids left over they need to be removed from the table.
2611 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2612 user.id);
2613 for (String uid : ssaidUids) {
2614 ssaidSettings.deleteSettingLocked(uid);
2615 }
2616 }
2617 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002618 }
2619
Svetoslav683914b2015-01-15 14:22:26 -08002620 public List<String> getSettingsNamesLocked(int type, int userId) {
2621 final int key = makeKey(type, userId);
2622 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002623 if (settingsState == null) {
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002624 return new ArrayList<>();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002625 }
Svetoslav683914b2015-01-15 14:22:26 -08002626 return settingsState.getSettingNamesLocked();
2627 }
2628
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002629 public SparseBooleanArray getKnownUsersLocked() {
2630 SparseBooleanArray users = new SparseBooleanArray();
2631 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2632 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2633 }
2634 return users;
2635 }
2636
Kweku Adamsb0886f32017-10-31 15:32:09 -07002637 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002638 public SettingsState getSettingsLocked(int type, int userId) {
2639 final int key = makeKey(type, userId);
2640 return peekSettingsStateLocked(key);
2641 }
2642
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002643 public boolean ensureSettingsForUserLocked(int userId) {
2644 // First make sure this user actually exists.
2645 if (mUserManager.getUserInfo(userId) == null) {
2646 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2647 return false;
2648 }
2649
Svetoslav683914b2015-01-15 14:22:26 -08002650 // Migrate the setting for this user if needed.
2651 migrateLegacySettingsForUserIfNeededLocked(userId);
2652
Matt Pape1b31a332018-10-17 09:58:28 -07002653 // Ensure config settings loaded if owner.
2654 if (userId == UserHandle.USER_SYSTEM) {
2655 final int configKey
2656 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2657 ensureSettingsStateLocked(configKey);
2658 }
2659
Svetoslav683914b2015-01-15 14:22:26 -08002660 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002661 if (userId == UserHandle.USER_SYSTEM) {
2662 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002663 ensureSettingsStateLocked(globalKey);
2664 }
2665
2666 // Ensure secure settings loaded.
2667 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2668 ensureSettingsStateLocked(secureKey);
2669
2670 // Make sure the secure settings have an Android id set.
2671 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2672 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2673
2674 // Ensure system settings loaded.
2675 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2676 ensureSettingsStateLocked(systemKey);
2677
Mark Rathjend891f012017-01-19 04:10:37 +00002678 // Ensure secure settings loaded.
2679 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2680 ensureSettingsStateLocked(ssaidKey);
2681
Svetoslav683914b2015-01-15 14:22:26 -08002682 // Upgrade the settings to the latest version.
2683 UpgradeController upgrader = new UpgradeController(userId);
2684 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002685 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002686 }
2687
2688 private void ensureSettingsStateLocked(int key) {
2689 if (mSettingsStates.get(key) == null) {
2690 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002691 SettingsState settingsState = new SettingsState(getContext(), mLock,
2692 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002693 mSettingsStates.put(key, settingsState);
2694 }
2695 }
2696
2697 public void removeUserStateLocked(int userId, boolean permanently) {
2698 // We always keep the global settings in memory.
2699
2700 // Nuke system settings.
2701 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2702 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2703 if (systemSettingsState != null) {
2704 if (permanently) {
2705 mSettingsStates.remove(systemKey);
2706 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002707 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002708 systemSettingsState.destroyLocked(new Runnable() {
2709 @Override
2710 public void run() {
2711 mSettingsStates.remove(systemKey);
2712 }
2713 });
2714 }
2715 }
2716
2717 // Nuke secure settings.
2718 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2719 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2720 if (secureSettingsState != null) {
2721 if (permanently) {
2722 mSettingsStates.remove(secureKey);
2723 secureSettingsState.destroyLocked(null);
2724 } else {
2725 secureSettingsState.destroyLocked(new Runnable() {
2726 @Override
2727 public void run() {
2728 mSettingsStates.remove(secureKey);
2729 }
2730 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002731 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002732 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002733
Mark Rathjend891f012017-01-19 04:10:37 +00002734 // Nuke ssaid settings.
2735 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2736 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2737 if (ssaidSettingsState != null) {
2738 if (permanently) {
2739 mSettingsStates.remove(ssaidKey);
2740 ssaidSettingsState.destroyLocked(null);
2741 } else {
2742 ssaidSettingsState.destroyLocked(new Runnable() {
2743 @Override
2744 public void run() {
2745 mSettingsStates.remove(ssaidKey);
2746 }
2747 });
2748 }
2749 }
2750
Svet Ganov53a441c2016-04-19 19:38:00 -07002751 // Nuke generation tracking data
2752 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002753 }
2754
Svetoslav683914b2015-01-15 14:22:26 -08002755 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002756 String tag, boolean makeDefault, String packageName, boolean forceNotify,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00002757 Set<String> criticalSettings, boolean overrideableByRestore) {
Matt Papec1323dc2018-12-11 12:32:42 -08002758 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00002759 packageName, forceNotify, criticalSettings, overrideableByRestore);
Matt Papec1323dc2018-12-11 12:32:42 -08002760 }
2761
2762 public boolean insertSettingLocked(int type, int userId, String name, String value,
2763 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00002764 boolean forceNotify, Set<String> criticalSettings, boolean overrideableByRestore) {
Svetoslav683914b2015-01-15 14:22:26 -08002765 final int key = makeKey(type, userId);
2766
Svetoslav Ganove080da92016-12-21 17:10:35 -08002767 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002768 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002769 if (settingsState != null) {
2770 success = settingsState.insertSettingLocked(name, value,
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00002771 tag, makeDefault, forceNonSystemPackage, packageName, overrideableByRestore);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002772 }
Svetoslav683914b2015-01-15 14:22:26 -08002773
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002774 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2775 settingsState.persistSyncLocked();
2776 }
2777
Svet Ganov53a441c2016-04-19 19:38:00 -07002778 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002779 notifyForSettingsChange(key, name);
2780 }
2781 return success;
2782 }
2783
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00002784 /**
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +00002785 * Set Config Settings using consumed keyValues, returns true if the keyValues can be set,
2786 * false otherwise.
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00002787 */
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +00002788 public boolean setConfigSettingsLocked(int key, String prefix,
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002789 Map<String, String> keyValues, String packageName) {
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002790 SettingsState settingsState = peekSettingsStateLocked(key);
2791 if (settingsState != null) {
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +00002792 if (settingsState.isNewConfigBannedLocked(prefix, keyValues)) {
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00002793 return false;
2794 }
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002795 List<String> changedSettings =
2796 settingsState.setSettingsLocked(prefix, keyValues, packageName);
2797 if (!changedSettings.isEmpty()) {
Bohdan Petrivskyy095a4d32019-12-18 16:03:47 +00002798 reportDeviceConfigUpdate(prefix);
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002799 notifyForConfigSettingsChangeLocked(key, prefix, changedSettings);
2800 }
2801 }
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00002802 // keyValues aren't banned and can be set
2803 return true;
Matt Pape4bd0a6a2019-11-19 12:17:45 -08002804 }
2805
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002806 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2807 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002808 final int key = makeKey(type, userId);
2809
Svetoslav Ganove080da92016-12-21 17:10:35 -08002810 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002811 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002812 if (settingsState != null) {
2813 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002814 }
Svetoslav683914b2015-01-15 14:22:26 -08002815
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002816 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2817 settingsState.persistSyncLocked();
2818 }
2819
Svet Ganov53a441c2016-04-19 19:38:00 -07002820 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002821 notifyForSettingsChange(key, name);
2822 }
2823 return success;
2824 }
2825
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002826 public boolean updateSettingLocked(int type, int userId, String name, String value,
2827 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2828 Set<String> criticalSettings) {
2829 final int key = makeKey(type, userId);
2830
2831 boolean success = false;
2832 SettingsState settingsState = peekSettingsStateLocked(key);
2833 if (settingsState != null) {
2834 success = settingsState.updateSettingLocked(name, value, tag,
2835 makeDefault, packageName);
2836 }
2837
2838 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2839 settingsState.persistSyncLocked();
2840 }
2841
2842 if (forceNotify || success) {
2843 notifyForSettingsChange(key, name);
2844 }
2845
2846 return success;
2847 }
2848
Svetoslav683914b2015-01-15 14:22:26 -08002849 public Setting getSettingLocked(int type, int userId, String name) {
2850 final int key = makeKey(type, userId);
2851
2852 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002853 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002854 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002855 }
Mark Rathjend891f012017-01-19 04:10:37 +00002856
2857 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002858 return settingsState.getSettingLocked(name);
2859 }
2860
Svetoslav Ganove080da92016-12-21 17:10:35 -08002861 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2862 String tag) {
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00002863 resetSettingsLocked(type, userId, packageName, mode, tag, /*prefix=*/
2864 null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08002865 }
2866
2867 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2868 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002869 final int key = makeKey(type, userId);
2870 SettingsState settingsState = peekSettingsStateLocked(key);
2871 if (settingsState == null) {
2872 return;
2873 }
2874
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00002875 banConfigurationIfNecessary(type, prefix, settingsState);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002876 switch (mode) {
2877 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2878 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002879 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002880 Setting setting = settingsState.getSettingLocked(name);
2881 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002882 if ((tag != null && !tag.equals(setting.getTag()))
2883 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002884 continue;
2885 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002886 if (settingsState.resetSettingLocked(name)) {
2887 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002888 notifyForSettingsChange(key, name);
2889 }
2890 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002891 if (someSettingChanged) {
2892 settingsState.persistSyncLocked();
2893 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002894 }
2895 } break;
2896
2897 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2898 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002899 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002900 Setting setting = settingsState.getSettingLocked(name);
2901 if (!SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07002902 setting.getPackageName(), INVALID_UID, userId)) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002903 if (prefix != null && !setting.getName().startsWith(prefix)) {
2904 continue;
2905 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002906 if (settingsState.resetSettingLocked(name)) {
2907 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002908 notifyForSettingsChange(key, name);
2909 }
2910 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002911 if (someSettingChanged) {
2912 settingsState.persistSyncLocked();
2913 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002914 }
2915 } break;
2916
2917 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2918 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002919 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002920 Setting setting = settingsState.getSettingLocked(name);
2921 if (!SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07002922 setting.getPackageName(), INVALID_UID, userId)) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002923 if (prefix != null && !setting.getName().startsWith(prefix)) {
2924 continue;
2925 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002926 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002927 if (settingsState.resetSettingLocked(name)) {
2928 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002929 notifyForSettingsChange(key, name);
2930 }
2931 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002932 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002933 notifyForSettingsChange(key, name);
2934 }
2935 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002936 if (someSettingChanged) {
2937 settingsState.persistSyncLocked();
2938 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002939 }
2940 } break;
2941
2942 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2943 for (String name : settingsState.getSettingNamesLocked()) {
2944 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002945 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002946 if (prefix != null && !setting.getName().startsWith(prefix)) {
2947 continue;
2948 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002949 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002950 if (settingsState.resetSettingLocked(name)) {
2951 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002952 notifyForSettingsChange(key, name);
2953 }
2954 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002955 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002956 notifyForSettingsChange(key, name);
2957 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002958 if (someSettingChanged) {
2959 settingsState.persistSyncLocked();
2960 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002961 }
2962 } break;
2963 }
2964 }
2965
Zimuzoc56192c2018-07-25 10:40:01 +01002966 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002967 // Global and secure settings are signature protected. Apps signed
2968 // by the platform certificate are generally not uninstalled and
2969 // the main exception is tests. We trust components signed
2970 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002971
2972 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2973 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002974 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002975 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002976 }
Svetoslav683914b2015-01-15 14:22:26 -08002977 }
2978
Mark Rathjend891f012017-01-19 04:10:37 +00002979 public void onUidRemovedLocked(int uid) {
2980 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2981 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002982 if (ssaidSettings != null) {
2983 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2984 }
Mark Rathjend891f012017-01-19 04:10:37 +00002985 }
2986
Kweku Adamsb0886f32017-10-31 15:32:09 -07002987 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002988 private SettingsState peekSettingsStateLocked(int key) {
2989 SettingsState settingsState = mSettingsStates.get(key);
2990 if (settingsState != null) {
2991 return settingsState;
2992 }
2993
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002994 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2995 return null;
2996 }
Svetoslav683914b2015-01-15 14:22:26 -08002997 return mSettingsStates.get(key);
2998 }
2999
3000 private void migrateAllLegacySettingsIfNeeded() {
3001 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003002 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003003 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07003004 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08003005 return;
3006 }
3007
Amith Yamasani39452022017-03-21 15:23:47 -07003008 mSettingsCreationBuildId = Build.ID;
3009
Svetoslav683914b2015-01-15 14:22:26 -08003010 final long identity = Binder.clearCallingIdentity();
3011 try {
3012 List<UserInfo> users = mUserManager.getUsers(true);
3013
3014 final int userCount = users.size();
3015 for (int i = 0; i < userCount; i++) {
3016 final int userId = users.get(i).id;
3017
3018 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
3019 SQLiteDatabase database = dbHelper.getWritableDatabase();
3020 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
3021
3022 // Upgrade to the latest version.
3023 UpgradeController upgrader = new UpgradeController(userId);
3024 upgrader.upgradeIfNeededLocked();
3025
3026 // Drop from memory if not a running user.
3027 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
3028 removeUserStateLocked(userId, false);
3029 }
3030 }
3031 } finally {
3032 Binder.restoreCallingIdentity(identity);
3033 }
3034 }
3035 }
3036
3037 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
3038 // Every user has secure settings and if no file we need to migrate.
3039 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
3040 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07003041 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08003042 return;
3043 }
3044
3045 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
3046 SQLiteDatabase database = dbHelper.getWritableDatabase();
3047
3048 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
3049 }
3050
3051 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
3052 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08003053 // Move over the system settings.
3054 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
3055 ensureSettingsStateLocked(systemKey);
3056 SettingsState systemSettings = mSettingsStates.get(systemKey);
3057 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
3058 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08003059
3060 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08003061 // Do this after System settings, since this is the first thing we check when deciding
3062 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08003063 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
3064 ensureSettingsStateLocked(secureKey);
3065 SettingsState secureSettings = mSettingsStates.get(secureKey);
3066 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
3067 ensureSecureSettingAndroidIdSetLocked(secureSettings);
3068 secureSettings.persistSyncLocked();
3069
Amith Yamasanibf2ef612016-03-07 16:37:18 -08003070 // Move over the global settings if owner.
3071 // Do this last, since this is the first thing we check when deciding
3072 // to skip over migration from db to xml for owner user.
3073 if (userId == UserHandle.USER_SYSTEM) {
3074 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
3075 ensureSettingsStateLocked(globalKey);
3076 SettingsState globalSettings = mSettingsStates.get(globalKey);
3077 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07003078 // If this was just created
3079 if (mSettingsCreationBuildId != null) {
3080 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
3081 mSettingsCreationBuildId, null, true,
3082 SettingsState.SYSTEM_PACKAGE_NAME);
3083 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08003084 globalSettings.persistSyncLocked();
3085 }
Svetoslav683914b2015-01-15 14:22:26 -08003086
3087 // Drop the database as now all is moved and persisted.
3088 if (DROP_DATABASE_ON_MIGRATION) {
3089 dbHelper.dropDatabase();
3090 } else {
3091 dbHelper.backupDatabase();
3092 }
3093 }
3094
3095 private void migrateLegacySettingsLocked(SettingsState settingsState,
3096 SQLiteDatabase database, String table) {
3097 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
3098 queryBuilder.setTables(table);
3099
3100 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
3101 null, null, null, null, null);
3102
3103 if (cursor == null) {
3104 return;
3105 }
3106
3107 try {
3108 if (!cursor.moveToFirst()) {
3109 return;
3110 }
3111
3112 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
3113 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
3114
3115 settingsState.setVersionLocked(database.getVersion());
3116
3117 while (!cursor.isAfterLast()) {
3118 String name = cursor.getString(nameColumnIdx);
3119 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08003120 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08003121 SettingsState.SYSTEM_PACKAGE_NAME);
3122 cursor.moveToNext();
3123 }
3124 } finally {
3125 cursor.close();
3126 }
3127 }
3128
Andreas Gampeb58893072018-09-05 16:52:31 -07003129 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08003130 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
3131 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
3132
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003133 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08003134 return;
3135 }
3136
3137 final int userId = getUserIdFromKey(secureSettings.mKey);
3138
3139 final UserInfo user;
3140 final long identity = Binder.clearCallingIdentity();
3141 try {
3142 user = mUserManager.getUserInfo(userId);
3143 } finally {
3144 Binder.restoreCallingIdentity(identity);
3145 }
3146 if (user == null) {
3147 // Can happen due to races when deleting users - treat as benign.
3148 return;
3149 }
3150
3151 String androidId = Long.toHexString(new SecureRandom().nextLong());
3152 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003153 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003154
3155 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3156 + "] for user " + userId);
3157
3158 // Write a drop box entry if it's a restricted profile
3159 if (user.isRestricted()) {
3160 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3161 Context.DROPBOX_SERVICE);
3162 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3163 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3164 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3165 }
3166 }
3167 }
3168
3169 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003170 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003171 mGenerationRegistry.incrementGeneration(key);
3172
Linus Tufvesson93c38552019-05-30 12:47:39 +01003173 if (isGlobalSettingsKey(key) || isConfigSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003174 final long token = Binder.clearCallingIdentity();
3175 try {
Linus Tufvesson93c38552019-05-30 12:47:39 +01003176 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)
3177 && isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003178 // When the global kill switch is updated, send the
3179 // change notification for the location setting.
3180 notifyLocationChangeForRunningUsers();
3181 }
Linus Tufvesson93c38552019-05-30 12:47:39 +01003182 notifySettingChangeForRunningUsers(key, name);
Jeff Sharkey308093f2018-03-25 22:53:29 -06003183 } finally {
3184 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003185 }
Svet Ganov945864c2018-03-22 21:49:10 -07003186 } else {
3187 final int userId = getUserIdFromKey(key);
3188 final Uri uri = getNotificationUriFor(key, name);
3189 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3190 userId, 0, uri).sendToTarget();
3191 if (isSecureSettingsKey(key)) {
3192 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3193 sSecureCloneToManagedSettings);
3194 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3195 sSystemCloneFromParentOnDependency.values());
3196 } else if (isSystemSettingsKey(key)) {
3197 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3198 sSystemCloneToManagedSettings);
3199 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003200 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003201
Svet Ganov945864c2018-03-22 21:49:10 -07003202 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003203 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003204 }
3205
Matt Pape4bd0a6a2019-11-19 12:17:45 -08003206 private void notifyForConfigSettingsChangeLocked(int key, String prefix,
3207 List<String> changedSettings) {
3208
3209 // Increment the generation first, so observers always see the new value
3210 mGenerationRegistry.incrementGeneration(key);
3211
3212 StringBuilder stringBuilder = new StringBuilder(prefix);
3213 for (int i = 0; i < changedSettings.size(); ++i) {
3214 stringBuilder.append(changedSettings.get(i).split("/")[1]).append("/");
3215 }
3216
3217 final long token = Binder.clearCallingIdentity();
3218 try {
3219 notifySettingChangeForRunningUsers(key, stringBuilder.toString());
3220 } finally {
3221 Binder.restoreCallingIdentity(token);
3222 }
3223
3224 // Always notify that our data changed
3225 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
3226 }
3227
Svet Ganov53a441c2016-04-19 19:38:00 -07003228 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003229 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003230 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003231 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003232 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003233 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003234 final int key = makeKey(type, profileId);
3235 // Increment the generation first, so observers always see the new value
3236 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003237 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003238 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003239 }
3240 }
3241 }
Svetoslav683914b2015-01-15 14:22:26 -08003242 }
3243
Linus Tufvesson93c38552019-05-30 12:47:39 +01003244 private void notifySettingChangeForRunningUsers(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003245 // Important: No need to update generation for each user as there
3246 // is a singleton generation entry for the global settings which
3247 // is already incremented be the caller.
3248 final Uri uri = getNotificationUriFor(key, name);
3249 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3250 for (int i = 0; i < users.size(); i++) {
3251 final int userId = users.get(i).id;
3252 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3253 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3254 userId, 0, uri).sendToTarget();
3255 }
3256 }
3257 }
3258
Makoto Onuki0000d322017-11-28 16:31:47 -08003259 private void notifyLocationChangeForRunningUsers() {
3260 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3261
3262 for (int i = 0; i < users.size(); i++) {
3263 final int userId = users.get(i).id;
3264
3265 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3266 continue;
3267 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003268
Svet Ganov945864c2018-03-22 21:49:10 -07003269 // Increment the generation first, so observers always see the new value
3270 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3271 mGenerationRegistry.incrementGeneration(key);
3272
Kweku Adams5e0052b2019-02-22 15:17:52 -08003273 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_MODE);
Makoto Onuki0000d322017-11-28 16:31:47 -08003274 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3275 userId, 0, uri).sendToTarget();
3276 }
3277 }
3278
Matt Pape1b31a332018-10-17 09:58:28 -07003279 private boolean isConfigSettingsKey(int key) {
3280 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3281 }
3282
Svetoslav683914b2015-01-15 14:22:26 -08003283 private boolean isGlobalSettingsKey(int key) {
3284 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3285 }
3286
3287 private boolean isSystemSettingsKey(int key) {
3288 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3289 }
3290
3291 private boolean isSecureSettingsKey(int key) {
3292 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3293 }
3294
Mark Rathjend891f012017-01-19 04:10:37 +00003295 private boolean isSsaidSettingsKey(int key) {
3296 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3297 }
3298
Bohdan Petrivskyy66acc132019-11-07 11:48:20 +00003299 private boolean shouldBan(int type) {
3300 if (SETTINGS_TYPE_CONFIG != type) {
3301 return false;
3302 }
3303 final int callingUid = Binder.getCallingUid();
3304 final int appId = UserHandle.getAppId(callingUid);
3305
3306 // Only non-shell resets should result in namespace banning
3307 return appId != SHELL_UID;
3308 }
3309
3310 private void banConfigurationIfNecessary(int type, @Nullable String prefix,
3311 SettingsState settingsState) {
3312 // Banning should be performed only for Settings.Config and for non-shell reset calls
3313 if (!shouldBan(type)) {
3314 return;
3315 }
3316 if (prefix != null) {
3317 settingsState.banConfigurationLocked(prefix, getAllConfigFlags(prefix));
3318 } else {
3319 Set<String> configPrefixes = settingsState.getAllConfigPrefixesLocked();
3320 for (String configPrefix : configPrefixes) {
3321 settingsState.banConfigurationLocked(configPrefix,
3322 getAllConfigFlags(configPrefix));
3323 }
3324 }
3325 }
3326
Svetoslav683914b2015-01-15 14:22:26 -08003327 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003328 if (isConfigSettingsKey(key)) {
3329 final int userId = getUserIdFromKey(key);
3330 return new File(Environment.getUserSystemDirectory(userId),
3331 SETTINGS_FILE_CONFIG);
3332 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003333 final int userId = getUserIdFromKey(key);
3334 return new File(Environment.getUserSystemDirectory(userId),
3335 SETTINGS_FILE_GLOBAL);
3336 } else if (isSystemSettingsKey(key)) {
3337 final int userId = getUserIdFromKey(key);
3338 return new File(Environment.getUserSystemDirectory(userId),
3339 SETTINGS_FILE_SYSTEM);
3340 } else if (isSecureSettingsKey(key)) {
3341 final int userId = getUserIdFromKey(key);
3342 return new File(Environment.getUserSystemDirectory(userId),
3343 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003344 } else if (isSsaidSettingsKey(key)) {
3345 final int userId = getUserIdFromKey(key);
3346 return new File(Environment.getUserSystemDirectory(userId),
3347 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003348 } else {
3349 throw new IllegalArgumentException("Invalid settings key:" + key);
3350 }
3351 }
3352
3353 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003354 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003355 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3356 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003357 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003358 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3359 : Settings.Global.CONTENT_URI;
3360 } else if (isSecureSettingsKey(key)) {
3361 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3362 : Settings.Secure.CONTENT_URI;
3363 } else if (isSystemSettingsKey(key)) {
3364 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3365 : Settings.System.CONTENT_URI;
3366 } else {
3367 throw new IllegalArgumentException("Invalid settings key:" + key);
3368 }
3369 }
3370
3371 private int getMaxBytesPerPackageForType(int type) {
3372 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003373 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003374 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003375 case SETTINGS_TYPE_SECURE:
3376 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003377 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3378 }
3379
3380 default: {
3381 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3382 }
3383 }
3384 }
3385
Svetoslav7e0683b2015-08-03 16:02:52 -07003386 private final class MyHandler extends Handler {
3387 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3388 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3389
3390 public MyHandler(Looper looper) {
3391 super(looper);
3392 }
3393
3394 @Override
3395 public void handleMessage(Message msg) {
3396 switch (msg.what) {
3397 case MSG_NOTIFY_URI_CHANGED: {
3398 final int userId = msg.arg1;
3399 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003400 try {
3401 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3402 } catch (SecurityException e) {
3403 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3404 }
Varun Shah2ecf7ad2019-10-16 12:30:57 -07003405 if (DEBUG) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003406 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3407 }
3408 } break;
3409
3410 case MSG_NOTIFY_DATA_CHANGED: {
3411 mBackupManager.dataChanged();
3412 } break;
3413 }
3414 }
3415 }
3416
Svetoslav683914b2015-01-15 14:22:26 -08003417 private final class UpgradeController {
Rhed Jao129d4192019-11-28 17:28:53 +08003418 private static final int SETTINGS_VERSION = 186;
Svetoslav683914b2015-01-15 14:22:26 -08003419
3420 private final int mUserId;
3421
3422 public UpgradeController(int userId) {
3423 mUserId = userId;
3424 }
3425
3426 public void upgradeIfNeededLocked() {
3427 // The version of all settings for a user is the same (all users have secure).
3428 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003429 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003430
3431 // Try an update from the current state.
3432 final int oldVersion = secureSettings.getVersionLocked();
3433 final int newVersion = SETTINGS_VERSION;
3434
Svet Ganovc9755bc2015-03-28 13:21:22 -07003435 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003436 if (oldVersion == newVersion) {
3437 return;
3438 }
3439
3440 // Try to upgrade.
3441 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3442
3443 // If upgrade failed start from scratch and upgrade.
3444 if (curVersion != newVersion) {
3445 // Drop state we have for this user.
3446 removeUserStateLocked(mUserId, true);
3447
3448 // Recreate the database.
3449 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3450 SQLiteDatabase database = dbHelper.getWritableDatabase();
3451 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3452
3453 // Migrate the settings for this user.
3454 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3455
3456 // Now upgrade should work fine.
3457 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003458
3459 // Make a note what happened, so we don't wonder why data was lost
3460 String reason = "Settings rebuilt! Current version: "
3461 + curVersion + " while expected: " + newVersion;
3462 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003463 Settings.Global.DATABASE_DOWNGRADE_REASON,
3464 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003465 }
3466
3467 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003468 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003469 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003470 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003471 globalSettings.setVersionLocked(newVersion);
3472 }
3473
3474 // Set the secure settings version.
3475 secureSettings.setVersionLocked(newVersion);
3476
3477 // Set the system settings version.
3478 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003479 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003480 systemSettings.setVersionLocked(newVersion);
3481 }
3482
3483 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003484 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003485 }
3486
3487 private SettingsState getSecureSettingsLocked(int userId) {
3488 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3489 }
3490
Mark Rathjend891f012017-01-19 04:10:37 +00003491 private SettingsState getSsaidSettingsLocked(int userId) {
3492 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3493 }
3494
Svetoslav683914b2015-01-15 14:22:26 -08003495 private SettingsState getSystemSettingsLocked(int userId) {
3496 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3497 }
3498
Jeff Brown503cffc2015-03-26 18:08:51 -07003499 /**
3500 * You must perform all necessary mutations to bring the settings
3501 * for this user from the old to the new version. When you add a new
3502 * upgrade step you *must* update SETTINGS_VERSION.
3503 *
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003504 * All settings modifications should be made through
3505 * {@link SettingsState#insertSettingOverrideableByRestoreLocked(String, String, String,
3506 * boolean, String)} so that restore can override those values if needed.
3507 *
Jeff Brown503cffc2015-03-26 18:08:51 -07003508 * This is an example of moving a setting from secure to global.
3509 *
3510 * // v119: Example settings changes.
3511 * if (currentVersion == 118) {
3512 * if (userId == UserHandle.USER_OWNER) {
3513 * // Remove from the secure settings.
3514 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3515 * String name = "example_setting_to_move";
3516 * String value = secureSettings.getSetting(name);
3517 * secureSettings.deleteSetting(name);
3518 *
3519 * // Add to the global settings.
3520 * SettingsState globalSettings = getGlobalSettingsLocked();
3521 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3522 * }
3523 *
3524 * // Update the current version.
3525 * currentVersion = 119;
3526 * }
3527 */
Svetoslav683914b2015-01-15 14:22:26 -08003528 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3529 if (DEBUG) {
3530 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3531 + oldVersion + " to version: " + newVersion);
3532 }
3533
Jeff Brown503cffc2015-03-26 18:08:51 -07003534 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003535
John Spurlocke11ae112015-05-11 16:09:03 -04003536 // v119: Reset zen + ringer mode.
3537 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003538 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003539 final SettingsState globalSettings = getGlobalSettingsLocked();
3540 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003541 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3542 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003543 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003544 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3545 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003546 }
3547 currentVersion = 119;
3548 }
3549
Jason Monk27bbb2d2015-03-31 16:46:39 -04003550 // v120: Add double tap to wake setting.
3551 if (currentVersion == 119) {
3552 SettingsState secureSettings = getSecureSettingsLocked(userId);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003553 secureSettings.insertSettingOverrideableByRestoreLocked(
3554 Settings.Secure.DOUBLE_TAP_TO_WAKE,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003555 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003556 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003557 SettingsState.SYSTEM_PACKAGE_NAME);
3558
3559 currentVersion = 120;
3560 }
3561
Svetoslav7e0683b2015-08-03 16:02:52 -07003562 if (currentVersion == 120) {
3563 // Before 121, we used a different string encoding logic. We just bump the
3564 // version here; SettingsState knows how to handle pre-version 120 files.
3565 currentVersion = 121;
3566 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003567
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003568 if (currentVersion == 121) {
3569 // Version 122: allow OEMs to set a default payment component in resources.
3570 // Note that we only write the default if no default has been set;
3571 // if there is, we just leave the default at whatever it currently is.
3572 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3573 String defaultComponent = (getContext().getResources().getString(
3574 R.string.def_nfc_payment_component));
3575 Setting currentSetting = secureSettings.getSettingLocked(
3576 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3577 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003578 currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003579 secureSettings.insertSettingOverrideableByRestoreLocked(
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003580 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003581 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003582 }
3583 currentVersion = 122;
3584 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003585
3586 if (currentVersion == 122) {
3587 // Version 123: Adding a default value for the ability to add a user from
3588 // the lock screen.
3589 if (userId == UserHandle.USER_SYSTEM) {
3590 final SettingsState globalSettings = getGlobalSettingsLocked();
3591 Setting currentSetting = globalSettings.getSettingLocked(
3592 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003593 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003594 globalSettings.insertSettingOverrideableByRestoreLocked(
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003595 Settings.Global.ADD_USERS_WHEN_LOCKED,
3596 getContext().getResources().getBoolean(
3597 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003598 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003599 }
3600 }
3601 currentVersion = 123;
3602 }
Bryce Leebd179282015-12-17 19:01:37 -08003603
3604 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003605 final SettingsState globalSettings = getGlobalSettingsLocked();
3606 String defaultDisabledProfiles = (getContext().getResources().getString(
3607 R.string.def_bluetooth_disabled_profiles));
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003608 globalSettings.insertSettingOverrideableByRestoreLocked(
3609 Settings.Global.BLUETOOTH_DISABLED_PROFILES, defaultDisabledProfiles,
3610 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003611 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003612 }
3613
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003614 if (currentVersion == 124) {
3615 // Version 124: allow OEMs to set a default value for whether IME should be
3616 // shown when a physical keyboard is connected.
3617 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3618 Setting currentSetting = secureSettings.getSettingLocked(
3619 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003620 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003621 secureSettings.insertSettingOverrideableByRestoreLocked(
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003622 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3623 getContext().getResources().getBoolean(
3624 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003625 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003626 }
3627 currentVersion = 125;
3628 }
3629
Ruben Brunk98576cf2016-03-07 18:54:28 -08003630 if (currentVersion == 125) {
3631 // Version 125: Allow OEMs to set the default VR service.
3632 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3633
3634 Setting currentSetting = secureSettings.getSettingLocked(
3635 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003636 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003637 ArraySet<ComponentName> l =
3638 SystemConfig.getInstance().getDefaultVrComponents();
3639
3640 if (l != null && !l.isEmpty()) {
3641 StringBuilder b = new StringBuilder();
3642 boolean start = true;
3643 for (ComponentName c : l) {
3644 if (!start) {
3645 b.append(':');
3646 }
3647 b.append(c.flattenToString());
3648 start = false;
3649 }
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003650 secureSettings.insertSettingOverrideableByRestoreLocked(
Ruben Brunk98576cf2016-03-07 18:54:28 -08003651 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003652 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003653 }
3654
3655 }
3656 currentVersion = 126;
3657 }
3658
Daniel U02ba6122016-04-01 18:41:42 +01003659 if (currentVersion == 126) {
3660 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3661 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3662 if (mUserManager.isManagedProfile(userId)) {
3663 final SettingsState systemSecureSettings =
3664 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3665
3666 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3667 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003668 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003669 final SettingsState secureSettings = getSecureSettingsLocked(userId);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003670 secureSettings.insertSettingOverrideableByRestoreLocked(
Daniel U02ba6122016-04-01 18:41:42 +01003671 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003672 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003673 SettingsState.SYSTEM_PACKAGE_NAME);
3674 }
3675
3676 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3677 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003678 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003679 final SettingsState secureSettings = getSecureSettingsLocked(userId);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003680 secureSettings.insertSettingOverrideableByRestoreLocked(
Daniel U02ba6122016-04-01 18:41:42 +01003681 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003682 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003683 SettingsState.SYSTEM_PACKAGE_NAME);
3684 }
3685 }
3686 currentVersion = 127;
3687 }
3688
Steven Ngdc20ba62016-04-26 18:19:04 +01003689 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003690 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003691 currentVersion = 128;
3692 }
3693
Julia Reynolds1f721e12016-07-11 08:50:58 -04003694 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003695 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003696 currentVersion = 129;
3697 }
3698
Dan Sandler71f85e92016-07-20 13:46:05 -04003699 if (currentVersion == 129) {
3700 // default longpress timeout changed from 500 to 400. If unchanged from the old
3701 // default, update to the new default.
3702 final SettingsState systemSecureSettings =
3703 getSecureSettingsLocked(userId);
3704 final String oldValue = systemSecureSettings.getSettingLocked(
3705 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3706 if (TextUtils.equals("500", oldValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003707 systemSecureSettings.insertSettingOverrideableByRestoreLocked(
Dan Sandler71f85e92016-07-20 13:46:05 -04003708 Settings.Secure.LONG_PRESS_TIMEOUT,
3709 String.valueOf(getContext().getResources().getInteger(
3710 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003711 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003712 }
3713 currentVersion = 130;
3714 }
3715
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003716 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003717 // Split Ambient settings
3718 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3719 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3720 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3721
3722 if (dozeExplicitlyDisabled) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003723 secureSettings.insertSettingOverrideableByRestoreLocked(
3724 Settings.Secure.DOZE_PICK_UP_GESTURE, "0", null, true,
3725 SettingsState.SYSTEM_PACKAGE_NAME);
3726 secureSettings.insertSettingOverrideableByRestoreLocked(
3727 Settings.Secure.DOZE_DOUBLE_TAP_GESTURE, "0", null, true,
3728 SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003729 }
3730 currentVersion = 131;
3731 }
3732
3733 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003734 // Initialize new multi-press timeout to default value
3735 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3736 final String oldValue = systemSecureSettings.getSettingLocked(
3737 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3738 if (TextUtils.equals(null, oldValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003739 systemSecureSettings.insertSettingOverrideableByRestoreLocked(
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003740 Settings.Secure.MULTI_PRESS_TIMEOUT,
3741 String.valueOf(getContext().getResources().getInteger(
3742 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003743 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003744 }
3745
Adrian Roos69741a22016-10-21 14:49:17 -07003746 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003747 }
3748
Adrian Roos69741a22016-10-21 14:49:17 -07003749 if (currentVersion == 132) {
3750 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003751 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3752 String defaultSyncParentSounds = (getContext().getResources()
3753 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003754 systemSecureSettings.insertSettingOverrideableByRestoreLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003755 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3756 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003757 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003758 }
3759
Adrian Roos69741a22016-10-21 14:49:17 -07003760 if (currentVersion == 133) {
3761 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003762 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003763 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3764 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003765 String defaultEndButtonBehavior = Integer.toString(getContext()
3766 .getResources().getInteger(R.integer.def_end_button_behavior));
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003767 systemSettings.insertSettingOverrideableByRestoreLocked(
3768 Settings.System.END_BUTTON_BEHAVIOR, defaultEndButtonBehavior, null,
3769 true, SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003770 }
Adrian Roos69741a22016-10-21 14:49:17 -07003771 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003772 }
3773
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003774 if (currentVersion == 134) {
3775 // Remove setting that specifies if magnification values should be preserved.
3776 // This setting defaulted to true and never has a UI.
3777 getSecureSettingsLocked(userId).deleteSettingLocked(
3778 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3779 currentVersion = 135;
3780 }
3781
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003782 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003783 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003784 currentVersion = 136;
3785 }
3786
Mark Rathjend891f012017-01-19 04:10:37 +00003787 if (currentVersion == 136) {
3788 // Version 136: Store legacy SSAID for all apps currently installed on the
3789 // device as first step in migrating SSAID to be unique per application.
3790
3791 final boolean isUpgrade;
3792 try {
Svet Ganovd8eb8b22019-04-05 18:52:08 -07003793 isUpgrade = mPackageManager.isDeviceUpgrading();
Mark Rathjend891f012017-01-19 04:10:37 +00003794 } catch (RemoteException e) {
3795 throw new IllegalStateException("Package manager not available");
3796 }
3797 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3798 // user data or first boot on a new device should use new ssaid generation.
3799 if (isUpgrade) {
3800 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003801 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3802 userId, Settings.Secure.ANDROID_ID);
3803 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3804 || legacySsaidSetting.getValue() == null) {
3805 throw new IllegalStateException("Legacy ssaid not accessible");
3806 }
3807 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003808
3809 // Fill each uid with the legacy ssaid to be backwards compatible.
3810 final List<PackageInfo> packages;
3811 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003812 packages = mPackageManager.getInstalledPackages(
3813 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3814 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003815 } catch (RemoteException e) {
3816 throw new IllegalStateException("Package manager not available");
3817 }
3818
3819 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3820 for (PackageInfo info : packages) {
3821 // Check if the UID already has an entry in the table.
3822 final String uid = Integer.toString(info.applicationInfo.uid);
3823 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3824
3825 if (ssaid.isNull() || ssaid.getValue() == null) {
3826 // Android Id doesn't exist for this package so create it.
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003827 ssaidSettings.insertSettingOverrideableByRestoreLocked(uid,
3828 legacySsaid, null, true, info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003829 if (DEBUG) {
3830 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3831 }
Mark Rathjend891f012017-01-19 04:10:37 +00003832 }
3833 }
3834 }
3835
3836 currentVersion = 137;
3837 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003838 if (currentVersion == 137) {
3839 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3840 // default value set to 1. The user can no longer change the value of this
3841 // setting through the UI.
3842 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3843 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003844 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3845 && secureSetting.getSettingLocked(
3846 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3847
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003848 secureSetting.insertSettingOverrideableByRestoreLocked(
3849 Settings.Secure.INSTALL_NON_MARKET_APPS, "1", null, true,
3850 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003851 // For managed profiles with profile owners, DevicePolicyManagerService
3852 // may want to set the user restriction in this case
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003853 secureSetting.insertSettingOverrideableByRestoreLocked(
3854 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null,
3855 true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003856 }
3857 currentVersion = 138;
3858 }
Mark Rathjend891f012017-01-19 04:10:37 +00003859
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003860 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003861 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003862 currentVersion = 139;
3863 }
3864
Phil Weaver385912e2017-02-10 10:06:56 -08003865 if (currentVersion == 139) {
3866 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3867 // the user can no longer change the value of this setting through the UI.
3868 // Force to true.
3869 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3870 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3871 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3872 currentVersion = 140;
3873 }
3874
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003875 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003876 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003877 currentVersion = 141;
3878 }
3879
Svet Ganov13701552017-02-23 12:45:17 -08003880 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003881 // This implementation was incorrectly setting the current value of
3882 // settings changed by non-system packages as the default which default
3883 // is set by the system. We add a new upgrade step at the end to properly
3884 // handle this case which would also fix incorrect changes made by the
3885 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003886 currentVersion = 142;
3887 }
3888
Stephen Chen5d0922f2017-03-27 10:28:04 -07003889 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003890 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003891 if (userId == UserHandle.USER_SYSTEM) {
3892 final SettingsState globalSettings = getGlobalSettingsLocked();
3893 Setting currentSetting = globalSettings.getSettingLocked(
3894 Settings.Global.WIFI_WAKEUP_ENABLED);
3895 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003896 globalSettings.insertSettingOverrideableByRestoreLocked(
Stephen Chen5d0922f2017-03-27 10:28:04 -07003897 Settings.Global.WIFI_WAKEUP_ENABLED,
3898 getContext().getResources().getBoolean(
3899 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3900 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3901 }
3902 }
3903
3904 currentVersion = 143;
3905 }
3906
Felipe Lemeff355092017-04-03 12:55:02 -07003907 if (currentVersion == 143) {
3908 // Version 144: Set a default value for Autofill service.
3909 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3910 final Setting currentSetting = secureSettings
3911 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3912 if (currentSetting.isNull()) {
3913 final String defaultValue = getContext().getResources().getString(
3914 com.android.internal.R.string.config_defaultAutofillService);
3915 if (defaultValue != null) {
3916 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3917 + "for user " + userId);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003918 secureSettings.insertSettingOverrideableByRestoreLocked(
3919 Settings.Secure.AUTOFILL_SERVICE, defaultValue, null, true,
3920 SettingsState.SYSTEM_PACKAGE_NAME);
Felipe Lemeff355092017-04-03 12:55:02 -07003921 }
3922 }
3923
3924 currentVersion = 144;
3925 }
3926
Jeremy Joslin45caa252017-05-04 11:22:46 -07003927 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003928 // Version 145: Removed
3929 currentVersion = 145;
3930 }
3931
3932 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003933 // Version 146: In step 142 we had a bug where incorrectly
3934 // some settings were considered system set and as a result
3935 // made the default and marked as the default being set by
3936 // the system. Here reevaluate the default and default system
3937 // set flags. This would both fix corruption by the old impl
3938 // of step 142 and also properly handle devices which never
3939 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003940 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003941 SettingsState globalSettings = getGlobalSettingsLocked();
3942 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3943 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003944 }
3945
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003946 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3947 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3948 secureSettings.persistSyncLocked();
3949
3950 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3951 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3952 systemSettings.persistSyncLocked();
3953
Amin Shaikh86367962017-06-07 08:58:22 -07003954 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003955 }
3956
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003957 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003958 // Version 147: Removed. (This version previously allowed showing the
3959 // "wifi_wakeup_available" setting).
3960 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003961 currentVersion = 147;
3962 }
3963
3964 if (currentVersion == 147) {
3965 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003966 if (userId == UserHandle.USER_SYSTEM) {
3967 final SettingsState globalSettings = getGlobalSettingsLocked();
3968 final Setting currentSetting = globalSettings.getSettingLocked(
3969 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3970 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003971 globalSettings.insertSettingOverrideableByRestoreLocked(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003972 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3973 getContext().getResources().getBoolean(
3974 R.bool.def_restrict_background_data) ? "1" : "0",
3975 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3976 }
3977 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003978 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003979 }
3980
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003981 if (currentVersion == 148) {
3982 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3983 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3984 final String oldValue = systemSecureSettings.getSettingLocked(
3985 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3986 if (TextUtils.equals(null, oldValue)) {
3987 final String defaultValue = getContext().getResources().getString(
3988 R.string.def_backup_manager_constants);
3989 if (!TextUtils.isEmpty(defaultValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00003990 systemSecureSettings.insertSettingOverrideableByRestoreLocked(
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003991 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3992 true, SettingsState.SYSTEM_PACKAGE_NAME);
3993 }
3994 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003995 currentVersion = 149;
3996 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003997
3998 if (currentVersion == 149) {
3999 // Version 150: Set a default value for mobile data always on
4000 final SettingsState globalSettings = getGlobalSettingsLocked();
4001 final Setting currentSetting = globalSettings.getSettingLocked(
4002 Settings.Global.MOBILE_DATA_ALWAYS_ON);
4003 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004004 globalSettings.insertSettingOverrideableByRestoreLocked(
Jacky Cheung7076a312017-10-02 10:40:48 -07004005 Settings.Global.MOBILE_DATA_ALWAYS_ON,
4006 getContext().getResources().getBoolean(
4007 R.bool.def_mobile_data_always_on) ? "1" : "0",
4008 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4009 }
4010
4011 currentVersion = 150;
4012 }
4013
Mike Digman4af4a6f2018-01-16 14:49:38 -08004014 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07004015 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08004016 currentVersion = 151;
4017 }
4018
Joe LaPenna4f50ed42018-01-22 14:54:45 -08004019 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08004020 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
4021 // by default but it is now no longer configurable).
4022 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08004023 currentVersion = 152;
4024 }
4025
Joe LaPenna250d7842018-01-25 10:19:42 -08004026 if (currentVersion == 152) {
4027 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
4028 currentVersion = 153;
4029 }
4030
Ben Linb4df8bc2018-01-29 11:48:20 -08004031 if (currentVersion == 153) {
4032 // Version 154: Read notification badge configuration from config.
4033 // If user has already set the value, don't do anything.
4034 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
4035 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
4036 Settings.Secure.NOTIFICATION_BADGING);
4037 if (showNotificationBadges.isNull()) {
4038 final boolean defaultValue = getContext().getResources().getBoolean(
4039 com.android.internal.R.bool.config_notificationBadging);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004040 systemSecureSettings.insertSettingOverrideableByRestoreLocked(
Ben Linb4df8bc2018-01-29 11:48:20 -08004041 Secure.NOTIFICATION_BADGING,
4042 defaultValue ? "1" : "0",
4043 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4044 }
4045 currentVersion = 154;
4046 }
4047
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00004048 if (currentVersion == 154) {
4049 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
4050 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
4051 final String oldValue = systemSecureSettings.getSettingLocked(
4052 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
4053 if (TextUtils.equals(null, oldValue)) {
4054 final String defaultValue = getContext().getResources().getString(
4055 R.string.def_backup_local_transport_parameters);
4056 if (!TextUtils.isEmpty(defaultValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004057 systemSecureSettings.insertSettingOverrideableByRestoreLocked(
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00004058 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
4059 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4060 }
4061
4062 }
4063 currentVersion = 155;
4064 }
4065
Beverlyda904812018-03-02 09:55:30 -05004066 if (currentVersion == 155) {
Beverlyf364d7c2019-10-10 16:44:43 -04004067 // Version 156: migrated to version 184
Beverlyda904812018-03-02 09:55:30 -05004068 currentVersion = 156;
4069 }
4070
Beverly09da25f2018-02-26 09:17:07 -05004071 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04004072 // Version 157: Set a default value for zen duration,
4073 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05004074 final SettingsState globalSettings = getGlobalSettingsLocked();
4075 final Setting currentSetting = globalSettings.getSettingLocked(
4076 Global.ZEN_DURATION);
4077 if (currentSetting.isNull()) {
4078 String defaultZenDuration = Integer.toString(getContext()
4079 .getResources().getInteger(R.integer.def_zen_duration));
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004080 globalSettings.insertSettingOverrideableByRestoreLocked(
Beverly09da25f2018-02-26 09:17:07 -05004081 Global.ZEN_DURATION, defaultZenDuration,
4082 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4083 }
Beverly09da25f2018-02-26 09:17:07 -05004084 currentVersion = 157;
4085 }
Annie Mengd069a882018-03-13 15:31:40 +00004086
4087 if (currentVersion == 157) {
4088 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
4089 final SettingsState globalSettings = getGlobalSettingsLocked();
4090 final String oldValue = globalSettings.getSettingLocked(
4091 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
4092 if (TextUtils.equals(null, oldValue)) {
4093 final String defaultValue = getContext().getResources().getString(
4094 R.string.def_backup_agent_timeout_parameters);
4095 if (!TextUtils.isEmpty(defaultValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004096 globalSettings.insertSettingOverrideableByRestoreLocked(
Annie Mengd069a882018-03-13 15:31:40 +00004097 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
4098 null, true,
4099 SettingsState.SYSTEM_PACKAGE_NAME);
4100 }
4101 }
4102 currentVersion = 158;
4103 }
Roshan Pius9c396672018-03-02 14:54:13 -08004104
4105 if (currentVersion == 158) {
4106 // Remove setting that specifies wifi bgscan throttling params
4107 getGlobalSettingsLocked().deleteSettingLocked(
4108 "wifi_scan_background_throttle_interval_ms");
4109 getGlobalSettingsLocked().deleteSettingLocked(
4110 "wifi_scan_background_throttle_package_whitelist");
4111 currentVersion = 159;
4112 }
4113
Pavel Grafovc5c97302018-03-19 13:37:15 +00004114 if (currentVersion == 159) {
4115 // Version 160: Hiding notifications from the lockscreen is only available as
4116 // primary user option, profiles can only make them redacted. If a profile was
4117 // configured to not show lockscreen notifications, ensure that at the very
4118 // least these will be come hidden.
4119 if (mUserManager.isManagedProfile(userId)) {
4120 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4121 Setting showNotifications = secureSettings.getSettingLocked(
4122 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
4123 // The default value is "1", check if user has turned it off.
4124 if ("0".equals(showNotifications.getValue())) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004125 secureSettings.insertSettingOverrideableByRestoreLocked(
Pavel Grafovc5c97302018-03-19 13:37:15 +00004126 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
4127 null /* tag */, false /* makeDefault */,
4128 SettingsState.SYSTEM_PACKAGE_NAME);
4129 }
4130 // The setting is no longer valid for managed profiles, it should be
4131 // treated as if it was set to "1".
4132 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
4133 }
4134 currentVersion = 160;
4135 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08004136
4137 if (currentVersion == 160) {
4138 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08004139 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08004140 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
4141 final SettingsState globalSettings = getGlobalSettingsLocked();
4142
4143 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08004144 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
4145 if (TextUtils.equals(null, oldValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004146 globalSettings.insertSettingOverrideableByRestoreLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08004147 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
4148 Integer.toString(getContext().getResources().getInteger(
4149 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
4150 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4151 }
4152
4153 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08004154 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
4155 if (TextUtils.equals(null, oldValue)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004156 globalSettings.insertSettingOverrideableByRestoreLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08004157 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
4158 Integer.toString(getContext().getResources().getInteger(
4159 R.integer.def_sound_trigger_detection_service_op_timeout)),
4160 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4161 }
4162 currentVersion = 161;
4163 }
4164
Mike Digman55272862018-02-20 14:35:17 -08004165 if (currentVersion == 161) {
4166 // Version 161: Add a gesture for silencing phones
4167 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4168 final Setting currentSetting = secureSettings.getSettingLocked(
4169 Secure.VOLUME_HUSH_GESTURE);
4170 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004171 secureSettings.insertSettingOverrideableByRestoreLocked(
Mike Digman55272862018-02-20 14:35:17 -08004172 Secure.VOLUME_HUSH_GESTURE,
4173 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
4174 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4175 }
4176
4177 currentVersion = 162;
4178 }
4179
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04004180 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04004181 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04004182 currentVersion = 163;
4183 }
4184
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07004185 if (currentVersion == 163) {
4186 // Version 163: Update default value of
4187 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
4188 final SettingsState settings = getGlobalSettingsLocked();
4189 final Setting currentSetting = settings.getSettingLocked(
4190 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
4191 if (currentSetting.isDefaultFromSystem()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004192 settings.insertSettingOverrideableByRestoreLocked(
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07004193 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
4194 Integer.toString(getContext().getResources().getInteger(
4195 R.integer
4196 .def_max_sound_trigger_detection_service_ops_per_day)),
4197 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4198 }
4199
4200 currentVersion = 164;
4201 }
4202
Julia Reynolds76bfa602018-04-23 09:38:47 -04004203 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004204 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004205 currentVersion = 165;
4206 }
4207
Beverly301e92a2018-04-27 09:43:05 -04004208 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004209 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4210 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004211 currentVersion = 166;
4212 }
4213
Beverly38fcfd02018-05-18 17:33:40 -04004214 if (currentVersion == 166) {
4215 // Version 166: add default values for hush gesture used and manual ringer
4216 // toggle
4217 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4218 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4219 Secure.HUSH_GESTURE_USED);
4220 if (currentHushUsedSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004221 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly38fcfd02018-05-18 17:33:40 -04004222 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4223 SettingsState.SYSTEM_PACKAGE_NAME);
4224 }
4225
4226 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4227 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4228 if (currentRingerToggleCountSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004229 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly38fcfd02018-05-18 17:33:40 -04004230 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4231 SettingsState.SYSTEM_PACKAGE_NAME);
4232 }
4233 currentVersion = 167;
4234 }
4235
Beverly155c9d22018-05-23 18:03:23 -04004236 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004237 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4238 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004239 currentVersion = 168;
4240 }
4241
Michael Wright0e9eeee2018-05-26 00:31:20 +01004242 if (currentVersion == 168) {
4243 // Version 168: by default, vibrate for phone calls
4244 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4245 final Setting currentSetting = systemSettings.getSettingLocked(
4246 Settings.System.VIBRATE_WHEN_RINGING);
4247 if (currentSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004248 systemSettings.insertSettingOverrideableByRestoreLocked(
Michael Wright0e9eeee2018-05-26 00:31:20 +01004249 Settings.System.VIBRATE_WHEN_RINGING,
4250 getContext().getResources().getBoolean(
4251 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4252 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4253 }
4254 currentVersion = 169;
4255 }
4256
Nadav Barf9f115d2018-06-24 10:06:50 +03004257 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004258 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4259 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4260 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004261
Beverly91d0a632018-07-02 16:45:00 -04004262 final SettingsState globalSettings = getGlobalSettingsLocked();
4263 final Setting globalZenDuration = globalSettings.getSettingLocked(
4264 Global.ZEN_DURATION);
4265
4266 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4267 final Setting secureZenDuration = secureSettings.getSettingLocked(
4268 Secure.ZEN_DURATION);
4269
4270 // ZEN_DURATION
4271 if (!globalZenDuration.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004272 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004273 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4274 SettingsState.SYSTEM_PACKAGE_NAME);
4275
4276 // set global zen duration setting to null since it's deprecated
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004277 globalSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004278 Global.ZEN_DURATION, null, null, true,
4279 SettingsState.SYSTEM_PACKAGE_NAME);
4280 } else if (secureZenDuration.isNull()) {
4281 String defaultZenDuration = Integer.toString(getContext()
4282 .getResources().getInteger(R.integer.def_zen_duration));
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004283 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004284 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4285 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004286 }
Beverly91d0a632018-07-02 16:45:00 -04004287
4288 // SHOW_ZEN_SETTINGS_SUGGESTION
4289 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4290 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4291 if (currentShowZenSettingSuggestion.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004292 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004293 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4294 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4295 }
4296
4297 // ZEN_SETTINGS_UPDATED
4298 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4299 Secure.ZEN_SETTINGS_UPDATED);
4300 if (currentUpdatedSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004301 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004302 Secure.ZEN_SETTINGS_UPDATED, "0",
4303 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4304 }
4305
4306 // ZEN_SETTINGS_SUGGESTION_VIEWED
4307 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4308 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4309 if (currentSettingSuggestionViewed.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004310 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004311 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4312 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4313 }
4314
Nadav Barf9f115d2018-06-24 10:06:50 +03004315 currentVersion = 170;
4316 }
4317
Beverly91d0a632018-07-02 16:45:00 -04004318 if (currentVersion == 170) {
4319 // Version 170: Set the default value for Secure Settings:
4320 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4321
4322 final SettingsState globalSettings = getGlobalSettingsLocked();
4323 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4324
4325 // CHARGING_SOUNDS_ENABLED
4326 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4327 Global.CHARGING_SOUNDS_ENABLED);
4328 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4329 Secure.CHARGING_SOUNDS_ENABLED);
4330
4331 if (!globalChargingSoundEnabled.isNull()) {
Beverlyff9c5872019-01-02 15:44:00 -05004332 if (secureChargingSoundsEnabled.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004333 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverlyff9c5872019-01-02 15:44:00 -05004334 Secure.CHARGING_SOUNDS_ENABLED,
4335 globalChargingSoundEnabled.getValue(), null, false,
4336 SettingsState.SYSTEM_PACKAGE_NAME);
4337 }
Beverly91d0a632018-07-02 16:45:00 -04004338
4339 // set global charging_sounds_enabled setting to null since it's deprecated
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004340 globalSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004341 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4342 SettingsState.SYSTEM_PACKAGE_NAME);
4343 } else if (secureChargingSoundsEnabled.isNull()) {
4344 String defChargingSoundsEnabled = getContext().getResources()
4345 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004346 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004347 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4348 true, SettingsState.SYSTEM_PACKAGE_NAME);
4349 }
4350
4351 // CHARGING_VIBRATION_ENABLED
4352 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4353 Secure.CHARGING_VIBRATION_ENABLED);
4354
4355 if (secureChargingVibrationEnabled.isNull()) {
4356 String defChargingVibrationEnabled = getContext().getResources()
4357 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004358 secureSettings.insertSettingOverrideableByRestoreLocked(
Beverly91d0a632018-07-02 16:45:00 -04004359 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4360 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4361 }
4362
4363 currentVersion = 171;
4364 }
4365
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004366 if (currentVersion == 171) {
4367 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4368 // be muted.
4369 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4370 final Setting currentSetting = systemSettings.getSettingLocked(
4371 Settings.System.MUTE_STREAMS_AFFECTED);
4372 if (!currentSetting.isNull()) {
4373 try {
4374 int currentSettingIntegerValue = Integer.parseInt(
4375 currentSetting.getValue());
4376 if ((currentSettingIntegerValue
4377 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004378 systemSettings.insertSettingOverrideableByRestoreLocked(
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004379 Settings.System.MUTE_STREAMS_AFFECTED,
4380 Integer.toString(
4381 currentSettingIntegerValue
4382 | (1 << AudioManager.STREAM_VOICE_CALL)),
4383 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4384 }
4385 } catch (NumberFormatException e) {
4386 // remove the setting in case it is not a valid integer
4387 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4388 + "setting, removing setting", e);
4389 systemSettings.deleteSettingLocked(
4390 Settings.System.MUTE_STREAMS_AFFECTED);
4391 }
4392
4393 }
4394 currentVersion = 172;
4395 }
4396
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004397 if (currentVersion == 172) {
4398 // Version 172: Set the default value for Secure Settings: LOCATION_MODE
4399
4400 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4401
4402 final Setting locationMode = secureSettings.getSettingLocked(
4403 Secure.LOCATION_MODE);
4404
4405 if (locationMode.isNull()) {
4406 final Setting locationProvidersAllowed = secureSettings.getSettingLocked(
4407 Secure.LOCATION_PROVIDERS_ALLOWED);
4408
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004409 final int defLocationMode;
4410 if (locationProvidersAllowed.isNull()) {
4411 defLocationMode = getContext().getResources().getInteger(
4412 R.integer.def_location_mode);
4413 } else {
4414 defLocationMode =
4415 !TextUtils.isEmpty(locationProvidersAllowed.getValue())
4416 ? Secure.LOCATION_MODE_ON
4417 : Secure.LOCATION_MODE_OFF;
4418 }
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004419 secureSettings.insertSettingOverrideableByRestoreLocked(
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004420 Secure.LOCATION_MODE, Integer.toString(defLocationMode),
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004421 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4422 }
4423
4424 currentVersion = 173;
4425 }
4426
Beverly4179f992019-02-08 11:34:16 -05004427 if (currentVersion == 173) {
4428 // Version 173: Set the default value for Secure Settings: NOTIFICATION_BUBBLES
Lyn Hanb739fa62019-06-27 18:41:11 -07004429 // Removed. Moved NOTIFICATION_BUBBLES to Global Settings.
Beverly4179f992019-02-08 11:34:16 -05004430 currentVersion = 174;
4431 }
4432
Yiwen Chen0305b572019-03-05 11:26:59 -08004433 if (currentVersion == 174) {
4434 // Version 174: Set the default value for Global Settings: APPLY_RAMPING_RINGER
4435
4436 final SettingsState globalSettings = getGlobalSettingsLocked();
4437
4438 Setting currentRampingRingerSetting = globalSettings.getSettingLocked(
4439 Settings.Global.APPLY_RAMPING_RINGER);
4440 if (currentRampingRingerSetting.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004441 globalSettings.insertSettingOverrideableByRestoreLocked(
Yiwen Chen0305b572019-03-05 11:26:59 -08004442 Settings.Global.APPLY_RAMPING_RINGER,
4443 getContext().getResources().getBoolean(
4444 R.bool.def_apply_ramping_ringer) ? "1" : "0", null,
4445 true, SettingsState.SYSTEM_PACKAGE_NAME);
4446 }
4447
4448 currentVersion = 175;
4449 }
4450
wilsonshih5d999e22019-03-20 11:50:42 +08004451 if (currentVersion == 175) {
4452 // Version 175: Set the default value for System Settings:
4453 // RING_VIBRATION_INTENSITY. If the notification vibration intensity has been
4454 // set and ring vibration intensity hasn't, the ring vibration intensity should
4455 // followed notification vibration intensity.
4456
4457 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4458
4459 Setting notificationVibrationIntensity = systemSettings.getSettingLocked(
4460 Settings.System.NOTIFICATION_VIBRATION_INTENSITY);
4461
4462 Setting ringVibrationIntensity = systemSettings.getSettingLocked(
4463 Settings.System.RING_VIBRATION_INTENSITY);
4464
4465 if (!notificationVibrationIntensity.isNull()
4466 && ringVibrationIntensity.isNull()) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004467 systemSettings.insertSettingOverrideableByRestoreLocked(
wilsonshih5d999e22019-03-20 11:50:42 +08004468 Settings.System.RING_VIBRATION_INTENSITY,
4469 notificationVibrationIntensity.getValue(),
4470 null , true, SettingsState.SYSTEM_PACKAGE_NAME);
4471 }
4472
4473 currentVersion = 176;
4474 }
4475
Winson Chungd9f2fb32019-03-05 11:10:12 -08004476 if (currentVersion == 176) {
4477 // Version 176: Migrate the existing swipe up setting into the resource overlay
Winson Chung3d5d3b32019-04-24 16:52:47 -07004478 // for the navigation bar interaction mode. We do so only if the
4479 // setting is set.
Winson Chungd9f2fb32019-03-05 11:10:12 -08004480
Winson Chungd9f2fb32019-03-05 11:10:12 -08004481 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4482 final Setting swipeUpSetting = secureSettings.getSettingLocked(
Winson Chung85e74592019-03-06 11:49:22 -08004483 "swipe_up_to_switch_apps_enabled");
Winson Chung3d5d3b32019-04-24 16:52:47 -07004484 if (swipeUpSetting != null && !swipeUpSetting.isNull()
4485 && swipeUpSetting.getValue().equals("1")) {
4486 final IOverlayManager overlayManager = IOverlayManager.Stub.asInterface(
4487 ServiceManager.getService(Context.OVERLAY_SERVICE));
Winson Chungd9f2fb32019-03-05 11:10:12 -08004488 try {
Winson Chung3d5d3b32019-04-24 16:52:47 -07004489 overlayManager.setEnabledExclusiveInCategory(
4490 NAV_BAR_MODE_2BUTTON_OVERLAY, UserHandle.USER_CURRENT);
Winson792a0aa2020-01-15 17:16:14 -08004491 } catch (SecurityException | IllegalStateException | RemoteException e) {
Winson Chungd9f2fb32019-03-05 11:10:12 -08004492 throw new IllegalStateException(
4493 "Failed to set nav bar interaction mode overlay");
4494 }
4495 }
4496
4497 currentVersion = 177;
4498 }
4499
Edgar Wangeb8bddb2019-04-19 17:29:49 +08004500 if (currentVersion == 177) {
4501 // Version 177: Set the default value for Secure Settings: AWARE_ENABLED
4502
4503 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4504
4505 final Setting awareEnabled = secureSettings.getSettingLocked(
4506 Secure.AWARE_ENABLED);
4507
4508 if (awareEnabled.isNull()) {
4509 final boolean defAwareEnabled = getContext().getResources().getBoolean(
4510 R.bool.def_aware_enabled);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004511 secureSettings.insertSettingOverrideableByRestoreLocked(
Edgar Wangeb8bddb2019-04-19 17:29:49 +08004512 Secure.AWARE_ENABLED, defAwareEnabled ? "1" : "0",
4513 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4514 }
4515
4516 currentVersion = 178;
4517 }
4518
Edgar Wangdabc41e2019-05-07 18:53:31 +08004519 if (currentVersion == 178) {
4520 // Version 178: Set the default value for Secure Settings:
4521 // SKIP_GESTURE & SILENCE_GESTURE
4522
4523 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4524
4525 final Setting skipGesture = secureSettings.getSettingLocked(
4526 Secure.SKIP_GESTURE);
4527
4528 if (skipGesture.isNull()) {
4529 final boolean defSkipGesture = getContext().getResources().getBoolean(
4530 R.bool.def_skip_gesture);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004531 secureSettings.insertSettingOverrideableByRestoreLocked(
Edgar Wangdabc41e2019-05-07 18:53:31 +08004532 Secure.SKIP_GESTURE, defSkipGesture ? "1" : "0",
4533 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4534 }
4535
4536 final Setting silenceGesture = secureSettings.getSettingLocked(
4537 Secure.SILENCE_GESTURE);
4538
4539 if (silenceGesture.isNull()) {
4540 final boolean defSilenceGesture = getContext().getResources().getBoolean(
4541 R.bool.def_silence_gesture);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004542 secureSettings.insertSettingOverrideableByRestoreLocked(
Edgar Wangdabc41e2019-05-07 18:53:31 +08004543 Secure.SILENCE_GESTURE, defSilenceGesture ? "1" : "0",
4544 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4545 }
4546
4547 currentVersion = 179;
4548 }
4549
Mady Mellor95e879a2019-05-06 08:50:06 -07004550 if (currentVersion == 179) {
4551 // Version 178: Reset the default for Secure Settings: NOTIFICATION_BUBBLES
4552 // This is originally set in version 173, however, the default value changed
Lyn Hanb739fa62019-06-27 18:41:11 -07004553 // so this step is to ensure the value is updated to the correct default.
Mady Mellor95e879a2019-05-06 08:50:06 -07004554
Lyn Hanb739fa62019-06-27 18:41:11 -07004555 // Removed. Moved NOTIFICATION_BUBBLES to Global Settings.
Mady Mellor95e879a2019-05-06 08:50:06 -07004556 currentVersion = 180;
4557 }
Winson Chungd9f2fb32019-03-05 11:10:12 -08004558
Edgar Wang4870e4b2019-05-15 19:14:43 +08004559 if (currentVersion == 180) {
4560 // Version 180: Set the default value for Secure Settings: AWARE_LOCK_ENABLED
4561
4562 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4563
4564 final Setting awareLockEnabled = secureSettings.getSettingLocked(
4565 Secure.AWARE_LOCK_ENABLED);
4566
4567 if (awareLockEnabled.isNull()) {
4568 final boolean defAwareLockEnabled = getContext().getResources().getBoolean(
4569 R.bool.def_aware_lock_enabled);
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004570 secureSettings.insertSettingOverrideableByRestoreLocked(
Edgar Wang4870e4b2019-05-15 19:14:43 +08004571 Secure.AWARE_LOCK_ENABLED, defAwareLockEnabled ? "1" : "0",
4572 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4573 }
4574
4575 currentVersion = 181;
4576 }
4577
Eric Laurent02153e62019-06-12 17:20:03 -07004578 if (currentVersion == 181) {
4579 // Version cd : by default, add STREAM_BLUETOOTH_SCO to list of streams that can
4580 // be muted.
4581 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4582 final Setting currentSetting = systemSettings.getSettingLocked(
4583 Settings.System.MUTE_STREAMS_AFFECTED);
4584 if (!currentSetting.isNull()) {
4585 try {
4586 int currentSettingIntegerValue = Integer.parseInt(
4587 currentSetting.getValue());
4588 if ((currentSettingIntegerValue
4589 & (1 << AudioManager.STREAM_BLUETOOTH_SCO)) == 0) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004590 systemSettings.insertSettingOverrideableByRestoreLocked(
Eric Laurent02153e62019-06-12 17:20:03 -07004591 Settings.System.MUTE_STREAMS_AFFECTED,
4592 Integer.toString(
4593 currentSettingIntegerValue
4594 | (1 << AudioManager.STREAM_BLUETOOTH_SCO)),
4595 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4596 }
4597 } catch (NumberFormatException e) {
4598 // remove the setting in case it is not a valid integer
4599 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4600 + "setting, removing setting", e);
4601 systemSettings.deleteSettingLocked(
4602 Settings.System.MUTE_STREAMS_AFFECTED);
4603 }
4604
4605 }
4606 currentVersion = 182;
4607 }
4608
Lyn Hanb739fa62019-06-27 18:41:11 -07004609 if (currentVersion == 182) {
Mady Mellor4b73b902019-12-03 15:04:11 -08004610 // Remove secure bubble settings; it's in global now.
Mady Mellorfa9556a2019-09-19 11:10:31 -07004611 getSecureSettingsLocked(userId).deleteSettingLocked("notification_bubbles");
Lyn Hanb739fa62019-06-27 18:41:11 -07004612
Mady Mellor4b73b902019-12-03 15:04:11 -08004613 // Removed. Updated NOTIFICATION_BUBBLES to be true by default, see 184.
Lyn Hanb739fa62019-06-27 18:41:11 -07004614 currentVersion = 183;
4615 }
4616
Beverlyf364d7c2019-10-10 16:44:43 -04004617 if (currentVersion == 183) {
Mady Mellor4b73b902019-12-03 15:04:11 -08004618 // Version 183: Set default values for WIRELESS_CHARGING_STARTED_SOUND
Beverlyf364d7c2019-10-10 16:44:43 -04004619 // and CHARGING_STARTED_SOUND
4620 final SettingsState globalSettings = getGlobalSettingsLocked();
4621
4622 final String oldValueWireless = globalSettings.getSettingLocked(
4623 Global.WIRELESS_CHARGING_STARTED_SOUND).getValue();
4624 final String oldValueWired = globalSettings.getSettingLocked(
4625 Global.CHARGING_STARTED_SOUND).getValue();
4626
4627 final String defaultValueWireless = getContext().getResources().getString(
4628 R.string.def_wireless_charging_started_sound);
4629 final String defaultValueWired = getContext().getResources().getString(
4630 R.string.def_charging_started_sound);
4631
4632 // wireless charging sound
4633 if (oldValueWireless == null
4634 || TextUtils.equals(oldValueWireless, defaultValueWired)) {
4635 if (!TextUtils.isEmpty(defaultValueWireless)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004636 globalSettings.insertSettingOverrideableByRestoreLocked(
Beverlyf364d7c2019-10-10 16:44:43 -04004637 Global.WIRELESS_CHARGING_STARTED_SOUND, defaultValueWireless,
4638 null /* tag */, true /* makeDefault */,
4639 SettingsState.SYSTEM_PACKAGE_NAME);
4640 } else if (!TextUtils.isEmpty(defaultValueWired)) {
4641 // if the wireless sound is empty, use the wired charging sound
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004642 globalSettings.insertSettingOverrideableByRestoreLocked(
Beverlyf364d7c2019-10-10 16:44:43 -04004643 Global.WIRELESS_CHARGING_STARTED_SOUND, defaultValueWired,
4644 null /* tag */, true /* makeDefault */,
4645 SettingsState.SYSTEM_PACKAGE_NAME);
4646 }
4647 }
4648
4649 // wired charging sound
4650 if (oldValueWired == null && !TextUtils.isEmpty(defaultValueWired)) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004651 globalSettings.insertSettingOverrideableByRestoreLocked(
Beverlyf364d7c2019-10-10 16:44:43 -04004652 Global.CHARGING_STARTED_SOUND, defaultValueWired,
4653 null /* tag */, true /* makeDefault */,
4654 SettingsState.SYSTEM_PACKAGE_NAME);
4655 }
4656 currentVersion = 184;
4657 }
4658
Mady Mellor4b73b902019-12-03 15:04:11 -08004659 if (currentVersion == 184) {
4660 // Version 184: Reset the default for Global Settings: NOTIFICATION_BUBBLES
4661 // This is originally set in version 182, however, the default value changed
4662 // so this step is to ensure the value is updated to the correct default.
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004663 getGlobalSettingsLocked().insertSettingOverrideableByRestoreLocked(
4664 Global.NOTIFICATION_BUBBLES, getContext().getResources().getBoolean(
Mady Mellor4b73b902019-12-03 15:04:11 -08004665 R.bool.def_notification_bubbles) ? "1" : "0", null /* tag */,
4666 true /* makeDefault */, SettingsState.SYSTEM_PACKAGE_NAME);
4667
4668 currentVersion = 185;
4669 }
4670
Rhed Jao129d4192019-11-28 17:28:53 +08004671 if (currentVersion == 185) {
4672 // Deprecate ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, and migrate it
4673 // to ACCESSIBILITY_BUTTON_TARGET_COMPONENT.
4674 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4675 final Setting magnifyNavbarEnabled = secureSettings.getSettingLocked(
4676 Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED);
4677 if ("1".equals(magnifyNavbarEnabled.getValue())) {
4678 secureSettings.insertSettingLocked(
4679 Secure.ACCESSIBILITY_BUTTON_TARGET_COMPONENT,
4680 ACCESSIBILITY_SHORTCUT_TARGET_MAGNIFICATION_CONTROLLER,
4681 null /* tag */, false /* makeDefault */,
4682 SettingsState.SYSTEM_PACKAGE_NAME);
4683 } else {
4684 // Clear a11y button targets list setting. A11yManagerService will end up
4685 // adding all legacy enabled services that want the button to the list, so
4686 // there's no need to keep tracking them.
4687 secureSettings.insertSettingLocked(
4688 Secure.ACCESSIBILITY_BUTTON_TARGET_COMPONENT,
4689 null, null /* tag */, false /* makeDefault */,
4690 SettingsState.SYSTEM_PACKAGE_NAME);
4691 }
4692 secureSettings.deleteSettingLocked(
4693 Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED);
4694 currentVersion = 186;
4695 }
4696
Felipe Lemeff355092017-04-03 12:55:02 -07004697 // vXXX: Add new settings above this point.
4698
Dan Sandler71f85e92016-07-20 13:46:05 -04004699 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004700 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004701 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004702 + currentVersion +
4703 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4704 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004705 if (DEBUG) {
4706 throw new RuntimeException("db upgrade error");
4707 }
4708 }
4709
Jeff Brown503cffc2015-03-26 18:08:51 -07004710 // Return the current version.
4711 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004712 }
4713 }
Svet Ganov13701552017-02-23 12:45:17 -08004714
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004715 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4716 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004717 List<String> names = settings.getSettingNamesLocked();
4718 final int nameCount = names.size();
4719 for (int i = 0; i < nameCount; i++) {
4720 String name = names.get(i);
4721 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004722
4723 // In the upgrade case we pretend the call is made from the app
4724 // that made the last change to the setting to properly determine
4725 // whether the call has been made by a system component.
4726 int callingUid = -1;
4727 try {
4728 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4729 } catch (RemoteException e) {
4730 /* ignore - handled below */
4731 }
4732 if (callingUid < 0) {
4733 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4734 continue;
4735 }
4736 try {
4737 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
Matt Pape25c940d2019-03-26 12:14:33 -07004738 setting.getPackageName(), callingUid, userId);
Svet Ganov13701552017-02-23 12:45:17 -08004739 if (systemSet) {
Ruslan Tkhakokhov018f5532020-01-09 21:16:10 +00004740 settings.insertSettingOverrideableByRestoreLocked(name, setting.getValue(),
Svet Ganov13701552017-02-23 12:45:17 -08004741 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004742 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4743 // We had a bug where changes by non-system packages were marked
4744 // as system made and as a result set as the default. Therefore, if
4745 // the package changed the setting last is not a system one but the
4746 // setting is marked as its default coming from the system we clear
4747 // the default and clear the system set flag.
4748 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004749 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004750 } catch (IllegalStateException e) {
4751 // If the package goes over its quota during the upgrade, don't
4752 // crash but just log the error as the system does the upgrade.
4753 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4754
Svet Ganov13701552017-02-23 12:45:17 -08004755 }
4756 }
4757 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004758 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004759}