blob: 1727e75afe43d2905e7f4a43307102bb945f7cc2 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
Matt Pape1278d1c2018-12-11 13:03:49 -080066import android.provider.DeviceConfig;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070067import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010068import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080069import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000070import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070071import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010072import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080073import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000074import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070075import android.util.Slog;
76import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070077import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080078import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040079
Svetoslav683914b2015-01-15 14:22:26 -080080import com.android.internal.annotations.GuardedBy;
81import com.android.internal.content.PackageMonitor;
82import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080083import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070084import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080085import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040086
Svetoslav683914b2015-01-15 14:22:26 -080087import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080088import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080090import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080091import java.nio.ByteBuffer;
92import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000093import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080094import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070095import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080096import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000097import java.util.Collection;
Matt Pape6bfc62e2018-11-28 13:16:03 -080098import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +000099import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -0800100import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -0800101import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100102import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800103import java.util.Set;
104import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000105
Mark Rathjen7599f132017-01-23 14:15:54 -0800106import javax.crypto.Mac;
107import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700108
Svetoslav Ganove080da92016-12-21 17:10:35 -0800109
Svetoslav683914b2015-01-15 14:22:26 -0800110/**
111 * <p>
112 * This class is a content provider that publishes the system settings.
113 * It can be accessed via the content provider APIs or via custom call
114 * commands. The latter is a bit faster and is the preferred way to access
115 * the platform settings.
116 * </p>
117 * <p>
118 * There are three settings types, global (with signature level protection
119 * and shared across users), secure (with signature permission level
120 * protection and per user), and system (with dangerous permission level
121 * protection and per user). Global settings are stored under the device owner.
122 * Each of these settings is represented by a {@link
123 * com.android.providers.settings.SettingsState} object mapped to an integer
124 * key derived from the setting type in the most significant bits and user
125 * id in the least significant bits. Settings are synchronously loaded on
126 * instantiation of a SettingsState and asynchronously persisted on mutation.
127 * Settings are stored in the user specific system directory.
128 * </p>
129 * <p>
130 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
131 * and get a warning. Targeting higher API version prohibits this as the
132 * system settings are not a place for apps to save their state. When a package
133 * is removed the settings it added are deleted. Apps cannot delete system
134 * settings added by the platform. System settings values are validated to
135 * ensure the clients do not put bad values. Global and secure settings are
136 * changed only by trusted parties, therefore no validation is performed. Also
137 * there is a limit on the amount of app specific settings that can be added
138 * to prevent unlimited growth of the system process memory footprint.
139 * </p>
140 */
141@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700143 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700145 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800146
147 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700148
Christopher Tate06efb532012-08-24 15:29:27 -0700149 private static final String TABLE_SYSTEM = "system";
150 private static final String TABLE_SECURE = "secure";
151 private static final String TABLE_GLOBAL = "global";
Matt Pape6bfc62e2018-11-28 13:16:03 -0800152 private static final String TABLE_CONFIG = "config";
Svetoslav683914b2015-01-15 14:22:26 -0800153
154 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private static final String TABLE_FAVORITES = "favorites";
156 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800157 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
158 private static final String TABLE_BOOKMARKS = "bookmarks";
159 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Svetoslav683914b2015-01-15 14:22:26 -0800161 // The set of removed legacy tables.
162 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700163 static {
Svetoslav683914b2015-01-15 14:22:26 -0800164 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
165 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
166 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
167 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
168 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
169 }
Christopher Tate06efb532012-08-24 15:29:27 -0700170
Svetoslav683914b2015-01-15 14:22:26 -0800171 private static final int MUTATION_OPERATION_INSERT = 1;
172 private static final int MUTATION_OPERATION_DELETE = 2;
173 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800174 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400175
Svetoslav683914b2015-01-15 14:22:26 -0800176 private static final String[] ALL_COLUMNS = new String[] {
177 Settings.NameValueTable._ID,
178 Settings.NameValueTable.NAME,
179 Settings.NameValueTable.VALUE
180 };
181
Makoto Onuki53f0e022017-11-29 13:51:01 -0800182 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
183 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
184 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
185 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700186 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700187
188 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
189 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700190
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800191 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800192 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800193
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700194 // Overlay specified settings whitelisted for Instant Apps
195 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
196 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
197 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
198
199 static {
200 for (String name : Resources.getSystem().getStringArray(
201 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
202 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
203 }
204 for (String name : Resources.getSystem().getStringArray(
205 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
206 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
207 }
208 for (String name : Resources.getSystem().getStringArray(
209 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
210 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
211 }
212 }
213
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800214 // Changes to these global settings are synchronously persisted
215 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
216 static {
217 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
218 }
219
220 // Changes to these secure settings are synchronously persisted
221 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
222 static {
223 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
224 }
225
Svetoslav683914b2015-01-15 14:22:26 -0800226 // Per user secure settings that moved to the for all users global settings.
227 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
228 static {
229 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700230 }
231
Svetoslav683914b2015-01-15 14:22:26 -0800232 // Per user system settings that moved to the for all users global settings.
233 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
234 static {
235 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700236 }
237
Svetoslav683914b2015-01-15 14:22:26 -0800238 // Per user system settings that moved to the per user secure settings.
239 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
240 static {
241 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 }
243
Svetoslav683914b2015-01-15 14:22:26 -0800244 // Per all users global settings that moved to the per user secure settings.
245 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
246 static {
247 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 }
249
Svetoslav683914b2015-01-15 14:22:26 -0800250 // Per user secure settings that are cloned for the managed profiles of the user.
251 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
252 static {
253 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700254 }
255
Svetoslav683914b2015-01-15 14:22:26 -0800256 // Per user system settings that are cloned for the managed profiles of the user.
257 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
258 static {
259 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400260 }
261
Andre Lago3fa139c2016-08-04 13:53:44 +0100262 // Per user system settings that are cloned from the profile's parent when a dependency
263 // in {@link Settings.Secure} is set to "1".
264 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
265 static {
266 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
267 }
268
Svetoslav683914b2015-01-15 14:22:26 -0800269 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700270
Svetoslav683914b2015-01-15 14:22:26 -0800271 @GuardedBy("mLock")
272 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700273
Svet Ganova8f90262016-05-10 08:44:48 -0700274 @GuardedBy("mLock")
275 private HandlerThread mHandlerThread;
276
Makoto Onuki73360ab2017-03-17 11:50:13 -0700277 @GuardedBy("mLock")
278 private Handler mHandler;
279
Svetoslav7ec28e82015-05-20 17:01:10 -0700280 // We have to call in the user manager with no lock held,
281 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800282
yuemingw1d13eae2018-01-30 17:27:54 +0000283 private UserManagerInternal mUserManagerInternal;
284
Svetoslav7ec28e82015-05-20 17:01:10 -0700285 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700286 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700287
Svet Ganov53a441c2016-04-19 19:38:00 -0700288 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800289 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700290 }
291
292 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800293 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700294 }
295
296 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800297 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700298 }
299
300 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800301 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700302 }
303
304 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800305 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700306 }
307
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 @Override
309 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800310 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000311
312 // fail to boot if there're any backed up settings that don't have a non-null validator
313 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000314 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000315 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000316
Svetoslav683914b2015-01-15 14:22:26 -0800317 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700318 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000319 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700320 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700321 mHandlerThread = new HandlerThread(LOG_TAG,
322 Process.THREAD_PRIORITY_BACKGROUND);
323 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700324 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800325 mSettingsRegistry = new SettingsRegistry();
326 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700327 mHandler.post(() -> {
328 registerBroadcastReceivers();
329 startWatchingUserRestrictionChanges();
330 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700331 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800332 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333 return true;
334 }
335
Michal Karpinski2c37b082018-01-18 16:14:27 +0000336 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000337 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
338 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000339
340 failToBootIfOffendersPresent(offenders, "Settings.System");
341 }
342
343 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000344 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
345 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000346
347 failToBootIfOffendersPresent(offenders, "Settings.Global");
348 }
349
Michal Karpinski964943a2018-01-19 16:28:26 +0000350 private void ensureAllBackedUpSecureSettingsHaveValidators() {
351 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
352 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
353
354 failToBootIfOffendersPresent(offenders, "Settings.Secure");
355 }
356
Michal Karpinski5db1e432018-01-18 20:10:24 +0000357 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
358 if (offenders.length() > 0) {
359 throw new RuntimeException("All " + settingsType + " settings that are backed up"
360 + " have to have a non-null validator, but those don't: " + offenders);
361 }
362 }
363
364 private String getOffenders(String[] settingsToBackup, Map<String,
365 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000366 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000367 for (String setting : settingsToBackup) {
368 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000369 offenders.append(setting).append(" ");
370 }
371 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000372 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000373 }
374
Michal Karpinski964943a2018-01-19 16:28:26 +0000375 private final String[] concat(String[] first, String[] second) {
376 if (second == null || second.length == 0) {
377 return first;
378 }
379 final int firstLen = first.length;
380 final int secondLen = second.length;
381 String[] both = new String[firstLen + secondLen];
382 System.arraycopy(first, 0, both, 0, firstLen);
383 System.arraycopy(second, 0, both, firstLen, secondLen);
384 return both;
385 }
386
Svetoslav683914b2015-01-15 14:22:26 -0800387 @Override
388 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700389 final int requestingUserId = getRequestingUserId(args);
390 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700391 case Settings.CALL_METHOD_GET_CONFIG: {
392 Setting setting = getConfigSetting(name);
393 return packageValueForCallResult(setting, isTrackingGeneration(args));
394 }
395
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 case Settings.CALL_METHOD_GET_GLOBAL: {
397 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700398 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800399 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700400
401 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800402 Setting setting = getSecureSetting(name, requestingUserId,
403 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700404 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 }
406
407 case Settings.CALL_METHOD_GET_SYSTEM: {
408 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700409 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700410 }
411
Matt Pape1b31a332018-10-17 09:58:28 -0700412 case Settings.CALL_METHOD_PUT_CONFIG: {
413 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700414 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800415 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700416 break;
417 }
418
Svetoslav7ec28e82015-05-20 17:01:10 -0700419 case Settings.CALL_METHOD_PUT_GLOBAL: {
420 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800421 String tag = getSettingTag(args);
422 final boolean makeDefault = getSettingMakeDefault(args);
423 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700424 break;
425 }
426
427 case Settings.CALL_METHOD_PUT_SECURE: {
428 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800429 String tag = getSettingTag(args);
430 final boolean makeDefault = getSettingMakeDefault(args);
431 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700432 break;
433 }
434
435 case Settings.CALL_METHOD_PUT_SYSTEM: {
436 String value = getSettingValue(args);
437 insertSystemSetting(name, value, requestingUserId);
438 break;
439 }
440
Matt Pape1b31a332018-10-17 09:58:28 -0700441 case Settings.CALL_METHOD_RESET_CONFIG: {
442 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800443 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800444 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700445 break;
446 }
447
Svetoslav Ganove080da92016-12-21 17:10:35 -0800448 case Settings.CALL_METHOD_RESET_GLOBAL: {
449 final int mode = getResetModeEnforcingPermission(args);
450 String tag = getSettingTag(args);
451 resetGlobalSetting(requestingUserId, mode, tag);
452 break;
453 }
454
455 case Settings.CALL_METHOD_RESET_SECURE: {
456 final int mode = getResetModeEnforcingPermission(args);
457 String tag = getSettingTag(args);
458 resetSecureSetting(requestingUserId, mode, tag);
459 break;
460 }
461
Matt Pape6bfc62e2018-11-28 13:16:03 -0800462 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800463 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800464 Bundle result = new Bundle();
465 result.putInt(RESULT_ROWS_DELETED, rows);
466 return result;
467 }
468
469 case Settings.CALL_METHOD_DELETE_GLOBAL: {
470 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
471 Bundle result = new Bundle();
472 result.putInt(RESULT_ROWS_DELETED, rows);
473 return result;
474 }
475
Matt Pape6bfc62e2018-11-28 13:16:03 -0800476 case Settings.CALL_METHOD_DELETE_SECURE: {
477 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
478 Bundle result = new Bundle();
479 result.putInt(RESULT_ROWS_DELETED, rows);
480 return result;
481 }
482
483 case Settings.CALL_METHOD_DELETE_SYSTEM: {
484 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
485 Bundle result = new Bundle();
486 result.putInt(RESULT_ROWS_DELETED, rows);
487 return result;
488 }
489
490 case Settings.CALL_METHOD_LIST_CONFIG: {
491 String prefix = getSettingPrefix(args);
492 Bundle result = new Bundle();
493 result.putSerializable(
494 Settings.NameValueTable.VALUE, (HashMap) getAllConfigFlags(prefix));
495 return result;
496 }
497
498 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800499 Bundle result = new Bundle();
500 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800501 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800502 return result;
503 }
504
505 case Settings.CALL_METHOD_LIST_SECURE: {
506 Bundle result = new Bundle();
507 result.putStringArrayList(RESULT_SETTINGS_LIST,
508 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
509 return result;
510 }
511
Matt Pape6bfc62e2018-11-28 13:16:03 -0800512 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800513 Bundle result = new Bundle();
514 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800515 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800516 return result;
517 }
518
Svetoslav7ec28e82015-05-20 17:01:10 -0700519 default: {
520 Slog.w(LOG_TAG, "call() with invalid method: " + method);
521 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700522 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700523
Christopher Tate06efb532012-08-24 15:29:27 -0700524 return null;
525 }
526
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800527 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800528 public String getType(Uri uri) {
529 Arguments args = new Arguments(uri, null, null, true);
530 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531 return "vnd.android.cursor.dir/" + args.table;
532 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700533 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700534 }
535 }
536
537 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800538 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
539 String order) {
540 if (DEBUG) {
541 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542 }
543
Svetoslav683914b2015-01-15 14:22:26 -0800544 Arguments args = new Arguments(uri, where, whereArgs, true);
545 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700546
Svetoslav683914b2015-01-15 14:22:26 -0800547 // If a legacy table that is gone, done.
548 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
549 return new MatrixCursor(normalizedProjection, 0);
550 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700551
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 switch (args.table) {
553 case TABLE_GLOBAL: {
554 if (args.name != null) {
555 Setting setting = getGlobalSetting(args.name);
556 return packageSettingForQuery(setting, normalizedProjection);
557 } else {
558 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700559 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700560 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700561
Svetoslav7ec28e82015-05-20 17:01:10 -0700562 case TABLE_SECURE: {
563 final int userId = UserHandle.getCallingUserId();
564 if (args.name != null) {
565 Setting setting = getSecureSetting(args.name, userId);
566 return packageSettingForQuery(setting, normalizedProjection);
567 } else {
568 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800569 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700570 }
Svetoslav683914b2015-01-15 14:22:26 -0800571
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 case TABLE_SYSTEM: {
573 final int userId = UserHandle.getCallingUserId();
574 if (args.name != null) {
575 Setting setting = getSystemSetting(args.name, userId);
576 return packageSettingForQuery(setting, normalizedProjection);
577 } else {
578 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800579 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700580 }
Svetoslav683914b2015-01-15 14:22:26 -0800581
Svetoslav7ec28e82015-05-20 17:01:10 -0700582 default: {
583 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700584 }
585 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700586 }
587
Nicholas Sauer72500532018-11-21 10:30:58 -0800588 private ArrayList<String> buildSettingsList(Cursor cursor) {
589 final ArrayList<String> lines = new ArrayList<String>();
590 try {
591 while (cursor != null && cursor.moveToNext()) {
592 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
593 }
594 } finally {
595 if (cursor != null) {
596 cursor.close();
597 }
598 }
599 return lines;
600 }
601
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700602 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800603 public Uri insert(Uri uri, ContentValues values) {
604 if (DEBUG) {
605 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700606 }
607
Svetoslav683914b2015-01-15 14:22:26 -0800608 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700609
Svetoslav683914b2015-01-15 14:22:26 -0800610 // If a legacy table that is gone, done.
611 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 return null;
613 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614
Svetoslav683914b2015-01-15 14:22:26 -0800615 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700616 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800617 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700618 }
619
Svetoslav683914b2015-01-15 14:22:26 -0800620 String value = values.getAsString(Settings.Secure.VALUE);
621
Svetoslav7ec28e82015-05-20 17:01:10 -0700622 switch (table) {
623 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800624 if (insertGlobalSetting(name, value, null, false,
625 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700626 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700627 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700628 } break;
629
630 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800631 if (insertSecureSetting(name, value, null, false,
632 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700633 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
634 }
635 } break;
636
637 case TABLE_SYSTEM: {
638 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
639 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
640 }
641 } break;
642
643 default: {
644 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700645 }
646 }
647
Svetoslav683914b2015-01-15 14:22:26 -0800648 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700649 }
650
651 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800652 public int bulkInsert(Uri uri, ContentValues[] allValues) {
653 if (DEBUG) {
654 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700656
Svetoslav683914b2015-01-15 14:22:26 -0800657 int insertionCount = 0;
658 final int valuesCount = allValues.length;
659 for (int i = 0; i < valuesCount; i++) {
660 ContentValues values = allValues[i];
661 if (insert(uri, values) != null) {
662 insertionCount++;
663 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700664 }
Svetoslav683914b2015-01-15 14:22:26 -0800665
666 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700667 }
668
669 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800670 public int delete(Uri uri, String where, String[] whereArgs) {
671 if (DEBUG) {
672 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700674
Svetoslav683914b2015-01-15 14:22:26 -0800675 Arguments args = new Arguments(uri, where, whereArgs, false);
676
677 // If a legacy table that is gone, done.
678 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
679 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700680 }
Svetoslav683914b2015-01-15 14:22:26 -0800681
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700682 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800683 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700684 }
Svetoslav683914b2015-01-15 14:22:26 -0800685
Svetoslav7ec28e82015-05-20 17:01:10 -0700686 switch (args.table) {
687 case TABLE_GLOBAL: {
688 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700689 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700690 }
Svetoslav683914b2015-01-15 14:22:26 -0800691
Svetoslav7ec28e82015-05-20 17:01:10 -0700692 case TABLE_SECURE: {
693 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700694 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700695 }
Svetoslav683914b2015-01-15 14:22:26 -0800696
Svetoslav7ec28e82015-05-20 17:01:10 -0700697 case TABLE_SYSTEM: {
698 final int userId = UserHandle.getCallingUserId();
699 return deleteSystemSetting(args.name, userId) ? 1 : 0;
700 }
701
702 default: {
703 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800704 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700705 }
Svetoslav683914b2015-01-15 14:22:26 -0800706 }
707
708 @Override
709 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
710 if (DEBUG) {
711 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700712 }
Svetoslav683914b2015-01-15 14:22:26 -0800713
714 Arguments args = new Arguments(uri, where, whereArgs, false);
715
716 // If a legacy table that is gone, done.
717 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
718 return 0;
719 }
720
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700721 String name = values.getAsString(Settings.Secure.NAME);
722 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800723 return 0;
724 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700725 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800726
Svetoslav7ec28e82015-05-20 17:01:10 -0700727 switch (args.table) {
728 case TABLE_GLOBAL: {
729 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800730 return updateGlobalSetting(args.name, value, null, false,
731 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700732 }
Svetoslav683914b2015-01-15 14:22:26 -0800733
Svetoslav7ec28e82015-05-20 17:01:10 -0700734 case TABLE_SECURE: {
735 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800736 return updateSecureSetting(args.name, value, null, false,
737 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700738 }
Svetoslav683914b2015-01-15 14:22:26 -0800739
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 case TABLE_SYSTEM: {
741 final int userId = UserHandle.getCallingUserId();
742 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
743 }
Svetoslav683914b2015-01-15 14:22:26 -0800744
Svetoslav7ec28e82015-05-20 17:01:10 -0700745 default: {
746 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800747 }
748 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700749 }
750
751 @Override
752 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100753 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
754 if (userId != UserHandle.getCallingUserId()) {
755 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
756 "Access files from the settings of another user");
757 }
758 uri = ContentProvider.getUriWithoutUserId(uri);
759
Andre Lago3fa139c2016-08-04 13:53:44 +0100760 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700761 final String cacheName;
762 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100763 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700764 cacheName = Settings.System.RINGTONE_CACHE;
765 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100766 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700767 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
768 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100769 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700770 cacheName = Settings.System.ALARM_ALERT_CACHE;
771 } else {
772 throw new FileNotFoundException("Direct file access no longer supported; "
773 + "ringtone playback is available through android.media.Ringtone");
774 }
775
Andre Lago3fa139c2016-08-04 13:53:44 +0100776 int actualCacheOwner;
777 // Redirect cache to parent if ringtone setting is owned by profile parent
778 synchronized (mLock) {
779 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
780 cacheRingtoneSetting);
781 }
782 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700783 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
784 }
785
786 private File getRingtoneCacheDir(int userId) {
787 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
788 cacheDir.mkdir();
789 SELinux.restorecon(cacheDir);
790 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700791 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800792
Eugene Suslad72c3972016-12-27 15:49:30 -0800793 /**
794 * Dump all settings as a proto buf.
795 *
796 * @param fd The file to dump to
797 */
798 void dumpProto(@NonNull FileDescriptor fd) {
799 ProtoOutputStream proto = new ProtoOutputStream(fd);
800
801 synchronized (mLock) {
802 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800803 }
804
805 proto.flush();
806 }
807
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700808 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800809 synchronized (mLock) {
810 final long identity = Binder.clearCallingIdentity();
811 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700812 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800813 final int userCount = users.size();
814 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700815 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800816 }
817 } finally {
818 Binder.restoreCallingIdentity(identity);
819 }
820 }
821 }
822
Andreas Gampeb58893072018-09-05 16:52:31 -0700823 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700824 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700825 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700826 pw.println("CONFIG SETTINGS (user " + userId + ")");
827 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
828 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
829 if (configSettings != null) {
830 dumpSettingsLocked(configSettings, pw);
831 pw.println();
832 configSettings.dumpHistoricalOperations(pw);
833 }
834
Svetoslavb505ccc2015-02-17 12:41:04 -0800835 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700836 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
837 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700838 if (globalSettings != null) {
839 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800840 pw.println();
841 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700842 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800843 }
844
845 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700846 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
847 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700848 if (secureSettings != null) {
849 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800850 pw.println();
851 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700852 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700853
Svetoslavb505ccc2015-02-17 12:41:04 -0800854 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700855 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
856 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700857 if (systemSettings != null) {
858 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800859 pw.println();
860 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700861 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800862 }
863
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700864 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
865 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800866
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700867 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800868
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700869 for (int i = 0; i < nameCount; i++) {
870 String name = names.get(i);
871 Setting setting = settingsState.getSettingLocked(name);
872 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
873 pw.print(" name:"); pw.print(toDumpString(name));
874 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800875 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700876 }
877 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800878 if (setting.getDefaultValue() != null) {
879 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800880 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800881 }
882 if (setting.getTag() != null) {
883 pw.print(" tag:"); pw.print(setting.getTag());
884 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800885 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700886 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800887 }
888
Svetoslav7e0683b2015-08-03 16:02:52 -0700889 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700890 if (s != null) {
891 return s;
892 }
893 return "{null}";
894 }
895
Svetoslav683914b2015-01-15 14:22:26 -0800896 private void registerBroadcastReceivers() {
897 IntentFilter userFilter = new IntentFilter();
898 userFilter.addAction(Intent.ACTION_USER_REMOVED);
899 userFilter.addAction(Intent.ACTION_USER_STOPPED);
900
901 getContext().registerReceiver(new BroadcastReceiver() {
902 @Override
903 public void onReceive(Context context, Intent intent) {
904 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700905 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800906
907 switch (intent.getAction()) {
908 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700909 synchronized (mLock) {
910 mSettingsRegistry.removeUserStateLocked(userId, true);
911 }
Svetoslav683914b2015-01-15 14:22:26 -0800912 } break;
913
914 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700915 synchronized (mLock) {
916 mSettingsRegistry.removeUserStateLocked(userId, false);
917 }
Svetoslav683914b2015-01-15 14:22:26 -0800918 } break;
919 }
920 }
921 }, userFilter);
922
923 PackageMonitor monitor = new PackageMonitor() {
924 @Override
925 public void onPackageRemoved(String packageName, int uid) {
926 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100927 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800928 UserHandle.getUserId(uid));
929 }
930 }
Mark Rathjend891f012017-01-19 04:10:37 +0000931
932 @Override
933 public void onUidRemoved(int uid) {
934 synchronized (mLock) {
935 mSettingsRegistry.onUidRemovedLocked(uid);
936 }
937 }
Zimuzoc56192c2018-07-25 10:40:01 +0100938
939 @Override
940 public void onPackageDataCleared(String packageName, int uid) {
941 synchronized (mLock) {
942 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
943 UserHandle.getUserId(uid));
944 }
945 }
Svetoslav683914b2015-01-15 14:22:26 -0800946 };
947
948 // package changes
949 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
950 UserHandle.ALL, true);
951 }
952
Svet Ganov53a441c2016-04-19 19:38:00 -0700953 private void startWatchingUserRestrictionChanges() {
954 // TODO: The current design of settings looking different based on user restrictions
955 // should be reworked to keep them separate and system code should check the setting
956 // first followed by checking the user restriction before performing an operation.
957 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
958 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
959 Bundle prevRestrictions) -> {
960 // We are changing the settings affected by restrictions to their current
961 // value with a forced update to ensure that all cross profile dependencies
962 // are taken into account. Also make sure the settings update to.. the same
963 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800964 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
965 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700966 final long identity = Binder.clearCallingIdentity();
967 try {
968 synchronized (mLock) {
969 Setting setting = getSecureSetting(
970 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
971 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800972 setting != null ? setting.getValue() : null, null,
973 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700974 }
975 } finally {
976 Binder.restoreCallingIdentity(identity);
977 }
978 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800979 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100980 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
981 newRestrictions.getBoolean(
982 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
983 != prevRestrictions.getBoolean(
984 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700985 final long identity = Binder.clearCallingIdentity();
986 try {
987 synchronized (mLock) {
988 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800989 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700990 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800991 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700992 }
993 } finally {
994 Binder.restoreCallingIdentity(identity);
995 }
996 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800997 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
998 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700999 final long identity = Binder.clearCallingIdentity();
1000 try {
1001 synchronized (mLock) {
1002 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001003 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001004 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001005 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001006 }
1007 } finally {
1008 Binder.restoreCallingIdentity(identity);
1009 }
1010 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001011 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
1012 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001013 final long identity = Binder.clearCallingIdentity();
1014 try {
1015 synchronized (mLock) {
1016 Setting enable = getGlobalSetting(
1017 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001018 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001019 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001020 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001021 Setting include = getGlobalSetting(
1022 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001023 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001024 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001025 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001026 }
1027 } finally {
1028 Binder.restoreCallingIdentity(identity);
1029 }
1030 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001031 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
1032 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001033 final long identity = Binder.clearCallingIdentity();
1034 try {
1035 synchronized (mLock) {
1036 Setting setting = getGlobalSetting(
1037 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001038 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001039 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001040 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001041 }
1042 } finally {
1043 Binder.restoreCallingIdentity(identity);
1044 }
1045 }
1046 });
1047 }
1048
Matt Pape1b31a332018-10-17 09:58:28 -07001049 private Setting getConfigSetting(String name) {
1050 if (DEBUG) {
1051 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1052 }
1053
1054 // TODO(b/117663715): Ensure the caller can access the setting.
1055 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1056
1057 // Get the value.
1058 synchronized (mLock) {
1059 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1060 UserHandle.USER_SYSTEM, name);
1061 }
1062 }
1063
Matt Papec1323dc2018-12-11 12:32:42 -08001064 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001065 if (DEBUG) {
1066 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001067 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001068 }
Matt Papec1323dc2018-12-11 12:32:42 -08001069 return mutateConfigSetting(name, value, null, makeDefault,
1070 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001071 }
1072
Matt Papec1323dc2018-12-11 12:32:42 -08001073 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001074 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001075 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001076 }
Matt Papec1323dc2018-12-11 12:32:42 -08001077 return mutateConfigSetting(name, null, null, false,
1078 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001079 }
1080
Matt Papec1323dc2018-12-11 12:32:42 -08001081 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001082 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001083 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001084 }
Matt Papec1323dc2018-12-11 12:32:42 -08001085 mutateConfigSetting(null, null, prefix, false,
1086 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001087 }
1088
Matt Pape6bfc62e2018-11-28 13:16:03 -08001089 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001090 boolean makeDefault, int operation, int mode) {
Matt Pape1b31a332018-10-17 09:58:28 -07001091 // TODO(b/117663715): check the new permission when it's added.
1092 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1093
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,
1100 getCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001101 }
1102
Matt Pape6bfc62e2018-11-28 13:16:03 -08001103 case MUTATION_OPERATION_DELETE: {
1104 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001105 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001106 }
1107
Matt Pape1b31a332018-10-17 09:58:28 -07001108 case MUTATION_OPERATION_RESET: {
1109 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape6bfc62e2018-11-28 13:16:03 -08001110 UserHandle.USER_SYSTEM, getCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001111 } return true;
1112 }
1113 }
1114
1115 return false;
1116 }
1117
Matt Pape6bfc62e2018-11-28 13:16:03 -08001118 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1119 if (DEBUG) {
1120 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1121 }
1122
1123 synchronized (mLock) {
1124 // Get the settings.
1125 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1126 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1127
1128 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1129 UserHandle.USER_SYSTEM);
1130
1131 final int nameCount = names.size();
1132 Map<String, String> flagsToValues = new HashMap<>(names.size());
1133
1134 for (int i = 0; i < nameCount; i++) {
1135 String name = names.get(i);
1136 Setting setting = settingsState.getSettingLocked(name);
1137 if (prefix == null || setting.getName().startsWith(prefix)) {
1138 flagsToValues.put(setting.getName(), setting.getValue());
1139 }
1140 }
1141
1142 return flagsToValues;
1143 }
1144 }
1145
Svetoslav7ec28e82015-05-20 17:01:10 -07001146 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001147 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001148 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001149 }
1150
Svetoslav7ec28e82015-05-20 17:01:10 -07001151 synchronized (mLock) {
1152 // Get the settings.
1153 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001154 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001155
Chad Brubaker97bccee2017-01-05 15:51:41 -08001156 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1157 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001158
Svetoslav7ec28e82015-05-20 17:01:10 -07001159 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001160
Svetoslav7ec28e82015-05-20 17:01:10 -07001161 String[] normalizedProjection = normalizeProjection(projection);
1162 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001163
Svetoslav7ec28e82015-05-20 17:01:10 -07001164 // Anyone can get the global settings, so no security checks.
1165 for (int i = 0; i < nameCount; i++) {
1166 String name = names.get(i);
1167 Setting setting = settingsState.getSettingLocked(name);
1168 appendSettingToCursor(result, setting);
1169 }
1170
1171 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001172 }
Svetoslav683914b2015-01-15 14:22:26 -08001173 }
1174
Svetoslav7ec28e82015-05-20 17:01:10 -07001175 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001176 if (DEBUG) {
1177 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1178 }
1179
Chad Brubakera6830e72017-04-28 17:34:36 -07001180 // Ensure the caller can access the setting.
1181 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1182
Svetoslav683914b2015-01-15 14:22:26 -08001183 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001184 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001185 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001186 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001187 }
Svetoslav683914b2015-01-15 14:22:26 -08001188 }
1189
Svetoslav Ganove080da92016-12-21 17:10:35 -08001190 private boolean updateGlobalSetting(String name, String value, String tag,
1191 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001192 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001193 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1194 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1195 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001196 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001197 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1198 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
1200
Svetoslav Ganove080da92016-12-21 17:10:35 -08001201 private boolean insertGlobalSetting(String name, String value, String tag,
1202 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001203 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001204 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1205 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1206 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001208 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1209 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001210 }
1211
Svet Ganov53a441c2016-04-19 19:38:00 -07001212 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001213 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1215 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001216 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001217 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1218 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001219 }
1220
Svetoslav Ganove080da92016-12-21 17:10:35 -08001221 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1222 if (DEBUG) {
1223 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1224 + mode + ", " + tag + ")");
1225 }
1226 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1227 MUTATION_OPERATION_RESET, false, mode);
1228 }
1229
1230 private boolean mutateGlobalSetting(String name, String value, String tag,
1231 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1232 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001233 // Make sure the caller can change the settings - treated as secure.
1234 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1235
Svetoslav683914b2015-01-15 14:22:26 -08001236 // Resolve the userId on whose behalf the call is made.
1237 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1238
Makoto Onuki28da2e32015-11-20 11:30:44 -08001239 // If this is a setting that is currently restricted for this user, do not allow
1240 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001241 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1242 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001243 return false;
1244 }
1245
1246 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001247 synchronized (mLock) {
1248 switch (operation) {
1249 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001250 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1251 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001252 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001253 }
Svetoslav683914b2015-01-15 14:22:26 -08001254
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001256 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001257 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 }
Svetoslav683914b2015-01-15 14:22:26 -08001259
Svetoslav7ec28e82015-05-20 17:01:10 -07001260 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001261 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1262 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001263 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001264 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001265
1266 case MUTATION_OPERATION_RESET: {
1267 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1268 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1269 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001270 }
1271 }
1272
1273 return false;
1274 }
1275
Christopher Tateb218e762017-04-05 16:34:07 -07001276 private PackageInfo getCallingPackageInfo(int userId) {
1277 try {
1278 return mPackageManager.getPackageInfo(getCallingPackage(),
1279 PackageManager.GET_SIGNATURES, userId);
1280 } catch (RemoteException e) {
1281 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1282 }
1283 }
1284
Svetoslav7ec28e82015-05-20 17:01:10 -07001285 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001286 if (DEBUG) {
1287 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1288 }
1289
1290 // Resolve the userId on whose behalf the call is made.
1291 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1292
Christopher Tateb218e762017-04-05 16:34:07 -07001293 // The relevant "calling package" userId will be the owning userId for some
1294 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1295 // up front who the effective "new SSAID" user ID for that settings name will be.
1296 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1297 Settings.Secure.ANDROID_ID);
1298 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1299
Svetoslav7ec28e82015-05-20 17:01:10 -07001300 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001301 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001302
Svetoslav7ec28e82015-05-20 17:01:10 -07001303 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001304
Svetoslav7ec28e82015-05-20 17:01:10 -07001305 String[] normalizedProjection = normalizeProjection(projection);
1306 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001307
Svetoslav7ec28e82015-05-20 17:01:10 -07001308 for (int i = 0; i < nameCount; i++) {
1309 String name = names.get(i);
1310 // Determine the owning user as some profile settings are cloned from the parent.
1311 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1312 name);
Svetoslav683914b2015-01-15 14:22:26 -08001313
Alex Klyubin1991f572017-03-03 14:08:36 -08001314 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1315 // This caller is not permitted to access this setting. Pretend the setting
1316 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001317 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001318 }
Svetoslav683914b2015-01-15 14:22:26 -08001319
Mark Rathjen7599f132017-01-23 14:15:54 -08001320 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001321 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1322 final Setting setting;
1323 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001324 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001325 } else {
1326 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1327 name);
1328 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001329 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001330 }
1331
Svetoslav7ec28e82015-05-20 17:01:10 -07001332 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001333 }
Svetoslav683914b2015-01-15 14:22:26 -08001334 }
1335
Svetoslav7ec28e82015-05-20 17:01:10 -07001336 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001337 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1338 }
1339
1340 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001341 if (DEBUG) {
1342 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1343 }
1344
1345 // Resolve the userId on whose behalf the call is made.
1346 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1347
Chad Brubakera6830e72017-04-28 17:34:36 -07001348 // Ensure the caller can access the setting.
1349 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1350
Svetoslav683914b2015-01-15 14:22:26 -08001351 // Determine the owning user as some profile settings are cloned from the parent.
1352 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1353
Alex Klyubin1991f572017-03-03 14:08:36 -08001354 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1355 // This caller is not permitted to access this setting. Pretend the setting doesn't
1356 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001357 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1358 owningUserId);
1359 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001360 }
1361
Christopher Tateb218e762017-04-05 16:34:07 -07001362 // As of Android O, the SSAID is read from an app-specific entry in table
1363 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1364 if (isNewSsaidSetting(name)) {
1365 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1366 synchronized (mLock) {
1367 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001368 }
Christopher Tateb218e762017-04-05 16:34:07 -07001369 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001370 if (enableOverride) {
1371 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1372 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1373 if (overridden != null) {
1374 return overridden;
1375 }
1376 }
1377 }
Mark Rathjend891f012017-01-19 04:10:37 +00001378
Christopher Tateb218e762017-04-05 16:34:07 -07001379 // Not the SSAID; do a straight lookup
1380 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001381 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001382 owningUserId, name);
1383 }
Svetoslav683914b2015-01-15 14:22:26 -08001384 }
1385
Mark Rathjend891f012017-01-19 04:10:37 +00001386 private boolean isNewSsaidSetting(String name) {
1387 return Settings.Secure.ANDROID_ID.equals(name)
1388 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1389 }
1390
Andreas Gampeb58893072018-09-05 16:52:31 -07001391 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001392 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001393 // Get uid of caller (key) used to store ssaid value
1394 String name = Integer.toString(
1395 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1396
1397 if (DEBUG) {
1398 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1399 }
1400
1401 // Retrieve the ssaid from the table if present.
1402 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1403 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001404 // If the app is an Instant App use its stored SSAID instead of our own.
1405 final String instantSsaid;
1406 final long token = Binder.clearCallingIdentity();
1407 try {
1408 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1409 owningUserId);
1410 } catch (RemoteException e) {
1411 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1412 return null;
1413 } finally {
1414 Binder.restoreCallingIdentity(token);
1415 }
Svet Ganov96c99462017-05-05 14:27:13 -07001416
1417 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1418 SETTINGS_TYPE_SSAID, owningUserId);
1419
Chad Brubaker0d277a72017-04-12 16:56:53 -07001420 if (instantSsaid != null) {
1421 // Use the stored value if it is still valid.
1422 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001423 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001424 }
1425 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001426 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1427 true, callingPkg.packageName);
1428 if (!success) {
1429 throw new IllegalStateException("Failed to update instant app android id");
1430 }
Svet Ganov96c99462017-05-05 14:27:13 -07001431 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1432 owningUserId, name);
1433 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001434 }
Mark Rathjend891f012017-01-19 04:10:37 +00001435
1436 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001437 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001438 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1439 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001440 }
1441
Svet Ganov96c99462017-05-05 14:27:13 -07001442 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1443 }
1444
1445 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1446 // SSAID settings are located in a dedicated table for internal bookkeeping
1447 // but for the world they reside in the secure table, so adjust the key here.
1448 // We have a special name when looking it up but want the world to see it as
1449 // "android_id".
1450 if (ssaidSetting != null) {
1451 return settingsState.new Setting(ssaidSetting) {
1452 @Override
1453 public int getKey() {
1454 final int userId = getUserIdFromKey(super.getKey());
1455 return makeKey(SETTINGS_TYPE_SECURE, userId);
1456 }
1457
1458 @Override
1459 public String getName() {
1460 return Settings.Secure.ANDROID_ID;
1461 }
1462 };
1463 }
1464 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001465 }
1466
Makoto Onuki0000d322017-11-28 16:31:47 -08001467 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1468 synchronized (mLock) {
1469 final Setting setting = getGlobalSetting(
1470 Global.LOCATION_GLOBAL_KILL_SWITCH);
1471 if (!"1".equals(setting.getValue())) {
1472 return null;
1473 }
1474 // Global kill-switch is enabled. Return an empty value.
1475 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1476 SETTINGS_TYPE_SECURE, owningUserId);
1477 return settingsState.new Setting(
1478 Secure.LOCATION_PROVIDERS_ALLOWED,
1479 "", // value
1480 "", // tag
1481 "", // default value
1482 "", // package name
1483 false, // from system
1484 "0" // id
1485 ) {
1486 @Override
1487 public boolean update(String value, boolean setDefault, String packageName,
1488 String tag, boolean forceNonSystemPackage) {
1489 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1490 return false;
1491 }
1492 };
1493 }
1494 }
1495
Svetoslav Ganove080da92016-12-21 17:10:35 -08001496 private boolean insertSecureSetting(String name, String value, String tag,
1497 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001498 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001499 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001500 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1501 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001502 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001503 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1504 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001505 }
1506
Svet Ganov53a441c2016-04-19 19:38:00 -07001507 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001508 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001509 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1510 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001511 }
1512
Svetoslav Ganove080da92016-12-21 17:10:35 -08001513 return mutateSecureSetting(name, null, null, false, requestingUserId,
1514 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001515 }
1516
Svetoslav Ganove080da92016-12-21 17:10:35 -08001517 private boolean updateSecureSetting(String name, String value, String tag,
1518 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001519 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001520 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001521 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1522 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001523 }
1524
Svetoslav Ganove080da92016-12-21 17:10:35 -08001525 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1526 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001527 }
1528
Svetoslav Ganove080da92016-12-21 17:10:35 -08001529 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1530 if (DEBUG) {
1531 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1532 + mode + ", " + tag + ")");
1533 }
1534
1535 mutateSecureSetting(null, null, tag, false, requestingUserId,
1536 MUTATION_OPERATION_RESET, false, mode);
1537 }
1538
1539 private boolean mutateSecureSetting(String name, String value, String tag,
1540 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1541 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001542 // Make sure the caller can change the settings.
1543 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1544
Svetoslav683914b2015-01-15 14:22:26 -08001545 // Resolve the userId on whose behalf the call is made.
1546 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1547
Makoto Onuki28da2e32015-11-20 11:30:44 -08001548 // If this is a setting that is currently restricted for this user, do not allow
1549 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001550 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1551 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001552 return false;
1553 }
1554
1555 // Determine the owning user as some profile settings are cloned from the parent.
1556 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1557
1558 // Only the owning user can change the setting.
1559 if (owningUserId != callingUserId) {
1560 return false;
1561 }
1562
1563 // Special cases for location providers (sigh).
1564 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001565 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1566 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001567 }
1568
1569 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001570 synchronized (mLock) {
1571 switch (operation) {
1572 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001573 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001574 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001575 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001576 }
Svetoslav683914b2015-01-15 14:22:26 -08001577
Svetoslav7ec28e82015-05-20 17:01:10 -07001578 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001579 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001580 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001581 }
Svetoslav683914b2015-01-15 14:22:26 -08001582
Svetoslav7ec28e82015-05-20 17:01:10 -07001583 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001584 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001585 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001586 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001587 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001588
1589 case MUTATION_OPERATION_RESET: {
1590 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1591 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1592 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001593 }
1594 }
1595
1596 return false;
1597 }
1598
Svetoslav7ec28e82015-05-20 17:01:10 -07001599 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001600 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001601 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001602 }
1603
1604 // Resolve the userId on whose behalf the call is made.
1605 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1606
Svetoslav7ec28e82015-05-20 17:01:10 -07001607 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001608 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001609
Svetoslav7ec28e82015-05-20 17:01:10 -07001610 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001611
Svetoslav7ec28e82015-05-20 17:01:10 -07001612 String[] normalizedProjection = normalizeProjection(projection);
1613 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001614
Svetoslav7ec28e82015-05-20 17:01:10 -07001615 for (int i = 0; i < nameCount; i++) {
1616 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001617
Svetoslav7ec28e82015-05-20 17:01:10 -07001618 // Determine the owning user as some profile settings are cloned from the parent.
1619 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1620 name);
Svetoslav683914b2015-01-15 14:22:26 -08001621
Svetoslav7ec28e82015-05-20 17:01:10 -07001622 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001623 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001624 appendSettingToCursor(result, setting);
1625 }
1626
1627 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001628 }
Svetoslav683914b2015-01-15 14:22:26 -08001629 }
1630
Svetoslav7ec28e82015-05-20 17:01:10 -07001631 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001632 if (DEBUG) {
1633 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1634 }
1635
1636 // Resolve the userId on whose behalf the call is made.
1637 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1638
Chad Brubakera6830e72017-04-28 17:34:36 -07001639 // Ensure the caller can access the setting.
1640 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001641
Svetoslav683914b2015-01-15 14:22:26 -08001642 // Determine the owning user as some profile settings are cloned from the parent.
1643 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1644
1645 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001646 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001647 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001648 }
Svetoslav683914b2015-01-15 14:22:26 -08001649 }
1650
Svetoslav7ec28e82015-05-20 17:01:10 -07001651 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001652 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001653 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001654 + requestingUserId + ")");
1655 }
1656
Svetoslav7ec28e82015-05-20 17:01:10 -07001657 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001658 }
1659
Svetoslav7ec28e82015-05-20 17:01:10 -07001660 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001661 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001662 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001663 }
1664
Svetoslav7ec28e82015-05-20 17:01:10 -07001665 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001666 }
1667
Svetoslav7ec28e82015-05-20 17:01:10 -07001668 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001669 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001670 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001671 + requestingUserId + ")");
1672 }
1673
Svetoslav7ec28e82015-05-20 17:01:10 -07001674 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001675 }
1676
Svetoslav7ec28e82015-05-20 17:01:10 -07001677 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001678 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001679 if (!hasWriteSecureSettingsPermission()) {
1680 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1681 // operation is allowed for the calling package through appops.
1682 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1683 Binder.getCallingUid(), getCallingPackage(), true)) {
1684 return false;
1685 }
Svetoslav683914b2015-01-15 14:22:26 -08001686 }
1687
Svetoslav683914b2015-01-15 14:22:26 -08001688 // Resolve the userId on whose behalf the call is made.
1689 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1690
yuemingw1d13eae2018-01-30 17:27:54 +00001691 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1692 name, callingUserId, value, Binder.getCallingUid())) {
1693 return false;
1694 }
1695
Svetoslavd8d25e02015-11-20 13:09:26 -08001696 // Enforce what the calling package can mutate the system settings.
1697 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1698
Svetoslav683914b2015-01-15 14:22:26 -08001699 // Determine the owning user as some profile settings are cloned from the parent.
1700 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1701
1702 // Only the owning user id can change the setting.
1703 if (owningUserId != callingUserId) {
1704 return false;
1705 }
1706
Jeff Sharkey413573a2016-02-22 17:52:45 -07001707 // Invalidate any relevant cache files
1708 String cacheName = null;
1709 if (Settings.System.RINGTONE.equals(name)) {
1710 cacheName = Settings.System.RINGTONE_CACHE;
1711 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1712 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1713 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1714 cacheName = Settings.System.ALARM_ALERT_CACHE;
1715 }
1716 if (cacheName != null) {
1717 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001718 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001719 cacheFile.delete();
1720 }
1721
Svetoslav683914b2015-01-15 14:22:26 -08001722 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001723 synchronized (mLock) {
1724 switch (operation) {
1725 case MUTATION_OPERATION_INSERT: {
1726 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001727 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001728 owningUserId, name, value, null, false, getCallingPackage(),
1729 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001730 }
1731
1732 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001733 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001734 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001735 }
1736
1737 case MUTATION_OPERATION_UPDATE: {
1738 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001739 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001740 owningUserId, name, value, null, false, getCallingPackage(),
1741 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001742 }
Svetoslav683914b2015-01-15 14:22:26 -08001743 }
1744
Svetoslav7ec28e82015-05-20 17:01:10 -07001745 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001746 }
Svetoslav683914b2015-01-15 14:22:26 -08001747 }
1748
Billy Lau6ad2d662015-07-18 00:26:58 +01001749 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001750 // Write secure settings is a more protected permission. If caller has it we are good.
1751 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1752 == PackageManager.PERMISSION_GRANTED) {
1753 return true;
1754 }
1755
Svetoslavf41334b2015-06-23 12:06:03 -07001756 return false;
1757 }
1758
Svetoslav683914b2015-01-15 14:22:26 -08001759 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001760 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001761 if (validator != null && !validator.validate(value)) {
1762 throw new IllegalArgumentException("Invalid value: " + value
1763 + " for setting: " + name);
1764 }
1765 }
1766
Alex Klyubin1991f572017-03-03 14:08:36 -08001767 /**
1768 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1769 */
1770 private boolean isSecureSettingAccessible(String name, int callingUserId,
1771 int owningUserId) {
1772 // Special case for location (sigh).
1773 // This check is not inside the name-based checks below because this method performs checks
1774 // only if the calling user ID is not the same as the owning user ID.
1775 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1776 return false;
1777 }
1778
1779 switch (name) {
1780 case "bluetooth_address":
1781 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1782 // address in this secure setting. Secure settings can normally be read by any app,
1783 // which thus enables them to bypass the recently introduced restrictions on access
1784 // to device identifiers.
1785 // To mitigate this we make this setting available only to callers privileged to see
1786 // this device's MAC addresses, same as through public API
1787 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1788 return getContext().checkCallingOrSelfPermission(
1789 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1790 default:
1791 return true;
1792 }
1793 }
1794
Svetoslav683914b2015-01-15 14:22:26 -08001795 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1796 int owningUserId) {
1797 // Optimization - location providers are restricted only for managed profiles.
1798 if (callingUserId == owningUserId) {
1799 return false;
1800 }
1801 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1802 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1803 new UserHandle(callingUserId))) {
1804 return true;
1805 }
1806 return false;
1807 }
1808
Svetoslav683914b2015-01-15 14:22:26 -08001809 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1810 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1811 }
1812
1813 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001814 final int parentId;
1815 // Resolves dependency if setting has a dependency and the calling user has a parent
1816 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1817 && (parentId = getGroupParentLocked(userId)) != userId) {
1818 // The setting has a dependency and the profile has a parent
1819 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001820 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1821 final long token = Binder.clearCallingIdentity();
1822 try {
1823 Setting settingObj = getSecureSetting(dependency, userId);
1824 if (settingObj != null && settingObj.getValue().equals("1")) {
1825 return parentId;
1826 }
1827 } finally {
1828 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001829 }
1830 }
Svetoslav683914b2015-01-15 14:22:26 -08001831 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1832 }
1833
1834 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1835 final int parentId = getGroupParentLocked(userId);
1836 if (parentId != userId && keys.contains(name)) {
1837 return parentId;
1838 }
1839 return userId;
1840 }
1841
Svetoslavf41334b2015-06-23 12:06:03 -07001842 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001843 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001844 // System/root/shell can mutate whatever secure settings they want.
1845 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001846 final int appId = UserHandle.getAppId(callingUid);
1847 if (appId == android.os.Process.SYSTEM_UID
1848 || appId == Process.SHELL_UID
1849 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001850 return;
1851 }
1852
1853 switch (operation) {
1854 case MUTATION_OPERATION_INSERT:
1855 // Insert updates.
1856 case MUTATION_OPERATION_UPDATE: {
1857 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1858 return;
1859 }
1860
1861 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001862 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001863
1864 // Privileged apps can do whatever they want.
1865 if ((packageInfo.applicationInfo.privateFlags
1866 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1867 return;
1868 }
1869
1870 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1871 packageInfo.applicationInfo.targetSdkVersion, name);
1872 } break;
1873
1874 case MUTATION_OPERATION_DELETE: {
1875 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1876 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1877 throw new IllegalArgumentException("You cannot delete system defined"
1878 + " secure settings.");
1879 }
1880
1881 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001882 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001883
1884 // Privileged apps can do whatever they want.
1885 if ((packageInfo.applicationInfo.privateFlags &
1886 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1887 return;
1888 }
1889
1890 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1891 packageInfo.applicationInfo.targetSdkVersion, name);
1892 } break;
1893 }
1894 }
1895
Todd Kennedybe0b8892017-02-15 14:13:52 -08001896 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001897 switch (settingsType) {
1898 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001899 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001900 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001901 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001902 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001903 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001904 default:
1905 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1906 }
1907 }
1908
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001909 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1910 switch (settingsType) {
1911 case SETTINGS_TYPE_GLOBAL:
1912 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1913 case SETTINGS_TYPE_SYSTEM:
1914 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1915 case SETTINGS_TYPE_SECURE:
1916 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1917 default:
1918 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1919 }
1920 }
1921
Andreas Gampeb58893072018-09-05 16:52:31 -07001922 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001923 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001924 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1925 // in the current form.
1926 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001927 }
1928
Chad Brubakera6830e72017-04-28 17:34:36 -07001929 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001930 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1931 return;
1932 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001933 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001934 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001935 return;
1936 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001937 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1938 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001939 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1940 // breakage in the current form.
1941 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1942 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001943 }
1944 }
1945
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001946 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1947 // We always use the callingUid for this lookup. This means that if hypothetically an
1948 // app was installed in user A with cross user and in user B as an Instant App
1949 // the app in A would be able to see all the settings in user B. However since cross
1950 // user is a system permission and the app must be uninstalled in B and then installed as
1951 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001952 ApplicationInfo ai = null;
1953 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001954 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1955 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001956 } catch (RemoteException ignored) {
1957 }
1958 if (ai == null) {
1959 throw new IllegalStateException("Failed to lookup info for package "
1960 + getCallingPackage());
1961 }
1962 return ai;
1963 }
1964
Xiaohui Chen43765b72015-08-31 10:57:33 -07001965 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001966 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001967 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1968 getCallingPackage(), 0, userId);
1969 if (packageInfo != null) {
1970 return packageInfo;
1971 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001972 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001973 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001974 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001975 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001976 }
1977
1978 private int getGroupParentLocked(int userId) {
1979 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001980 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001981 return userId;
1982 }
1983 // We are in the same process with the user manager and the returned
1984 // user info is a cached instance, so just look up instead of cache.
1985 final long identity = Binder.clearCallingIdentity();
1986 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001987 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001988 UserInfo userInfo = mUserManager.getProfileParent(userId);
1989 return (userInfo != null) ? userInfo.id : userId;
1990 } finally {
1991 Binder.restoreCallingIdentity(identity);
1992 }
1993 }
1994
Svetoslav683914b2015-01-15 14:22:26 -08001995 private void enforceWritePermission(String permission) {
1996 if (getContext().checkCallingOrSelfPermission(permission)
1997 != PackageManager.PERMISSION_GRANTED) {
1998 throw new SecurityException("Permission denial: writing to settings requires:"
1999 + permission);
2000 }
2001 }
2002
2003 /*
2004 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2005 * This setting contains a list of the currently enabled location providers.
2006 * But helper functions in android.providers.Settings can enable or disable
2007 * a single provider by using a "+" or "-" prefix before the provider name.
2008 *
yuemingw1d13eae2018-01-30 17:27:54 +00002009 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2010 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2011 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002012 *
Svetoslav683914b2015-01-15 14:22:26 -08002013 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002014 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002015 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002016 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2017 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002018 if (TextUtils.isEmpty(value)) {
2019 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002020 }
Maggie83e03f52018-03-16 12:22:20 -07002021 Setting oldSetting = getSecureSetting(
2022 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2023 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002024 return false;
2025 }
Maggie83e03f52018-03-16 12:22:20 -07002026 String oldProviders = oldSetting.getValue();
2027 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2028 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2029 Set<String> newProvidersSet = new ArraySet<>();
2030 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002031
Maggie83e03f52018-03-16 12:22:20 -07002032 String[] providerUpdates = value.split(",");
2033 boolean inputError = false;
2034 for (String provider : providerUpdates) {
2035 // do not update location_providers_allowed when input is invalid
2036 if (TextUtils.isEmpty(provider)) {
2037 inputError = true;
2038 break;
Svetoslav683914b2015-01-15 14:22:26 -08002039 }
Maggie83e03f52018-03-16 12:22:20 -07002040 final char prefix = provider.charAt(0);
2041 // do not update location_providers_allowed when input is invalid
2042 if (prefix != '+' && prefix != '-') {
2043 inputError = true;
2044 break;
Svetoslav683914b2015-01-15 14:22:26 -08002045 }
Maggie83e03f52018-03-16 12:22:20 -07002046 // skip prefix
2047 provider = provider.substring(1);
2048 if (prefix == '+') {
2049 newProvidersSet.add(provider);
2050 } else if (prefix == '-') {
2051 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002052 }
Maggie83e03f52018-03-16 12:22:20 -07002053 }
2054 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2055 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002056 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002057 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002058 mSettingsRegistry.notifyForSettingsChange(
2059 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002060 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2061 }
Svetoslav683914b2015-01-15 14:22:26 -08002062 return false;
2063 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002064 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002065 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2066 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002067 }
2068
Svetoslav683914b2015-01-15 14:22:26 -08002069 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2070 int targetSdkVersion, String name) {
2071 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2072 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2073 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2074 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2075 + " This will soon become an error.");
2076 } else {
2077 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2078 + " This will soon become an error.");
2079 }
2080 } else {
2081 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2082 throw new IllegalArgumentException("You cannot change private secure settings.");
2083 } else {
2084 throw new IllegalArgumentException("You cannot keep your settings in"
2085 + " the secure settings.");
2086 }
2087 }
2088 }
2089
2090 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2091 if (requestingUserId == UserHandle.getCallingUserId()) {
2092 return requestingUserId;
2093 }
2094 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2095 Binder.getCallingUid(), requestingUserId, false, true,
2096 "get/set setting for user", null);
2097 }
2098
Svet Ganov53a441c2016-04-19 19:38:00 -07002099 private Bundle packageValueForCallResult(Setting setting,
2100 boolean trackingGeneration) {
2101 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002102 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002103 return NULL_SETTING_BUNDLE;
2104 }
2105 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002106 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002107 Bundle result = new Bundle();
2108 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002109 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002110
Svetoslav Ganove080da92016-12-21 17:10:35 -08002111 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002112 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002113 }
2114
2115 private static int getRequestingUserId(Bundle args) {
2116 final int callingUserId = UserHandle.getCallingUserId();
2117 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2118 : callingUserId;
2119 }
2120
Svet Ganov53a441c2016-04-19 19:38:00 -07002121 private boolean isTrackingGeneration(Bundle args) {
2122 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2123 }
2124
Svetoslav683914b2015-01-15 14:22:26 -08002125 private static String getSettingValue(Bundle args) {
2126 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2127 }
2128
Svetoslav Ganove080da92016-12-21 17:10:35 -08002129 private static String getSettingTag(Bundle args) {
2130 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2131 }
2132
Matt Pape6bfc62e2018-11-28 13:16:03 -08002133 private static String getSettingPrefix(Bundle args) {
2134 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2135 // Append '/' to ensure we only match properties with this exact prefix.
2136 // i.e. "foo" should match "foo/property" but not "foobar/property"
2137 return prefix != null ? prefix + "/" : null;
2138 }
2139
Svetoslav Ganove080da92016-12-21 17:10:35 -08002140 private static boolean getSettingMakeDefault(Bundle args) {
2141 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2142 }
2143
2144 private static int getResetModeEnforcingPermission(Bundle args) {
2145 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2146 switch (mode) {
2147 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2148 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2149 throw new SecurityException("Only system, shell/root on a "
2150 + "debuggable build can reset to untrusted defaults");
2151 }
2152 return mode;
2153 }
2154 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2155 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2156 throw new SecurityException("Only system, shell/root on a "
2157 + "debuggable build can reset untrusted changes");
2158 }
2159 return mode;
2160 }
2161 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2162 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2163 throw new SecurityException("Only system, shell/root on a "
2164 + "debuggable build can reset to trusted defaults");
2165 }
2166 return mode;
2167 }
2168 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2169 return mode;
2170 }
2171 }
2172 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2173 }
2174
2175 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2176 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2177 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2178 && (appId == SHELL_UID || appId == ROOT_UID));
2179 }
2180
Svetoslav683914b2015-01-15 14:22:26 -08002181 private static String getValidTableOrThrow(Uri uri) {
2182 if (uri.getPathSegments().size() > 0) {
2183 String table = uri.getPathSegments().get(0);
2184 if (DatabaseHelper.isValidTable(table)) {
2185 return table;
2186 }
2187 throw new IllegalArgumentException("Bad root path: " + table);
2188 }
2189 throw new IllegalArgumentException("Invalid URI:" + uri);
2190 }
2191
2192 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002193 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002194 return new MatrixCursor(projection, 0);
2195 }
2196 MatrixCursor cursor = new MatrixCursor(projection, 1);
2197 appendSettingToCursor(cursor, setting);
2198 return cursor;
2199 }
2200
2201 private static String[] normalizeProjection(String[] projection) {
2202 if (projection == null) {
2203 return ALL_COLUMNS;
2204 }
2205
2206 final int columnCount = projection.length;
2207 for (int i = 0; i < columnCount; i++) {
2208 String column = projection[i];
2209 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2210 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002211 }
2212 }
2213
Svetoslav683914b2015-01-15 14:22:26 -08002214 return projection;
2215 }
2216
2217 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002218 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002219 return;
2220 }
Svetoslav683914b2015-01-15 14:22:26 -08002221 final int columnCount = cursor.getColumnCount();
2222
2223 String[] values = new String[columnCount];
2224
2225 for (int i = 0; i < columnCount; i++) {
2226 String column = cursor.getColumnName(i);
2227
2228 switch (column) {
2229 case Settings.NameValueTable._ID: {
2230 values[i] = setting.getId();
2231 } break;
2232
2233 case Settings.NameValueTable.NAME: {
2234 values[i] = setting.getName();
2235 } break;
2236
2237 case Settings.NameValueTable.VALUE: {
2238 values[i] = setting.getValue();
2239 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002240 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002241 }
2242
Svetoslav683914b2015-01-15 14:22:26 -08002243 cursor.addRow(values);
2244 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002245
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002246 private static boolean isKeyValid(String key) {
2247 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2248 }
2249
Svetoslav683914b2015-01-15 14:22:26 -08002250 private static final class Arguments {
2251 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2252 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2253
2254 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2255 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2256
2257 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2258 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2259
2260 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2261 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2262
2263 public final String table;
2264 public final String name;
2265
2266 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2267 final int segmentSize = uri.getPathSegments().size();
2268 switch (segmentSize) {
2269 case 1: {
2270 if (where != null
2271 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2272 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2273 && whereArgs.length == 1) {
2274 name = whereArgs[0];
2275 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002276 return;
Svetoslav683914b2015-01-15 14:22:26 -08002277 } else if (where != null
2278 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2279 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2280 final int startIndex = Math.max(where.indexOf("'"),
2281 where.indexOf("\"")) + 1;
2282 final int endIndex = Math.max(where.lastIndexOf("'"),
2283 where.lastIndexOf("\""));
2284 name = where.substring(startIndex, endIndex);
2285 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002286 return;
Svetoslav683914b2015-01-15 14:22:26 -08002287 } else if (supportAll && where == null && whereArgs == null) {
2288 name = null;
2289 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002290 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002291 }
Svetoslav683914b2015-01-15 14:22:26 -08002292 } break;
2293
Svetoslav28494652015-02-12 14:11:42 -08002294 case 2: {
2295 if (where == null && whereArgs == null) {
2296 name = uri.getPathSegments().get(1);
2297 table = computeTableForSetting(uri, name);
2298 return;
2299 }
2300 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002301 }
Svetoslav28494652015-02-12 14:11:42 -08002302
2303 EventLogTags.writeUnsupportedSettingsQuery(
2304 uri.toSafeString(), where, Arrays.toString(whereArgs));
2305 String message = String.format( "Supported SQL:\n"
2306 + " uri content://some_table/some_property with null where and where args\n"
2307 + " uri content://some_table with query name=? and single name as arg\n"
2308 + " uri content://some_table with query name=some_name and null args\n"
2309 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2310 Arrays.toString(whereArgs));
2311 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002312 }
2313
Svetoslav28494652015-02-12 14:11:42 -08002314 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002315 String table = getValidTableOrThrow(uri);
2316
2317 if (name != null) {
2318 if (sSystemMovedToSecureSettings.contains(name)) {
2319 table = TABLE_SECURE;
2320 }
2321
2322 if (sSystemMovedToGlobalSettings.contains(name)) {
2323 table = TABLE_GLOBAL;
2324 }
2325
2326 if (sSecureMovedToGlobalSettings.contains(name)) {
2327 table = TABLE_GLOBAL;
2328 }
2329
2330 if (sGlobalMovedToSecureSettings.contains(name)) {
2331 table = TABLE_SECURE;
2332 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002333 }
Svetoslav683914b2015-01-15 14:22:26 -08002334
2335 return table;
2336 }
2337 }
2338
2339 final class SettingsRegistry {
2340 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2341
Svetoslav683914b2015-01-15 14:22:26 -08002342 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2343 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2344 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002345 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002346 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002347
2348 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002349
2350 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2351
Svet Ganov53a441c2016-04-19 19:38:00 -07002352 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002353
Svetoslav7e0683b2015-08-03 16:02:52 -07002354 private final Handler mHandler;
2355
Svet Ganov53a441c2016-04-19 19:38:00 -07002356 private final BackupManager mBackupManager;
2357
Amith Yamasani39452022017-03-21 15:23:47 -07002358 private String mSettingsCreationBuildId;
2359
Svetoslav683914b2015-01-15 14:22:26 -08002360 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002361 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002362 mGenerationRegistry = new GenerationRegistry(mLock);
2363 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002364 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002365 syncSsaidTableOnStart();
2366 }
2367
2368 private void generateUserKeyLocked(int userId) {
2369 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002370 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002371 final SecureRandom rand = new SecureRandom();
2372 rand.nextBytes(keyBytes);
2373
2374 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002375 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002376
2377 // Store the key in the ssaid table.
2378 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2379 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2380 true, SettingsState.SYSTEM_PACKAGE_NAME);
2381
2382 if (!success) {
2383 throw new IllegalStateException("Ssaid settings not accessible");
2384 }
2385 }
2386
Mark Rathjen7599f132017-01-23 14:15:54 -08002387 private byte[] getLengthPrefix(byte[] data) {
2388 return ByteBuffer.allocate(4).putInt(data.length).array();
2389 }
2390
Christopher Tateb218e762017-04-05 16:34:07 -07002391 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002392 // Read the user's key from the ssaid table.
2393 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002394 if (userKeySetting == null || userKeySetting.isNull()
2395 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002396 // Lazy initialize and store the user key.
2397 generateUserKeyLocked(userId);
2398 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002399 if (userKeySetting == null || userKeySetting.isNull()
2400 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002401 throw new IllegalStateException("User key not accessible");
2402 }
2403 }
2404 final String userKey = userKeySetting.getValue();
2405
2406 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002407 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2408
2409 // Validate that the key is of expected length.
2410 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2411 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002412 throw new IllegalStateException("User key invalid");
2413 }
2414
Mark Rathjen7599f132017-01-23 14:15:54 -08002415 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002416 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002417 m = Mac.getInstance("HmacSHA256");
2418 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002419 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002420 throw new IllegalStateException("HmacSHA256 is not available", e);
2421 } catch (InvalidKeyException e) {
2422 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002423 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002424
Mark Rathjenf42dd912017-06-05 19:04:34 -07002425 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002426 for (int i = 0; i < callingPkg.signatures.length; i++) {
2427 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002428 m.update(getLengthPrefix(sig), 0, 4);
2429 m.update(sig);
2430 }
Mark Rathjend891f012017-01-19 04:10:37 +00002431
2432 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002433 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2434 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002435
2436 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002437 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002438 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2439 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002440 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002441
2442 if (!success) {
2443 throw new IllegalStateException("Ssaid settings not accessible");
2444 }
2445
2446 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2447 }
2448
2449 public void syncSsaidTableOnStart() {
2450 synchronized (mLock) {
2451 // Verify that each user's packages and ssaid's are in sync.
2452 for (UserInfo user : mUserManager.getUsers(true)) {
2453 // Get all uids for the user's packages.
2454 final List<PackageInfo> packages;
2455 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002456 packages = mPackageManager.getInstalledPackages(
2457 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2458 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002459 } catch (RemoteException e) {
2460 throw new IllegalStateException("Package manager not available");
2461 }
2462 final Set<String> appUids = new HashSet<>();
2463 for (PackageInfo info : packages) {
2464 appUids.add(Integer.toString(info.applicationInfo.uid));
2465 }
2466
2467 // Get all uids currently stored in the user's ssaid table.
2468 final Set<String> ssaidUids = new HashSet<>(
2469 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2470 ssaidUids.remove(SSAID_USER_KEY);
2471
2472 // Perform a set difference for the appUids and ssaidUids.
2473 ssaidUids.removeAll(appUids);
2474
2475 // If there are ssaidUids left over they need to be removed from the table.
2476 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2477 user.id);
2478 for (String uid : ssaidUids) {
2479 ssaidSettings.deleteSettingLocked(uid);
2480 }
2481 }
2482 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002483 }
2484
Svetoslav683914b2015-01-15 14:22:26 -08002485 public List<String> getSettingsNamesLocked(int type, int userId) {
2486 final int key = makeKey(type, userId);
2487 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002488 if (settingsState == null) {
2489 return new ArrayList<String>();
2490 }
Svetoslav683914b2015-01-15 14:22:26 -08002491 return settingsState.getSettingNamesLocked();
2492 }
2493
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002494 public SparseBooleanArray getKnownUsersLocked() {
2495 SparseBooleanArray users = new SparseBooleanArray();
2496 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2497 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2498 }
2499 return users;
2500 }
2501
Kweku Adamsb0886f32017-10-31 15:32:09 -07002502 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002503 public SettingsState getSettingsLocked(int type, int userId) {
2504 final int key = makeKey(type, userId);
2505 return peekSettingsStateLocked(key);
2506 }
2507
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002508 public boolean ensureSettingsForUserLocked(int userId) {
2509 // First make sure this user actually exists.
2510 if (mUserManager.getUserInfo(userId) == null) {
2511 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2512 return false;
2513 }
2514
Svetoslav683914b2015-01-15 14:22:26 -08002515 // Migrate the setting for this user if needed.
2516 migrateLegacySettingsForUserIfNeededLocked(userId);
2517
Matt Pape1b31a332018-10-17 09:58:28 -07002518 // Ensure config settings loaded if owner.
2519 if (userId == UserHandle.USER_SYSTEM) {
2520 final int configKey
2521 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2522 ensureSettingsStateLocked(configKey);
2523 }
2524
Svetoslav683914b2015-01-15 14:22:26 -08002525 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002526 if (userId == UserHandle.USER_SYSTEM) {
2527 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002528 ensureSettingsStateLocked(globalKey);
2529 }
2530
2531 // Ensure secure settings loaded.
2532 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2533 ensureSettingsStateLocked(secureKey);
2534
2535 // Make sure the secure settings have an Android id set.
2536 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2537 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2538
2539 // Ensure system settings loaded.
2540 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2541 ensureSettingsStateLocked(systemKey);
2542
Mark Rathjend891f012017-01-19 04:10:37 +00002543 // Ensure secure settings loaded.
2544 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2545 ensureSettingsStateLocked(ssaidKey);
2546
Svetoslav683914b2015-01-15 14:22:26 -08002547 // Upgrade the settings to the latest version.
2548 UpgradeController upgrader = new UpgradeController(userId);
2549 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002550 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002551 }
2552
2553 private void ensureSettingsStateLocked(int key) {
2554 if (mSettingsStates.get(key) == null) {
2555 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002556 SettingsState settingsState = new SettingsState(getContext(), mLock,
2557 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002558 mSettingsStates.put(key, settingsState);
2559 }
2560 }
2561
2562 public void removeUserStateLocked(int userId, boolean permanently) {
2563 // We always keep the global settings in memory.
2564
2565 // Nuke system settings.
2566 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2567 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2568 if (systemSettingsState != null) {
2569 if (permanently) {
2570 mSettingsStates.remove(systemKey);
2571 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002572 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002573 systemSettingsState.destroyLocked(new Runnable() {
2574 @Override
2575 public void run() {
2576 mSettingsStates.remove(systemKey);
2577 }
2578 });
2579 }
2580 }
2581
2582 // Nuke secure settings.
2583 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2584 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2585 if (secureSettingsState != null) {
2586 if (permanently) {
2587 mSettingsStates.remove(secureKey);
2588 secureSettingsState.destroyLocked(null);
2589 } else {
2590 secureSettingsState.destroyLocked(new Runnable() {
2591 @Override
2592 public void run() {
2593 mSettingsStates.remove(secureKey);
2594 }
2595 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002596 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002597 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002598
Mark Rathjend891f012017-01-19 04:10:37 +00002599 // Nuke ssaid settings.
2600 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2601 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2602 if (ssaidSettingsState != null) {
2603 if (permanently) {
2604 mSettingsStates.remove(ssaidKey);
2605 ssaidSettingsState.destroyLocked(null);
2606 } else {
2607 ssaidSettingsState.destroyLocked(new Runnable() {
2608 @Override
2609 public void run() {
2610 mSettingsStates.remove(ssaidKey);
2611 }
2612 });
2613 }
2614 }
2615
Svet Ganov53a441c2016-04-19 19:38:00 -07002616 // Nuke generation tracking data
2617 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002618 }
2619
Svetoslav683914b2015-01-15 14:22:26 -08002620 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002621 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2622 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002623 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2624 packageName, forceNotify, criticalSettings);
2625 }
2626
2627 public boolean insertSettingLocked(int type, int userId, String name, String value,
2628 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2629 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002630 final int key = makeKey(type, userId);
2631
Svetoslav Ganove080da92016-12-21 17:10:35 -08002632 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002633 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002634 if (settingsState != null) {
2635 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002636 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002637 }
Svetoslav683914b2015-01-15 14:22:26 -08002638
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002639 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2640 settingsState.persistSyncLocked();
2641 }
2642
Svet Ganov53a441c2016-04-19 19:38:00 -07002643 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002644 notifyForSettingsChange(key, name);
2645 }
2646 return success;
2647 }
2648
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002649 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2650 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002651 final int key = makeKey(type, userId);
2652
Svetoslav Ganove080da92016-12-21 17:10:35 -08002653 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002654 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002655 if (settingsState != null) {
2656 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002657 }
Svetoslav683914b2015-01-15 14:22:26 -08002658
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002659 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2660 settingsState.persistSyncLocked();
2661 }
2662
Svet Ganov53a441c2016-04-19 19:38:00 -07002663 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002664 notifyForSettingsChange(key, name);
2665 }
2666 return success;
2667 }
2668
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002669 public boolean updateSettingLocked(int type, int userId, String name, String value,
2670 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2671 Set<String> criticalSettings) {
2672 final int key = makeKey(type, userId);
2673
2674 boolean success = false;
2675 SettingsState settingsState = peekSettingsStateLocked(key);
2676 if (settingsState != null) {
2677 success = settingsState.updateSettingLocked(name, value, tag,
2678 makeDefault, packageName);
2679 }
2680
2681 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2682 settingsState.persistSyncLocked();
2683 }
2684
2685 if (forceNotify || success) {
2686 notifyForSettingsChange(key, name);
2687 }
2688
2689 return success;
2690 }
2691
Svetoslav683914b2015-01-15 14:22:26 -08002692 public Setting getSettingLocked(int type, int userId, String name) {
2693 final int key = makeKey(type, userId);
2694
2695 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002696 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002697 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002698 }
Mark Rathjend891f012017-01-19 04:10:37 +00002699
2700 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002701 return settingsState.getSettingLocked(name);
2702 }
2703
Svetoslav Ganove080da92016-12-21 17:10:35 -08002704 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2705 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002706 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2707 }
2708
2709 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2710 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002711 final int key = makeKey(type, userId);
2712 SettingsState settingsState = peekSettingsStateLocked(key);
2713 if (settingsState == null) {
2714 return;
2715 }
2716
2717 switch (mode) {
2718 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2719 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002720 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002721 Setting setting = settingsState.getSettingLocked(name);
2722 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002723 if ((tag != null && !tag.equals(setting.getTag()))
2724 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002725 continue;
2726 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002727 if (settingsState.resetSettingLocked(name)) {
2728 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002729 notifyForSettingsChange(key, name);
2730 }
2731 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002732 if (someSettingChanged) {
2733 settingsState.persistSyncLocked();
2734 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002735 }
2736 } break;
2737
2738 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2739 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002740 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002741 Setting setting = settingsState.getSettingLocked(name);
2742 if (!SettingsState.isSystemPackage(getContext(),
2743 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002744 if (prefix != null && !setting.getName().startsWith(prefix)) {
2745 continue;
2746 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002747 if (settingsState.resetSettingLocked(name)) {
2748 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002749 notifyForSettingsChange(key, name);
2750 }
2751 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002752 if (someSettingChanged) {
2753 settingsState.persistSyncLocked();
2754 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002755 }
2756 } break;
2757
2758 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2759 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002760 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002761 Setting setting = settingsState.getSettingLocked(name);
2762 if (!SettingsState.isSystemPackage(getContext(),
2763 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002764 if (prefix != null && !setting.getName().startsWith(prefix)) {
2765 continue;
2766 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002767 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002768 if (settingsState.resetSettingLocked(name)) {
2769 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002770 notifyForSettingsChange(key, name);
2771 }
2772 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002773 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002774 notifyForSettingsChange(key, name);
2775 }
2776 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002777 if (someSettingChanged) {
2778 settingsState.persistSyncLocked();
2779 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002780 }
2781 } break;
2782
2783 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2784 for (String name : settingsState.getSettingNamesLocked()) {
2785 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002786 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002787 if (prefix != null && !setting.getName().startsWith(prefix)) {
2788 continue;
2789 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002790 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002791 if (settingsState.resetSettingLocked(name)) {
2792 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002793 notifyForSettingsChange(key, name);
2794 }
2795 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002796 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002797 notifyForSettingsChange(key, name);
2798 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002799 if (someSettingChanged) {
2800 settingsState.persistSyncLocked();
2801 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002802 }
2803 } break;
2804 }
2805 }
2806
Zimuzoc56192c2018-07-25 10:40:01 +01002807 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002808 // Global and secure settings are signature protected. Apps signed
2809 // by the platform certificate are generally not uninstalled and
2810 // the main exception is tests. We trust components signed
2811 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002812
2813 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2814 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002815 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002816 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002817 }
Svetoslav683914b2015-01-15 14:22:26 -08002818 }
2819
Mark Rathjend891f012017-01-19 04:10:37 +00002820 public void onUidRemovedLocked(int uid) {
2821 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2822 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002823 if (ssaidSettings != null) {
2824 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2825 }
Mark Rathjend891f012017-01-19 04:10:37 +00002826 }
2827
Kweku Adamsb0886f32017-10-31 15:32:09 -07002828 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002829 private SettingsState peekSettingsStateLocked(int key) {
2830 SettingsState settingsState = mSettingsStates.get(key);
2831 if (settingsState != null) {
2832 return settingsState;
2833 }
2834
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002835 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2836 return null;
2837 }
Svetoslav683914b2015-01-15 14:22:26 -08002838 return mSettingsStates.get(key);
2839 }
2840
2841 private void migrateAllLegacySettingsIfNeeded() {
2842 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002843 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002844 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002845 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002846 return;
2847 }
2848
Amith Yamasani39452022017-03-21 15:23:47 -07002849 mSettingsCreationBuildId = Build.ID;
2850
Svetoslav683914b2015-01-15 14:22:26 -08002851 final long identity = Binder.clearCallingIdentity();
2852 try {
2853 List<UserInfo> users = mUserManager.getUsers(true);
2854
2855 final int userCount = users.size();
2856 for (int i = 0; i < userCount; i++) {
2857 final int userId = users.get(i).id;
2858
2859 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2860 SQLiteDatabase database = dbHelper.getWritableDatabase();
2861 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2862
2863 // Upgrade to the latest version.
2864 UpgradeController upgrader = new UpgradeController(userId);
2865 upgrader.upgradeIfNeededLocked();
2866
2867 // Drop from memory if not a running user.
2868 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2869 removeUserStateLocked(userId, false);
2870 }
2871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(identity);
2874 }
2875 }
2876 }
2877
2878 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2879 // Every user has secure settings and if no file we need to migrate.
2880 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2881 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002882 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002883 return;
2884 }
2885
2886 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2887 SQLiteDatabase database = dbHelper.getWritableDatabase();
2888
2889 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2890 }
2891
2892 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2893 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002894 // Move over the system settings.
2895 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2896 ensureSettingsStateLocked(systemKey);
2897 SettingsState systemSettings = mSettingsStates.get(systemKey);
2898 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2899 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002900
2901 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002902 // Do this after System settings, since this is the first thing we check when deciding
2903 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002904 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2905 ensureSettingsStateLocked(secureKey);
2906 SettingsState secureSettings = mSettingsStates.get(secureKey);
2907 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2908 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2909 secureSettings.persistSyncLocked();
2910
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002911 // Move over the global settings if owner.
2912 // Do this last, since this is the first thing we check when deciding
2913 // to skip over migration from db to xml for owner user.
2914 if (userId == UserHandle.USER_SYSTEM) {
2915 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2916 ensureSettingsStateLocked(globalKey);
2917 SettingsState globalSettings = mSettingsStates.get(globalKey);
2918 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002919 // If this was just created
2920 if (mSettingsCreationBuildId != null) {
2921 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2922 mSettingsCreationBuildId, null, true,
2923 SettingsState.SYSTEM_PACKAGE_NAME);
2924 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002925 globalSettings.persistSyncLocked();
2926 }
Svetoslav683914b2015-01-15 14:22:26 -08002927
2928 // Drop the database as now all is moved and persisted.
2929 if (DROP_DATABASE_ON_MIGRATION) {
2930 dbHelper.dropDatabase();
2931 } else {
2932 dbHelper.backupDatabase();
2933 }
2934 }
2935
2936 private void migrateLegacySettingsLocked(SettingsState settingsState,
2937 SQLiteDatabase database, String table) {
2938 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2939 queryBuilder.setTables(table);
2940
2941 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2942 null, null, null, null, null);
2943
2944 if (cursor == null) {
2945 return;
2946 }
2947
2948 try {
2949 if (!cursor.moveToFirst()) {
2950 return;
2951 }
2952
2953 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2954 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2955
2956 settingsState.setVersionLocked(database.getVersion());
2957
2958 while (!cursor.isAfterLast()) {
2959 String name = cursor.getString(nameColumnIdx);
2960 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002961 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002962 SettingsState.SYSTEM_PACKAGE_NAME);
2963 cursor.moveToNext();
2964 }
2965 } finally {
2966 cursor.close();
2967 }
2968 }
2969
Andreas Gampeb58893072018-09-05 16:52:31 -07002970 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002971 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2972 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2973
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002974 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002975 return;
2976 }
2977
2978 final int userId = getUserIdFromKey(secureSettings.mKey);
2979
2980 final UserInfo user;
2981 final long identity = Binder.clearCallingIdentity();
2982 try {
2983 user = mUserManager.getUserInfo(userId);
2984 } finally {
2985 Binder.restoreCallingIdentity(identity);
2986 }
2987 if (user == null) {
2988 // Can happen due to races when deleting users - treat as benign.
2989 return;
2990 }
2991
2992 String androidId = Long.toHexString(new SecureRandom().nextLong());
2993 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002994 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002995
2996 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2997 + "] for user " + userId);
2998
2999 // Write a drop box entry if it's a restricted profile
3000 if (user.isRestricted()) {
3001 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3002 Context.DROPBOX_SERVICE);
3003 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3004 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3005 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3006 }
3007 }
3008 }
3009
3010 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003011 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003012 mGenerationRegistry.incrementGeneration(key);
3013
Svet Ganov945864c2018-03-22 21:49:10 -07003014 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003015 final long token = Binder.clearCallingIdentity();
3016 try {
3017 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3018 // When the global kill switch is updated, send the
3019 // change notification for the location setting.
3020 notifyLocationChangeForRunningUsers();
3021 }
3022 notifyGlobalSettingChangeForRunningUsers(key, name);
3023 } finally {
3024 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003025 }
Svet Ganov945864c2018-03-22 21:49:10 -07003026 } else {
3027 final int userId = getUserIdFromKey(key);
3028 final Uri uri = getNotificationUriFor(key, name);
3029 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3030 userId, 0, uri).sendToTarget();
3031 if (isSecureSettingsKey(key)) {
3032 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3033 sSecureCloneToManagedSettings);
3034 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3035 sSystemCloneFromParentOnDependency.values());
3036 } else if (isSystemSettingsKey(key)) {
3037 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3038 sSystemCloneToManagedSettings);
3039 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003040 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003041
Svet Ganov945864c2018-03-22 21:49:10 -07003042 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003043 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003044 }
3045
Svet Ganov53a441c2016-04-19 19:38:00 -07003046 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003047 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003048 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003049 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003050 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003051 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003052 final int key = makeKey(type, profileId);
3053 // Increment the generation first, so observers always see the new value
3054 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003055 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003056 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003057 }
3058 }
3059 }
Svetoslav683914b2015-01-15 14:22:26 -08003060 }
3061
Svet Ganov945864c2018-03-22 21:49:10 -07003062 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3063 // Important: No need to update generation for each user as there
3064 // is a singleton generation entry for the global settings which
3065 // is already incremented be the caller.
3066 final Uri uri = getNotificationUriFor(key, name);
3067 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3068 for (int i = 0; i < users.size(); i++) {
3069 final int userId = users.get(i).id;
3070 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3071 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3072 userId, 0, uri).sendToTarget();
3073 }
3074 }
3075 }
3076
Makoto Onuki0000d322017-11-28 16:31:47 -08003077 private void notifyLocationChangeForRunningUsers() {
3078 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3079
3080 for (int i = 0; i < users.size(); i++) {
3081 final int userId = users.get(i).id;
3082
3083 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3084 continue;
3085 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003086
Svet Ganov945864c2018-03-22 21:49:10 -07003087 // Increment the generation first, so observers always see the new value
3088 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3089 mGenerationRegistry.incrementGeneration(key);
3090
3091 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003092 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3093 userId, 0, uri).sendToTarget();
3094 }
3095 }
3096
Matt Pape1b31a332018-10-17 09:58:28 -07003097 private boolean isConfigSettingsKey(int key) {
3098 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3099 }
3100
Svetoslav683914b2015-01-15 14:22:26 -08003101 private boolean isGlobalSettingsKey(int key) {
3102 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3103 }
3104
3105 private boolean isSystemSettingsKey(int key) {
3106 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3107 }
3108
3109 private boolean isSecureSettingsKey(int key) {
3110 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3111 }
3112
Mark Rathjend891f012017-01-19 04:10:37 +00003113 private boolean isSsaidSettingsKey(int key) {
3114 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3115 }
3116
Svetoslav683914b2015-01-15 14:22:26 -08003117 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003118 if (isConfigSettingsKey(key)) {
3119 final int userId = getUserIdFromKey(key);
3120 return new File(Environment.getUserSystemDirectory(userId),
3121 SETTINGS_FILE_CONFIG);
3122 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003123 final int userId = getUserIdFromKey(key);
3124 return new File(Environment.getUserSystemDirectory(userId),
3125 SETTINGS_FILE_GLOBAL);
3126 } else if (isSystemSettingsKey(key)) {
3127 final int userId = getUserIdFromKey(key);
3128 return new File(Environment.getUserSystemDirectory(userId),
3129 SETTINGS_FILE_SYSTEM);
3130 } else if (isSecureSettingsKey(key)) {
3131 final int userId = getUserIdFromKey(key);
3132 return new File(Environment.getUserSystemDirectory(userId),
3133 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003134 } else if (isSsaidSettingsKey(key)) {
3135 final int userId = getUserIdFromKey(key);
3136 return new File(Environment.getUserSystemDirectory(userId),
3137 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003138 } else {
3139 throw new IllegalArgumentException("Invalid settings key:" + key);
3140 }
3141 }
3142
3143 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003144 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003145 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3146 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003147 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003148 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3149 : Settings.Global.CONTENT_URI;
3150 } else if (isSecureSettingsKey(key)) {
3151 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3152 : Settings.Secure.CONTENT_URI;
3153 } else if (isSystemSettingsKey(key)) {
3154 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3155 : Settings.System.CONTENT_URI;
3156 } else {
3157 throw new IllegalArgumentException("Invalid settings key:" + key);
3158 }
3159 }
3160
3161 private int getMaxBytesPerPackageForType(int type) {
3162 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003163 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003164 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003165 case SETTINGS_TYPE_SECURE:
3166 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003167 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3168 }
3169
3170 default: {
3171 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3172 }
3173 }
3174 }
3175
Svetoslav7e0683b2015-08-03 16:02:52 -07003176 private final class MyHandler extends Handler {
3177 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3178 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3179
3180 public MyHandler(Looper looper) {
3181 super(looper);
3182 }
3183
3184 @Override
3185 public void handleMessage(Message msg) {
3186 switch (msg.what) {
3187 case MSG_NOTIFY_URI_CHANGED: {
3188 final int userId = msg.arg1;
3189 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003190 try {
3191 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3192 } catch (SecurityException e) {
3193 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3194 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003195 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003196 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3197 }
3198 } break;
3199
3200 case MSG_NOTIFY_DATA_CHANGED: {
3201 mBackupManager.dataChanged();
3202 } break;
3203 }
3204 }
3205 }
3206
Svetoslav683914b2015-01-15 14:22:26 -08003207 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003208 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003209
3210 private final int mUserId;
3211
3212 public UpgradeController(int userId) {
3213 mUserId = userId;
3214 }
3215
3216 public void upgradeIfNeededLocked() {
3217 // The version of all settings for a user is the same (all users have secure).
3218 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003219 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003220
3221 // Try an update from the current state.
3222 final int oldVersion = secureSettings.getVersionLocked();
3223 final int newVersion = SETTINGS_VERSION;
3224
Svet Ganovc9755bc2015-03-28 13:21:22 -07003225 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003226 if (oldVersion == newVersion) {
3227 return;
3228 }
3229
3230 // Try to upgrade.
3231 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3232
3233 // If upgrade failed start from scratch and upgrade.
3234 if (curVersion != newVersion) {
3235 // Drop state we have for this user.
3236 removeUserStateLocked(mUserId, true);
3237
3238 // Recreate the database.
3239 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3240 SQLiteDatabase database = dbHelper.getWritableDatabase();
3241 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3242
3243 // Migrate the settings for this user.
3244 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3245
3246 // Now upgrade should work fine.
3247 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003248
3249 // Make a note what happened, so we don't wonder why data was lost
3250 String reason = "Settings rebuilt! Current version: "
3251 + curVersion + " while expected: " + newVersion;
3252 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003253 Settings.Global.DATABASE_DOWNGRADE_REASON,
3254 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003255 }
3256
3257 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003258 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003259 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003260 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003261 globalSettings.setVersionLocked(newVersion);
3262 }
3263
3264 // Set the secure settings version.
3265 secureSettings.setVersionLocked(newVersion);
3266
3267 // Set the system settings version.
3268 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003269 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003270 systemSettings.setVersionLocked(newVersion);
3271 }
3272
3273 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003274 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003275 }
3276
3277 private SettingsState getSecureSettingsLocked(int userId) {
3278 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3279 }
3280
Mark Rathjend891f012017-01-19 04:10:37 +00003281 private SettingsState getSsaidSettingsLocked(int userId) {
3282 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3283 }
3284
Svetoslav683914b2015-01-15 14:22:26 -08003285 private SettingsState getSystemSettingsLocked(int userId) {
3286 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3287 }
3288
Jeff Brown503cffc2015-03-26 18:08:51 -07003289 /**
3290 * You must perform all necessary mutations to bring the settings
3291 * for this user from the old to the new version. When you add a new
3292 * upgrade step you *must* update SETTINGS_VERSION.
3293 *
3294 * This is an example of moving a setting from secure to global.
3295 *
3296 * // v119: Example settings changes.
3297 * if (currentVersion == 118) {
3298 * if (userId == UserHandle.USER_OWNER) {
3299 * // Remove from the secure settings.
3300 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3301 * String name = "example_setting_to_move";
3302 * String value = secureSettings.getSetting(name);
3303 * secureSettings.deleteSetting(name);
3304 *
3305 * // Add to the global settings.
3306 * SettingsState globalSettings = getGlobalSettingsLocked();
3307 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3308 * }
3309 *
3310 * // Update the current version.
3311 * currentVersion = 119;
3312 * }
3313 */
Svetoslav683914b2015-01-15 14:22:26 -08003314 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3315 if (DEBUG) {
3316 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3317 + oldVersion + " to version: " + newVersion);
3318 }
3319
Jeff Brown503cffc2015-03-26 18:08:51 -07003320 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003321
John Spurlocke11ae112015-05-11 16:09:03 -04003322 // v119: Reset zen + ringer mode.
3323 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003324 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003325 final SettingsState globalSettings = getGlobalSettingsLocked();
3326 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003327 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3328 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003329 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003330 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3331 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003332 }
3333 currentVersion = 119;
3334 }
3335
Jason Monk27bbb2d2015-03-31 16:46:39 -04003336 // v120: Add double tap to wake setting.
3337 if (currentVersion == 119) {
3338 SettingsState secureSettings = getSecureSettingsLocked(userId);
3339 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3340 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003341 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003342 SettingsState.SYSTEM_PACKAGE_NAME);
3343
3344 currentVersion = 120;
3345 }
3346
Svetoslav7e0683b2015-08-03 16:02:52 -07003347 if (currentVersion == 120) {
3348 // Before 121, we used a different string encoding logic. We just bump the
3349 // version here; SettingsState knows how to handle pre-version 120 files.
3350 currentVersion = 121;
3351 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003352
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003353 if (currentVersion == 121) {
3354 // Version 122: allow OEMs to set a default payment component in resources.
3355 // Note that we only write the default if no default has been set;
3356 // if there is, we just leave the default at whatever it currently is.
3357 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3358 String defaultComponent = (getContext().getResources().getString(
3359 R.string.def_nfc_payment_component));
3360 Setting currentSetting = secureSettings.getSettingLocked(
3361 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3362 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003363 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003364 secureSettings.insertSettingLocked(
3365 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003366 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003367 }
3368 currentVersion = 122;
3369 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003370
3371 if (currentVersion == 122) {
3372 // Version 123: Adding a default value for the ability to add a user from
3373 // the lock screen.
3374 if (userId == UserHandle.USER_SYSTEM) {
3375 final SettingsState globalSettings = getGlobalSettingsLocked();
3376 Setting currentSetting = globalSettings.getSettingLocked(
3377 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003378 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003379 globalSettings.insertSettingLocked(
3380 Settings.Global.ADD_USERS_WHEN_LOCKED,
3381 getContext().getResources().getBoolean(
3382 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003383 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003384 }
3385 }
3386 currentVersion = 123;
3387 }
Bryce Leebd179282015-12-17 19:01:37 -08003388
3389 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003390 final SettingsState globalSettings = getGlobalSettingsLocked();
3391 String defaultDisabledProfiles = (getContext().getResources().getString(
3392 R.string.def_bluetooth_disabled_profiles));
3393 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003394 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003395 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003396 }
3397
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003398 if (currentVersion == 124) {
3399 // Version 124: allow OEMs to set a default value for whether IME should be
3400 // shown when a physical keyboard is connected.
3401 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3402 Setting currentSetting = secureSettings.getSettingLocked(
3403 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003404 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003405 secureSettings.insertSettingLocked(
3406 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3407 getContext().getResources().getBoolean(
3408 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003409 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003410 }
3411 currentVersion = 125;
3412 }
3413
Ruben Brunk98576cf2016-03-07 18:54:28 -08003414 if (currentVersion == 125) {
3415 // Version 125: Allow OEMs to set the default VR service.
3416 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3417
3418 Setting currentSetting = secureSettings.getSettingLocked(
3419 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003420 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003421 ArraySet<ComponentName> l =
3422 SystemConfig.getInstance().getDefaultVrComponents();
3423
3424 if (l != null && !l.isEmpty()) {
3425 StringBuilder b = new StringBuilder();
3426 boolean start = true;
3427 for (ComponentName c : l) {
3428 if (!start) {
3429 b.append(':');
3430 }
3431 b.append(c.flattenToString());
3432 start = false;
3433 }
3434 secureSettings.insertSettingLocked(
3435 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003436 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003437 }
3438
3439 }
3440 currentVersion = 126;
3441 }
3442
Daniel U02ba6122016-04-01 18:41:42 +01003443 if (currentVersion == 126) {
3444 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3445 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3446 if (mUserManager.isManagedProfile(userId)) {
3447 final SettingsState systemSecureSettings =
3448 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3449
3450 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3451 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003452 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003453 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3454 secureSettings.insertSettingLocked(
3455 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003456 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003457 SettingsState.SYSTEM_PACKAGE_NAME);
3458 }
3459
3460 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3461 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003462 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003463 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3464 secureSettings.insertSettingLocked(
3465 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003466 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003467 SettingsState.SYSTEM_PACKAGE_NAME);
3468 }
3469 }
3470 currentVersion = 127;
3471 }
3472
Steven Ngdc20ba62016-04-26 18:19:04 +01003473 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003474 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003475 currentVersion = 128;
3476 }
3477
Julia Reynolds1f721e12016-07-11 08:50:58 -04003478 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003479 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003480 currentVersion = 129;
3481 }
3482
Dan Sandler71f85e92016-07-20 13:46:05 -04003483 if (currentVersion == 129) {
3484 // default longpress timeout changed from 500 to 400. If unchanged from the old
3485 // default, update to the new default.
3486 final SettingsState systemSecureSettings =
3487 getSecureSettingsLocked(userId);
3488 final String oldValue = systemSecureSettings.getSettingLocked(
3489 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3490 if (TextUtils.equals("500", oldValue)) {
3491 systemSecureSettings.insertSettingLocked(
3492 Settings.Secure.LONG_PRESS_TIMEOUT,
3493 String.valueOf(getContext().getResources().getInteger(
3494 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003495 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003496 }
3497 currentVersion = 130;
3498 }
3499
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003500 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003501 // Split Ambient settings
3502 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3503 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3504 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3505
3506 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003507 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003508 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003509 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003510 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003511 }
3512 currentVersion = 131;
3513 }
3514
3515 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003516 // Initialize new multi-press timeout to default value
3517 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3518 final String oldValue = systemSecureSettings.getSettingLocked(
3519 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3520 if (TextUtils.equals(null, oldValue)) {
3521 systemSecureSettings.insertSettingLocked(
3522 Settings.Secure.MULTI_PRESS_TIMEOUT,
3523 String.valueOf(getContext().getResources().getInteger(
3524 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003525 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003526 }
3527
Adrian Roos69741a22016-10-21 14:49:17 -07003528 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003529 }
3530
Adrian Roos69741a22016-10-21 14:49:17 -07003531 if (currentVersion == 132) {
3532 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003533 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3534 String defaultSyncParentSounds = (getContext().getResources()
3535 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3536 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003537 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3538 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003539 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003540 }
3541
Adrian Roos69741a22016-10-21 14:49:17 -07003542 if (currentVersion == 133) {
3543 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003544 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003545 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3546 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003547 String defaultEndButtonBehavior = Integer.toString(getContext()
3548 .getResources().getInteger(R.integer.def_end_button_behavior));
3549 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003550 defaultEndButtonBehavior, null, true,
3551 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003552 }
Adrian Roos69741a22016-10-21 14:49:17 -07003553 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003554 }
3555
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003556 if (currentVersion == 134) {
3557 // Remove setting that specifies if magnification values should be preserved.
3558 // This setting defaulted to true and never has a UI.
3559 getSecureSettingsLocked(userId).deleteSettingLocked(
3560 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3561 currentVersion = 135;
3562 }
3563
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003564 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003565 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003566 currentVersion = 136;
3567 }
3568
Mark Rathjend891f012017-01-19 04:10:37 +00003569 if (currentVersion == 136) {
3570 // Version 136: Store legacy SSAID for all apps currently installed on the
3571 // device as first step in migrating SSAID to be unique per application.
3572
3573 final boolean isUpgrade;
3574 try {
3575 isUpgrade = mPackageManager.isUpgrade();
3576 } catch (RemoteException e) {
3577 throw new IllegalStateException("Package manager not available");
3578 }
3579 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3580 // user data or first boot on a new device should use new ssaid generation.
3581 if (isUpgrade) {
3582 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003583 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3584 userId, Settings.Secure.ANDROID_ID);
3585 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3586 || legacySsaidSetting.getValue() == null) {
3587 throw new IllegalStateException("Legacy ssaid not accessible");
3588 }
3589 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003590
3591 // Fill each uid with the legacy ssaid to be backwards compatible.
3592 final List<PackageInfo> packages;
3593 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003594 packages = mPackageManager.getInstalledPackages(
3595 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3596 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003597 } catch (RemoteException e) {
3598 throw new IllegalStateException("Package manager not available");
3599 }
3600
3601 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3602 for (PackageInfo info : packages) {
3603 // Check if the UID already has an entry in the table.
3604 final String uid = Integer.toString(info.applicationInfo.uid);
3605 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3606
3607 if (ssaid.isNull() || ssaid.getValue() == null) {
3608 // Android Id doesn't exist for this package so create it.
3609 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3610 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003611 if (DEBUG) {
3612 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3613 }
Mark Rathjend891f012017-01-19 04:10:37 +00003614 }
3615 }
3616 }
3617
3618 currentVersion = 137;
3619 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003620 if (currentVersion == 137) {
3621 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3622 // default value set to 1. The user can no longer change the value of this
3623 // setting through the UI.
3624 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3625 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003626 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3627 && secureSetting.getSettingLocked(
3628 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3629
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003630 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3631 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003632 // For managed profiles with profile owners, DevicePolicyManagerService
3633 // may want to set the user restriction in this case
3634 secureSetting.insertSettingLocked(
3635 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3636 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003637 }
3638 currentVersion = 138;
3639 }
Mark Rathjend891f012017-01-19 04:10:37 +00003640
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003641 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003642 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003643 currentVersion = 139;
3644 }
3645
Phil Weaver385912e2017-02-10 10:06:56 -08003646 if (currentVersion == 139) {
3647 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3648 // the user can no longer change the value of this setting through the UI.
3649 // Force to true.
3650 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3651 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3652 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3653 currentVersion = 140;
3654 }
3655
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003656 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003657 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003658 currentVersion = 141;
3659 }
3660
Svet Ganov13701552017-02-23 12:45:17 -08003661 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003662 // This implementation was incorrectly setting the current value of
3663 // settings changed by non-system packages as the default which default
3664 // is set by the system. We add a new upgrade step at the end to properly
3665 // handle this case which would also fix incorrect changes made by the
3666 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003667 currentVersion = 142;
3668 }
3669
Stephen Chen5d0922f2017-03-27 10:28:04 -07003670 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003671 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003672 if (userId == UserHandle.USER_SYSTEM) {
3673 final SettingsState globalSettings = getGlobalSettingsLocked();
3674 Setting currentSetting = globalSettings.getSettingLocked(
3675 Settings.Global.WIFI_WAKEUP_ENABLED);
3676 if (currentSetting.isNull()) {
3677 globalSettings.insertSettingLocked(
3678 Settings.Global.WIFI_WAKEUP_ENABLED,
3679 getContext().getResources().getBoolean(
3680 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3681 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3682 }
3683 }
3684
3685 currentVersion = 143;
3686 }
3687
Felipe Lemeff355092017-04-03 12:55:02 -07003688 if (currentVersion == 143) {
3689 // Version 144: Set a default value for Autofill service.
3690 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3691 final Setting currentSetting = secureSettings
3692 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3693 if (currentSetting.isNull()) {
3694 final String defaultValue = getContext().getResources().getString(
3695 com.android.internal.R.string.config_defaultAutofillService);
3696 if (defaultValue != null) {
3697 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3698 + "for user " + userId);
3699 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3700 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3701 }
3702 }
3703
3704 currentVersion = 144;
3705 }
3706
Jeremy Joslin45caa252017-05-04 11:22:46 -07003707 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003708 // Version 145: Removed
3709 currentVersion = 145;
3710 }
3711
3712 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003713 // Version 146: In step 142 we had a bug where incorrectly
3714 // some settings were considered system set and as a result
3715 // made the default and marked as the default being set by
3716 // the system. Here reevaluate the default and default system
3717 // set flags. This would both fix corruption by the old impl
3718 // of step 142 and also properly handle devices which never
3719 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003720 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003721 SettingsState globalSettings = getGlobalSettingsLocked();
3722 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3723 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003724 }
3725
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003726 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3727 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3728 secureSettings.persistSyncLocked();
3729
3730 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3731 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3732 systemSettings.persistSyncLocked();
3733
Amin Shaikh86367962017-06-07 08:58:22 -07003734 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003735 }
3736
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003737 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003738 // Version 147: Removed. (This version previously allowed showing the
3739 // "wifi_wakeup_available" setting).
3740 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003741 currentVersion = 147;
3742 }
3743
3744 if (currentVersion == 147) {
3745 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003746 if (userId == UserHandle.USER_SYSTEM) {
3747 final SettingsState globalSettings = getGlobalSettingsLocked();
3748 final Setting currentSetting = globalSettings.getSettingLocked(
3749 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3750 if (currentSetting.isNull()) {
3751 globalSettings.insertSettingLocked(
3752 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3753 getContext().getResources().getBoolean(
3754 R.bool.def_restrict_background_data) ? "1" : "0",
3755 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3756 }
3757 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003758 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003759 }
3760
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003761 if (currentVersion == 148) {
3762 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3763 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3764 final String oldValue = systemSecureSettings.getSettingLocked(
3765 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3766 if (TextUtils.equals(null, oldValue)) {
3767 final String defaultValue = getContext().getResources().getString(
3768 R.string.def_backup_manager_constants);
3769 if (!TextUtils.isEmpty(defaultValue)) {
3770 systemSecureSettings.insertSettingLocked(
3771 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3772 true, SettingsState.SYSTEM_PACKAGE_NAME);
3773 }
3774 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003775 currentVersion = 149;
3776 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003777
3778 if (currentVersion == 149) {
3779 // Version 150: Set a default value for mobile data always on
3780 final SettingsState globalSettings = getGlobalSettingsLocked();
3781 final Setting currentSetting = globalSettings.getSettingLocked(
3782 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3783 if (currentSetting.isNull()) {
3784 globalSettings.insertSettingLocked(
3785 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3786 getContext().getResources().getBoolean(
3787 R.bool.def_mobile_data_always_on) ? "1" : "0",
3788 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3789 }
3790
3791 currentVersion = 150;
3792 }
3793
Mike Digman4af4a6f2018-01-16 14:49:38 -08003794 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003795 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003796 currentVersion = 151;
3797 }
3798
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003799 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003800 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3801 // by default but it is now no longer configurable).
3802 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003803 currentVersion = 152;
3804 }
3805
Joe LaPenna250d7842018-01-25 10:19:42 -08003806 if (currentVersion == 152) {
3807 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3808 currentVersion = 153;
3809 }
3810
Ben Linb4df8bc2018-01-29 11:48:20 -08003811 if (currentVersion == 153) {
3812 // Version 154: Read notification badge configuration from config.
3813 // If user has already set the value, don't do anything.
3814 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3815 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3816 Settings.Secure.NOTIFICATION_BADGING);
3817 if (showNotificationBadges.isNull()) {
3818 final boolean defaultValue = getContext().getResources().getBoolean(
3819 com.android.internal.R.bool.config_notificationBadging);
3820 systemSecureSettings.insertSettingLocked(
3821 Secure.NOTIFICATION_BADGING,
3822 defaultValue ? "1" : "0",
3823 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3824 }
3825 currentVersion = 154;
3826 }
3827
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003828 if (currentVersion == 154) {
3829 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3830 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3831 final String oldValue = systemSecureSettings.getSettingLocked(
3832 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3833 if (TextUtils.equals(null, oldValue)) {
3834 final String defaultValue = getContext().getResources().getString(
3835 R.string.def_backup_local_transport_parameters);
3836 if (!TextUtils.isEmpty(defaultValue)) {
3837 systemSecureSettings.insertSettingLocked(
3838 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3839 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3840 }
3841
3842 }
3843 currentVersion = 155;
3844 }
3845
Beverlyda904812018-03-02 09:55:30 -05003846 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003847 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003848 final SettingsState globalSettings = getGlobalSettingsLocked();
3849 final String oldValue = globalSettings.getSettingLocked(
3850 Global.CHARGING_STARTED_SOUND).getValue();
3851 final String oldDefault = getContext().getResources().getString(
3852 R.string.def_wireless_charging_started_sound);
3853 if (TextUtils.equals(null, oldValue)
3854 || TextUtils.equals(oldValue, oldDefault)) {
3855 final String defaultValue = getContext().getResources().getString(
3856 R.string.def_charging_started_sound);
3857 if (!TextUtils.isEmpty(defaultValue)) {
3858 globalSettings.insertSettingLocked(
3859 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3860 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3861 }
3862
3863 }
3864 currentVersion = 156;
3865 }
3866
Beverly09da25f2018-02-26 09:17:07 -05003867 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003868 // Version 157: Set a default value for zen duration,
3869 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003870 final SettingsState globalSettings = getGlobalSettingsLocked();
3871 final Setting currentSetting = globalSettings.getSettingLocked(
3872 Global.ZEN_DURATION);
3873 if (currentSetting.isNull()) {
3874 String defaultZenDuration = Integer.toString(getContext()
3875 .getResources().getInteger(R.integer.def_zen_duration));
3876 globalSettings.insertSettingLocked(
3877 Global.ZEN_DURATION, defaultZenDuration,
3878 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3879 }
Beverly09da25f2018-02-26 09:17:07 -05003880 currentVersion = 157;
3881 }
Annie Mengd069a882018-03-13 15:31:40 +00003882
3883 if (currentVersion == 157) {
3884 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3885 final SettingsState globalSettings = getGlobalSettingsLocked();
3886 final String oldValue = globalSettings.getSettingLocked(
3887 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3888 if (TextUtils.equals(null, oldValue)) {
3889 final String defaultValue = getContext().getResources().getString(
3890 R.string.def_backup_agent_timeout_parameters);
3891 if (!TextUtils.isEmpty(defaultValue)) {
3892 globalSettings.insertSettingLocked(
3893 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3894 null, true,
3895 SettingsState.SYSTEM_PACKAGE_NAME);
3896 }
3897 }
3898 currentVersion = 158;
3899 }
Roshan Pius9c396672018-03-02 14:54:13 -08003900
3901 if (currentVersion == 158) {
3902 // Remove setting that specifies wifi bgscan throttling params
3903 getGlobalSettingsLocked().deleteSettingLocked(
3904 "wifi_scan_background_throttle_interval_ms");
3905 getGlobalSettingsLocked().deleteSettingLocked(
3906 "wifi_scan_background_throttle_package_whitelist");
3907 currentVersion = 159;
3908 }
3909
Pavel Grafovc5c97302018-03-19 13:37:15 +00003910 if (currentVersion == 159) {
3911 // Version 160: Hiding notifications from the lockscreen is only available as
3912 // primary user option, profiles can only make them redacted. If a profile was
3913 // configured to not show lockscreen notifications, ensure that at the very
3914 // least these will be come hidden.
3915 if (mUserManager.isManagedProfile(userId)) {
3916 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3917 Setting showNotifications = secureSettings.getSettingLocked(
3918 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3919 // The default value is "1", check if user has turned it off.
3920 if ("0".equals(showNotifications.getValue())) {
3921 secureSettings.insertSettingLocked(
3922 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3923 null /* tag */, false /* makeDefault */,
3924 SettingsState.SYSTEM_PACKAGE_NAME);
3925 }
3926 // The setting is no longer valid for managed profiles, it should be
3927 // treated as if it was set to "1".
3928 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3929 }
3930 currentVersion = 160;
3931 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003932
3933 if (currentVersion == 160) {
3934 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003935 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003936 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3937 final SettingsState globalSettings = getGlobalSettingsLocked();
3938
3939 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003940 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3941 if (TextUtils.equals(null, oldValue)) {
3942 globalSettings.insertSettingLocked(
3943 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3944 Integer.toString(getContext().getResources().getInteger(
3945 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3946 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3947 }
3948
3949 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003950 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3951 if (TextUtils.equals(null, oldValue)) {
3952 globalSettings.insertSettingLocked(
3953 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3954 Integer.toString(getContext().getResources().getInteger(
3955 R.integer.def_sound_trigger_detection_service_op_timeout)),
3956 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3957 }
3958 currentVersion = 161;
3959 }
3960
Mike Digman55272862018-02-20 14:35:17 -08003961 if (currentVersion == 161) {
3962 // Version 161: Add a gesture for silencing phones
3963 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3964 final Setting currentSetting = secureSettings.getSettingLocked(
3965 Secure.VOLUME_HUSH_GESTURE);
3966 if (currentSetting.isNull()) {
3967 secureSettings.insertSettingLocked(
3968 Secure.VOLUME_HUSH_GESTURE,
3969 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3970 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3971 }
3972
3973 currentVersion = 162;
3974 }
3975
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003976 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003977 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003978 currentVersion = 163;
3979 }
3980
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003981 if (currentVersion == 163) {
3982 // Version 163: Update default value of
3983 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3984 final SettingsState settings = getGlobalSettingsLocked();
3985 final Setting currentSetting = settings.getSettingLocked(
3986 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3987 if (currentSetting.isDefaultFromSystem()) {
3988 settings.insertSettingLocked(
3989 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3990 Integer.toString(getContext().getResources().getInteger(
3991 R.integer
3992 .def_max_sound_trigger_detection_service_ops_per_day)),
3993 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3994 }
3995
3996 currentVersion = 164;
3997 }
3998
Julia Reynolds76bfa602018-04-23 09:38:47 -04003999 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004000 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004001 currentVersion = 165;
4002 }
4003
Beverly301e92a2018-04-27 09:43:05 -04004004 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004005 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4006 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004007 currentVersion = 166;
4008 }
4009
Beverly38fcfd02018-05-18 17:33:40 -04004010 if (currentVersion == 166) {
4011 // Version 166: add default values for hush gesture used and manual ringer
4012 // toggle
4013 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4014 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4015 Secure.HUSH_GESTURE_USED);
4016 if (currentHushUsedSetting.isNull()) {
4017 secureSettings.insertSettingLocked(
4018 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4019 SettingsState.SYSTEM_PACKAGE_NAME);
4020 }
4021
4022 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4023 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4024 if (currentRingerToggleCountSetting.isNull()) {
4025 secureSettings.insertSettingLocked(
4026 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4027 SettingsState.SYSTEM_PACKAGE_NAME);
4028 }
4029 currentVersion = 167;
4030 }
4031
Beverly155c9d22018-05-23 18:03:23 -04004032 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004033 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4034 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004035 currentVersion = 168;
4036 }
4037
Michael Wright0e9eeee2018-05-26 00:31:20 +01004038 if (currentVersion == 168) {
4039 // Version 168: by default, vibrate for phone calls
4040 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4041 final Setting currentSetting = systemSettings.getSettingLocked(
4042 Settings.System.VIBRATE_WHEN_RINGING);
4043 if (currentSetting.isNull()) {
4044 systemSettings.insertSettingLocked(
4045 Settings.System.VIBRATE_WHEN_RINGING,
4046 getContext().getResources().getBoolean(
4047 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4048 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4049 }
4050 currentVersion = 169;
4051 }
4052
Nadav Barf9f115d2018-06-24 10:06:50 +03004053 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004054 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4055 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4056 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004057
Beverly91d0a632018-07-02 16:45:00 -04004058 final SettingsState globalSettings = getGlobalSettingsLocked();
4059 final Setting globalZenDuration = globalSettings.getSettingLocked(
4060 Global.ZEN_DURATION);
4061
4062 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4063 final Setting secureZenDuration = secureSettings.getSettingLocked(
4064 Secure.ZEN_DURATION);
4065
4066 // ZEN_DURATION
4067 if (!globalZenDuration.isNull()) {
4068 secureSettings.insertSettingLocked(
4069 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4070 SettingsState.SYSTEM_PACKAGE_NAME);
4071
4072 // set global zen duration setting to null since it's deprecated
4073 globalSettings.insertSettingLocked(
4074 Global.ZEN_DURATION, null, null, true,
4075 SettingsState.SYSTEM_PACKAGE_NAME);
4076 } else if (secureZenDuration.isNull()) {
4077 String defaultZenDuration = Integer.toString(getContext()
4078 .getResources().getInteger(R.integer.def_zen_duration));
4079 secureSettings.insertSettingLocked(
4080 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4081 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004082 }
Beverly91d0a632018-07-02 16:45:00 -04004083
4084 // SHOW_ZEN_SETTINGS_SUGGESTION
4085 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4086 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4087 if (currentShowZenSettingSuggestion.isNull()) {
4088 secureSettings.insertSettingLocked(
4089 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4090 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4091 }
4092
4093 // ZEN_SETTINGS_UPDATED
4094 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4095 Secure.ZEN_SETTINGS_UPDATED);
4096 if (currentUpdatedSetting.isNull()) {
4097 secureSettings.insertSettingLocked(
4098 Secure.ZEN_SETTINGS_UPDATED, "0",
4099 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4100 }
4101
4102 // ZEN_SETTINGS_SUGGESTION_VIEWED
4103 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4104 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4105 if (currentSettingSuggestionViewed.isNull()) {
4106 secureSettings.insertSettingLocked(
4107 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4108 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4109 }
4110
Nadav Barf9f115d2018-06-24 10:06:50 +03004111 currentVersion = 170;
4112 }
4113
Beverly91d0a632018-07-02 16:45:00 -04004114 if (currentVersion == 170) {
4115 // Version 170: Set the default value for Secure Settings:
4116 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4117
4118 final SettingsState globalSettings = getGlobalSettingsLocked();
4119 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4120
4121 // CHARGING_SOUNDS_ENABLED
4122 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4123 Global.CHARGING_SOUNDS_ENABLED);
4124 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4125 Secure.CHARGING_SOUNDS_ENABLED);
4126
4127 if (!globalChargingSoundEnabled.isNull()) {
Beverlyff9c5872019-01-02 15:44:00 -05004128 if (secureChargingSoundsEnabled.isNull()) {
4129 secureSettings.insertSettingLocked(
4130 Secure.CHARGING_SOUNDS_ENABLED,
4131 globalChargingSoundEnabled.getValue(), null, false,
4132 SettingsState.SYSTEM_PACKAGE_NAME);
4133 }
Beverly91d0a632018-07-02 16:45:00 -04004134
4135 // set global charging_sounds_enabled setting to null since it's deprecated
4136 globalSettings.insertSettingLocked(
4137 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4138 SettingsState.SYSTEM_PACKAGE_NAME);
4139 } else if (secureChargingSoundsEnabled.isNull()) {
4140 String defChargingSoundsEnabled = getContext().getResources()
4141 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4142 secureSettings.insertSettingLocked(
4143 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4144 true, SettingsState.SYSTEM_PACKAGE_NAME);
4145 }
4146
4147 // CHARGING_VIBRATION_ENABLED
4148 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4149 Secure.CHARGING_VIBRATION_ENABLED);
4150
4151 if (secureChargingVibrationEnabled.isNull()) {
4152 String defChargingVibrationEnabled = getContext().getResources()
4153 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4154 secureSettings.insertSettingLocked(
4155 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4156 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4157 }
4158
4159 currentVersion = 171;
4160 }
4161
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004162 if (currentVersion == 171) {
4163 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4164 // be muted.
4165 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4166 final Setting currentSetting = systemSettings.getSettingLocked(
4167 Settings.System.MUTE_STREAMS_AFFECTED);
4168 if (!currentSetting.isNull()) {
4169 try {
4170 int currentSettingIntegerValue = Integer.parseInt(
4171 currentSetting.getValue());
4172 if ((currentSettingIntegerValue
4173 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4174 systemSettings.insertSettingLocked(
4175 Settings.System.MUTE_STREAMS_AFFECTED,
4176 Integer.toString(
4177 currentSettingIntegerValue
4178 | (1 << AudioManager.STREAM_VOICE_CALL)),
4179 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4180 }
4181 } catch (NumberFormatException e) {
4182 // remove the setting in case it is not a valid integer
4183 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4184 + "setting, removing setting", e);
4185 systemSettings.deleteSettingLocked(
4186 Settings.System.MUTE_STREAMS_AFFECTED);
4187 }
4188
4189 }
4190 currentVersion = 172;
4191 }
4192
Felipe Lemeff355092017-04-03 12:55:02 -07004193 // vXXX: Add new settings above this point.
4194
Dan Sandler71f85e92016-07-20 13:46:05 -04004195 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004196 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004197 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004198 + currentVersion +
4199 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4200 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004201 if (DEBUG) {
4202 throw new RuntimeException("db upgrade error");
4203 }
4204 }
4205
Jeff Brown503cffc2015-03-26 18:08:51 -07004206 // Return the current version.
4207 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004208 }
4209 }
Svet Ganov13701552017-02-23 12:45:17 -08004210
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004211 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4212 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004213 List<String> names = settings.getSettingNamesLocked();
4214 final int nameCount = names.size();
4215 for (int i = 0; i < nameCount; i++) {
4216 String name = names.get(i);
4217 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004218
4219 // In the upgrade case we pretend the call is made from the app
4220 // that made the last change to the setting to properly determine
4221 // whether the call has been made by a system component.
4222 int callingUid = -1;
4223 try {
4224 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4225 } catch (RemoteException e) {
4226 /* ignore - handled below */
4227 }
4228 if (callingUid < 0) {
4229 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4230 continue;
4231 }
4232 try {
4233 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4234 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004235 if (systemSet) {
4236 settings.insertSettingLocked(name, setting.getValue(),
4237 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004238 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4239 // We had a bug where changes by non-system packages were marked
4240 // as system made and as a result set as the default. Therefore, if
4241 // the package changed the setting last is not a system one but the
4242 // setting is marked as its default coming from the system we clear
4243 // the default and clear the system set flag.
4244 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004245 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004246 } catch (IllegalStateException e) {
4247 // If the package goes over its quota during the upgrade, don't
4248 // crash but just log the error as the system does the upgrade.
4249 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4250
Svet Ganov13701552017-02-23 12:45:17 -08004251 }
4252 }
4253 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004254 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004255}