blob: 424368d2600cfae023c17edb898df908ab4b5a80 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010067import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080068import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000069import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010071import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080072import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000073import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070076import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080077import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import com.android.internal.annotations.GuardedBy;
80import com.android.internal.content.PackageMonitor;
81import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080082import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070083import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080084import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040085
Svetoslav683914b2015-01-15 14:22:26 -080086import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080087import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080089import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080090import java.nio.ByteBuffer;
91import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070094import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000096import java.util.Collection;
Matt Pape6bfc62e2018-11-28 13:16:03 -080097import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +000098import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080099import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -0800100import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100101import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800102import java.util.Set;
103import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000104
Mark Rathjen7599f132017-01-23 14:15:54 -0800105import javax.crypto.Mac;
106import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700107
Svetoslav Ganove080da92016-12-21 17:10:35 -0800108
Svetoslav683914b2015-01-15 14:22:26 -0800109/**
110 * <p>
111 * This class is a content provider that publishes the system settings.
112 * It can be accessed via the content provider APIs or via custom call
113 * commands. The latter is a bit faster and is the preferred way to access
114 * the platform settings.
115 * </p>
116 * <p>
117 * There are three settings types, global (with signature level protection
118 * and shared across users), secure (with signature permission level
119 * protection and per user), and system (with dangerous permission level
120 * protection and per user). Global settings are stored under the device owner.
121 * Each of these settings is represented by a {@link
122 * com.android.providers.settings.SettingsState} object mapped to an integer
123 * key derived from the setting type in the most significant bits and user
124 * id in the least significant bits. Settings are synchronously loaded on
125 * instantiation of a SettingsState and asynchronously persisted on mutation.
126 * Settings are stored in the user specific system directory.
127 * </p>
128 * <p>
129 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
130 * and get a warning. Targeting higher API version prohibits this as the
131 * system settings are not a place for apps to save their state. When a package
132 * is removed the settings it added are deleted. Apps cannot delete system
133 * settings added by the platform. System settings values are validated to
134 * ensure the clients do not put bad values. Global and secure settings are
135 * changed only by trusted parties, therefore no validation is performed. Also
136 * there is a limit on the amount of app specific settings that can be added
137 * to prevent unlimited growth of the system process memory footprint.
138 * </p>
139 */
140@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700142 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700144 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800145
146 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700147
Christopher Tate06efb532012-08-24 15:29:27 -0700148 private static final String TABLE_SYSTEM = "system";
149 private static final String TABLE_SECURE = "secure";
150 private static final String TABLE_GLOBAL = "global";
Matt Pape6bfc62e2018-11-28 13:16:03 -0800151 private static final String TABLE_CONFIG = "config";
Svetoslav683914b2015-01-15 14:22:26 -0800152
153 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 private static final String TABLE_FAVORITES = "favorites";
155 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800156 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
157 private static final String TABLE_BOOKMARKS = "bookmarks";
158 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Svetoslav683914b2015-01-15 14:22:26 -0800160 // The set of removed legacy tables.
161 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700162 static {
Svetoslav683914b2015-01-15 14:22:26 -0800163 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
164 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
165 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
166 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
167 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
168 }
Christopher Tate06efb532012-08-24 15:29:27 -0700169
Svetoslav683914b2015-01-15 14:22:26 -0800170 private static final int MUTATION_OPERATION_INSERT = 1;
171 private static final int MUTATION_OPERATION_DELETE = 2;
172 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800173 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400174
Svetoslav683914b2015-01-15 14:22:26 -0800175 private static final String[] ALL_COLUMNS = new String[] {
176 Settings.NameValueTable._ID,
177 Settings.NameValueTable.NAME,
178 Settings.NameValueTable.VALUE
179 };
180
Makoto Onuki53f0e022017-11-29 13:51:01 -0800181 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
182 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
183 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
184 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700185 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700186
187 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
188 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700189
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800190 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800191 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800192
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700193 // Overlay specified settings whitelisted for Instant Apps
194 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
195 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
196 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
197
Matt Pape1b31a332018-10-17 09:58:28 -0700198 /**
199 * TODO(b/113100523): Move this to DeviceConfig.java when it is added, and expose it as a System
200 * API.
201 */
202 private static final Uri CONFIG_CONTENT_URI =
203 Uri.parse("content://" + Settings.AUTHORITY + "/config");
204
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700205 static {
206 for (String name : Resources.getSystem().getStringArray(
207 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
208 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
209 }
210 for (String name : Resources.getSystem().getStringArray(
211 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
212 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
213 }
214 for (String name : Resources.getSystem().getStringArray(
215 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
216 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
217 }
218 }
219
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800220 // Changes to these global settings are synchronously persisted
221 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
222 static {
223 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
224 }
225
226 // Changes to these secure settings are synchronously persisted
227 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
228 static {
229 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
230 }
231
Svetoslav683914b2015-01-15 14:22:26 -0800232 // Per user secure settings that moved to the for all users global settings.
233 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
234 static {
235 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700236 }
237
Svetoslav683914b2015-01-15 14:22:26 -0800238 // Per user system settings that moved to the for all users global settings.
239 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
240 static {
241 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 }
243
Svetoslav683914b2015-01-15 14:22:26 -0800244 // Per user system settings that moved to the per user secure settings.
245 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
246 static {
247 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 }
249
Svetoslav683914b2015-01-15 14:22:26 -0800250 // Per all users global settings that moved to the per user secure settings.
251 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
252 static {
253 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700254 }
255
Svetoslav683914b2015-01-15 14:22:26 -0800256 // Per user secure settings that are cloned for the managed profiles of the user.
257 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
258 static {
259 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 }
261
Svetoslav683914b2015-01-15 14:22:26 -0800262 // Per user system settings that are cloned for the managed profiles of the user.
263 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
264 static {
265 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400266 }
267
Andre Lago3fa139c2016-08-04 13:53:44 +0100268 // Per user system settings that are cloned from the profile's parent when a dependency
269 // in {@link Settings.Secure} is set to "1".
270 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
271 static {
272 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
273 }
274
Svetoslav683914b2015-01-15 14:22:26 -0800275 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700276
Svetoslav683914b2015-01-15 14:22:26 -0800277 @GuardedBy("mLock")
278 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700279
Svet Ganova8f90262016-05-10 08:44:48 -0700280 @GuardedBy("mLock")
281 private HandlerThread mHandlerThread;
282
Makoto Onuki73360ab2017-03-17 11:50:13 -0700283 @GuardedBy("mLock")
284 private Handler mHandler;
285
Svetoslav7ec28e82015-05-20 17:01:10 -0700286 // We have to call in the user manager with no lock held,
287 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800288
yuemingw1d13eae2018-01-30 17:27:54 +0000289 private UserManagerInternal mUserManagerInternal;
290
Svetoslav7ec28e82015-05-20 17:01:10 -0700291 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700292 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700293
Svet Ganov53a441c2016-04-19 19:38:00 -0700294 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800295 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700296 }
297
298 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800299 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700300 }
301
302 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800303 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 }
305
306 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800307 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700308 }
309
310 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800311 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700312 }
313
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 @Override
315 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800316 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000317
318 // fail to boot if there're any backed up settings that don't have a non-null validator
319 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000320 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000321 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000322
Svetoslav683914b2015-01-15 14:22:26 -0800323 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700324 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000325 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700326 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700327 mHandlerThread = new HandlerThread(LOG_TAG,
328 Process.THREAD_PRIORITY_BACKGROUND);
329 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700330 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800331 mSettingsRegistry = new SettingsRegistry();
332 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700333 mHandler.post(() -> {
334 registerBroadcastReceivers();
335 startWatchingUserRestrictionChanges();
336 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700337 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800338 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700339 return true;
340 }
341
Michal Karpinski2c37b082018-01-18 16:14:27 +0000342 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000343 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
344 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000345
346 failToBootIfOffendersPresent(offenders, "Settings.System");
347 }
348
349 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000350 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
351 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000352
353 failToBootIfOffendersPresent(offenders, "Settings.Global");
354 }
355
Michal Karpinski964943a2018-01-19 16:28:26 +0000356 private void ensureAllBackedUpSecureSettingsHaveValidators() {
357 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
358 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
359
360 failToBootIfOffendersPresent(offenders, "Settings.Secure");
361 }
362
Michal Karpinski5db1e432018-01-18 20:10:24 +0000363 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
364 if (offenders.length() > 0) {
365 throw new RuntimeException("All " + settingsType + " settings that are backed up"
366 + " have to have a non-null validator, but those don't: " + offenders);
367 }
368 }
369
370 private String getOffenders(String[] settingsToBackup, Map<String,
371 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000372 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000373 for (String setting : settingsToBackup) {
374 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000375 offenders.append(setting).append(" ");
376 }
377 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000378 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000379 }
380
Michal Karpinski964943a2018-01-19 16:28:26 +0000381 private final String[] concat(String[] first, String[] second) {
382 if (second == null || second.length == 0) {
383 return first;
384 }
385 final int firstLen = first.length;
386 final int secondLen = second.length;
387 String[] both = new String[firstLen + secondLen];
388 System.arraycopy(first, 0, both, 0, firstLen);
389 System.arraycopy(second, 0, both, firstLen, secondLen);
390 return both;
391 }
392
Svetoslav683914b2015-01-15 14:22:26 -0800393 @Override
394 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700395 final int requestingUserId = getRequestingUserId(args);
396 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700397 case Settings.CALL_METHOD_GET_CONFIG: {
398 Setting setting = getConfigSetting(name);
399 return packageValueForCallResult(setting, isTrackingGeneration(args));
400 }
401
Svetoslav7ec28e82015-05-20 17:01:10 -0700402 case Settings.CALL_METHOD_GET_GLOBAL: {
403 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700404 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800405 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700406
407 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800408 Setting setting = getSecureSetting(name, requestingUserId,
409 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700410 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700411 }
412
413 case Settings.CALL_METHOD_GET_SYSTEM: {
414 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700415 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700416 }
417
Matt Pape1b31a332018-10-17 09:58:28 -0700418 case Settings.CALL_METHOD_PUT_CONFIG: {
419 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700420 final boolean makeDefault = getSettingMakeDefault(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800421 insertConfigSetting(name, value, null, makeDefault, requestingUserId, false);
Matt Pape1b31a332018-10-17 09:58:28 -0700422 break;
423 }
424
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 case Settings.CALL_METHOD_PUT_GLOBAL: {
426 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800427 String tag = getSettingTag(args);
428 final boolean makeDefault = getSettingMakeDefault(args);
429 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700430 break;
431 }
432
433 case Settings.CALL_METHOD_PUT_SECURE: {
434 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800435 String tag = getSettingTag(args);
436 final boolean makeDefault = getSettingMakeDefault(args);
437 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700438 break;
439 }
440
441 case Settings.CALL_METHOD_PUT_SYSTEM: {
442 String value = getSettingValue(args);
443 insertSystemSetting(name, value, requestingUserId);
444 break;
445 }
446
Matt Pape1b31a332018-10-17 09:58:28 -0700447 case Settings.CALL_METHOD_RESET_CONFIG: {
448 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800449 String prefix = getSettingPrefix(args);
450 resetConfigSetting(requestingUserId, mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700451 break;
452 }
453
Svetoslav Ganove080da92016-12-21 17:10:35 -0800454 case Settings.CALL_METHOD_RESET_GLOBAL: {
455 final int mode = getResetModeEnforcingPermission(args);
456 String tag = getSettingTag(args);
457 resetGlobalSetting(requestingUserId, mode, tag);
458 break;
459 }
460
461 case Settings.CALL_METHOD_RESET_SECURE: {
462 final int mode = getResetModeEnforcingPermission(args);
463 String tag = getSettingTag(args);
464 resetSecureSetting(requestingUserId, mode, tag);
465 break;
466 }
467
Matt Pape6bfc62e2018-11-28 13:16:03 -0800468 case Settings.CALL_METHOD_DELETE_CONFIG: {
469 int rows = deleteConfigSetting(name, requestingUserId, false) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800470 Bundle result = new Bundle();
471 result.putInt(RESULT_ROWS_DELETED, rows);
472 return result;
473 }
474
475 case Settings.CALL_METHOD_DELETE_GLOBAL: {
476 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
477 Bundle result = new Bundle();
478 result.putInt(RESULT_ROWS_DELETED, rows);
479 return result;
480 }
481
Matt Pape6bfc62e2018-11-28 13:16:03 -0800482 case Settings.CALL_METHOD_DELETE_SECURE: {
483 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
484 Bundle result = new Bundle();
485 result.putInt(RESULT_ROWS_DELETED, rows);
486 return result;
487 }
488
489 case Settings.CALL_METHOD_DELETE_SYSTEM: {
490 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
491 Bundle result = new Bundle();
492 result.putInt(RESULT_ROWS_DELETED, rows);
493 return result;
494 }
495
496 case Settings.CALL_METHOD_LIST_CONFIG: {
497 String prefix = getSettingPrefix(args);
498 Bundle result = new Bundle();
499 result.putSerializable(
500 Settings.NameValueTable.VALUE, (HashMap) getAllConfigFlags(prefix));
501 return result;
502 }
503
504 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800505 Bundle result = new Bundle();
506 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800507 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800508 return result;
509 }
510
511 case Settings.CALL_METHOD_LIST_SECURE: {
512 Bundle result = new Bundle();
513 result.putStringArrayList(RESULT_SETTINGS_LIST,
514 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
515 return result;
516 }
517
Matt Pape6bfc62e2018-11-28 13:16:03 -0800518 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800519 Bundle result = new Bundle();
520 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800521 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800522 return result;
523 }
524
Svetoslav7ec28e82015-05-20 17:01:10 -0700525 default: {
526 Slog.w(LOG_TAG, "call() with invalid method: " + method);
527 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700528 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700529
Christopher Tate06efb532012-08-24 15:29:27 -0700530 return null;
531 }
532
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800533 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800534 public String getType(Uri uri) {
535 Arguments args = new Arguments(uri, null, null, true);
536 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537 return "vnd.android.cursor.dir/" + args.table;
538 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700539 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700540 }
541 }
542
543 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800544 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
545 String order) {
546 if (DEBUG) {
547 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700548 }
549
Svetoslav683914b2015-01-15 14:22:26 -0800550 Arguments args = new Arguments(uri, where, whereArgs, true);
551 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552
Svetoslav683914b2015-01-15 14:22:26 -0800553 // If a legacy table that is gone, done.
554 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
555 return new MatrixCursor(normalizedProjection, 0);
556 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700557
Svetoslav7ec28e82015-05-20 17:01:10 -0700558 switch (args.table) {
559 case TABLE_GLOBAL: {
560 if (args.name != null) {
561 Setting setting = getGlobalSetting(args.name);
562 return packageSettingForQuery(setting, normalizedProjection);
563 } else {
564 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700565 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700566 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700567
Svetoslav7ec28e82015-05-20 17:01:10 -0700568 case TABLE_SECURE: {
569 final int userId = UserHandle.getCallingUserId();
570 if (args.name != null) {
571 Setting setting = getSecureSetting(args.name, userId);
572 return packageSettingForQuery(setting, normalizedProjection);
573 } else {
574 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800575 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700576 }
Svetoslav683914b2015-01-15 14:22:26 -0800577
Svetoslav7ec28e82015-05-20 17:01:10 -0700578 case TABLE_SYSTEM: {
579 final int userId = UserHandle.getCallingUserId();
580 if (args.name != null) {
581 Setting setting = getSystemSetting(args.name, userId);
582 return packageSettingForQuery(setting, normalizedProjection);
583 } else {
584 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800585 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700586 }
Svetoslav683914b2015-01-15 14:22:26 -0800587
Svetoslav7ec28e82015-05-20 17:01:10 -0700588 default: {
589 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700590 }
591 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700592 }
593
Nicholas Sauer72500532018-11-21 10:30:58 -0800594 private ArrayList<String> buildSettingsList(Cursor cursor) {
595 final ArrayList<String> lines = new ArrayList<String>();
596 try {
597 while (cursor != null && cursor.moveToNext()) {
598 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
599 }
600 } finally {
601 if (cursor != null) {
602 cursor.close();
603 }
604 }
605 return lines;
606 }
607
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700608 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800609 public Uri insert(Uri uri, ContentValues values) {
610 if (DEBUG) {
611 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700612 }
613
Svetoslav683914b2015-01-15 14:22:26 -0800614 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700615
Svetoslav683914b2015-01-15 14:22:26 -0800616 // If a legacy table that is gone, done.
617 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 return null;
619 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700620
Svetoslav683914b2015-01-15 14:22:26 -0800621 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700622 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800623 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700624 }
625
Svetoslav683914b2015-01-15 14:22:26 -0800626 String value = values.getAsString(Settings.Secure.VALUE);
627
Svetoslav7ec28e82015-05-20 17:01:10 -0700628 switch (table) {
629 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800630 if (insertGlobalSetting(name, value, null, false,
631 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700632 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700633 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700634 } break;
635
636 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800637 if (insertSecureSetting(name, value, null, false,
638 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700639 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
640 }
641 } break;
642
643 case TABLE_SYSTEM: {
644 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
645 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
646 }
647 } break;
648
649 default: {
650 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700651 }
652 }
653
Svetoslav683914b2015-01-15 14:22:26 -0800654 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700655 }
656
657 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800658 public int bulkInsert(Uri uri, ContentValues[] allValues) {
659 if (DEBUG) {
660 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700662
Svetoslav683914b2015-01-15 14:22:26 -0800663 int insertionCount = 0;
664 final int valuesCount = allValues.length;
665 for (int i = 0; i < valuesCount; i++) {
666 ContentValues values = allValues[i];
667 if (insert(uri, values) != null) {
668 insertionCount++;
669 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700670 }
Svetoslav683914b2015-01-15 14:22:26 -0800671
672 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700673 }
674
675 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800676 public int delete(Uri uri, String where, String[] whereArgs) {
677 if (DEBUG) {
678 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700680
Svetoslav683914b2015-01-15 14:22:26 -0800681 Arguments args = new Arguments(uri, where, whereArgs, false);
682
683 // If a legacy table that is gone, done.
684 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
685 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700686 }
Svetoslav683914b2015-01-15 14:22:26 -0800687
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700688 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800689 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700690 }
Svetoslav683914b2015-01-15 14:22:26 -0800691
Svetoslav7ec28e82015-05-20 17:01:10 -0700692 switch (args.table) {
693 case TABLE_GLOBAL: {
694 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700695 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700696 }
Svetoslav683914b2015-01-15 14:22:26 -0800697
Svetoslav7ec28e82015-05-20 17:01:10 -0700698 case TABLE_SECURE: {
699 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700700 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700701 }
Svetoslav683914b2015-01-15 14:22:26 -0800702
Svetoslav7ec28e82015-05-20 17:01:10 -0700703 case TABLE_SYSTEM: {
704 final int userId = UserHandle.getCallingUserId();
705 return deleteSystemSetting(args.name, userId) ? 1 : 0;
706 }
707
708 default: {
709 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800710 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700711 }
Svetoslav683914b2015-01-15 14:22:26 -0800712 }
713
714 @Override
715 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
716 if (DEBUG) {
717 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700718 }
Svetoslav683914b2015-01-15 14:22:26 -0800719
720 Arguments args = new Arguments(uri, where, whereArgs, false);
721
722 // If a legacy table that is gone, done.
723 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
724 return 0;
725 }
726
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700727 String name = values.getAsString(Settings.Secure.NAME);
728 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800729 return 0;
730 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700731 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800732
Svetoslav7ec28e82015-05-20 17:01:10 -0700733 switch (args.table) {
734 case TABLE_GLOBAL: {
735 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800736 return updateGlobalSetting(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_SECURE: {
741 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800742 return updateSecureSetting(args.name, value, null, false,
743 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700744 }
Svetoslav683914b2015-01-15 14:22:26 -0800745
Svetoslav7ec28e82015-05-20 17:01:10 -0700746 case TABLE_SYSTEM: {
747 final int userId = UserHandle.getCallingUserId();
748 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
749 }
Svetoslav683914b2015-01-15 14:22:26 -0800750
Svetoslav7ec28e82015-05-20 17:01:10 -0700751 default: {
752 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800753 }
754 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700755 }
756
757 @Override
758 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100759 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
760 if (userId != UserHandle.getCallingUserId()) {
761 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
762 "Access files from the settings of another user");
763 }
764 uri = ContentProvider.getUriWithoutUserId(uri);
765
Andre Lago3fa139c2016-08-04 13:53:44 +0100766 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700767 final String cacheName;
768 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100769 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700770 cacheName = Settings.System.RINGTONE_CACHE;
771 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100772 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700773 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
774 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100775 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700776 cacheName = Settings.System.ALARM_ALERT_CACHE;
777 } else {
778 throw new FileNotFoundException("Direct file access no longer supported; "
779 + "ringtone playback is available through android.media.Ringtone");
780 }
781
Andre Lago3fa139c2016-08-04 13:53:44 +0100782 int actualCacheOwner;
783 // Redirect cache to parent if ringtone setting is owned by profile parent
784 synchronized (mLock) {
785 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
786 cacheRingtoneSetting);
787 }
788 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700789 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
790 }
791
792 private File getRingtoneCacheDir(int userId) {
793 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
794 cacheDir.mkdir();
795 SELinux.restorecon(cacheDir);
796 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700797 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800798
Eugene Suslad72c3972016-12-27 15:49:30 -0800799 /**
800 * Dump all settings as a proto buf.
801 *
802 * @param fd The file to dump to
803 */
804 void dumpProto(@NonNull FileDescriptor fd) {
805 ProtoOutputStream proto = new ProtoOutputStream(fd);
806
807 synchronized (mLock) {
808 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800809 }
810
811 proto.flush();
812 }
813
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700814 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800815 synchronized (mLock) {
816 final long identity = Binder.clearCallingIdentity();
817 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700818 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800819 final int userCount = users.size();
820 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700821 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800822 }
823 } finally {
824 Binder.restoreCallingIdentity(identity);
825 }
826 }
827 }
828
Andreas Gampeb58893072018-09-05 16:52:31 -0700829 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700830 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700831 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700832 pw.println("CONFIG SETTINGS (user " + userId + ")");
833 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
834 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
835 if (configSettings != null) {
836 dumpSettingsLocked(configSettings, pw);
837 pw.println();
838 configSettings.dumpHistoricalOperations(pw);
839 }
840
Svetoslavb505ccc2015-02-17 12:41:04 -0800841 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700842 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
843 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700844 if (globalSettings != null) {
845 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800846 pw.println();
847 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700848 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800849 }
850
851 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700852 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
853 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700854 if (secureSettings != null) {
855 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 pw.println();
857 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700858 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700859
Svetoslavb505ccc2015-02-17 12:41:04 -0800860 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700861 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
862 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700863 if (systemSettings != null) {
864 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800865 pw.println();
866 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700867 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800868 }
869
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700870 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
871 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800872
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700873 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800874
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700875 for (int i = 0; i < nameCount; i++) {
876 String name = names.get(i);
877 Setting setting = settingsState.getSettingLocked(name);
878 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
879 pw.print(" name:"); pw.print(toDumpString(name));
880 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800881 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700882 }
883 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800884 if (setting.getDefaultValue() != null) {
885 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800886 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800887 }
888 if (setting.getTag() != null) {
889 pw.print(" tag:"); pw.print(setting.getTag());
890 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800891 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700892 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800893 }
894
Svetoslav7e0683b2015-08-03 16:02:52 -0700895 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700896 if (s != null) {
897 return s;
898 }
899 return "{null}";
900 }
901
Svetoslav683914b2015-01-15 14:22:26 -0800902 private void registerBroadcastReceivers() {
903 IntentFilter userFilter = new IntentFilter();
904 userFilter.addAction(Intent.ACTION_USER_REMOVED);
905 userFilter.addAction(Intent.ACTION_USER_STOPPED);
906
907 getContext().registerReceiver(new BroadcastReceiver() {
908 @Override
909 public void onReceive(Context context, Intent intent) {
910 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700911 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800912
913 switch (intent.getAction()) {
914 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700915 synchronized (mLock) {
916 mSettingsRegistry.removeUserStateLocked(userId, true);
917 }
Svetoslav683914b2015-01-15 14:22:26 -0800918 } break;
919
920 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700921 synchronized (mLock) {
922 mSettingsRegistry.removeUserStateLocked(userId, false);
923 }
Svetoslav683914b2015-01-15 14:22:26 -0800924 } break;
925 }
926 }
927 }, userFilter);
928
929 PackageMonitor monitor = new PackageMonitor() {
930 @Override
931 public void onPackageRemoved(String packageName, int uid) {
932 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100933 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800934 UserHandle.getUserId(uid));
935 }
936 }
Mark Rathjend891f012017-01-19 04:10:37 +0000937
938 @Override
939 public void onUidRemoved(int uid) {
940 synchronized (mLock) {
941 mSettingsRegistry.onUidRemovedLocked(uid);
942 }
943 }
Zimuzoc56192c2018-07-25 10:40:01 +0100944
945 @Override
946 public void onPackageDataCleared(String packageName, int uid) {
947 synchronized (mLock) {
948 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
949 UserHandle.getUserId(uid));
950 }
951 }
Svetoslav683914b2015-01-15 14:22:26 -0800952 };
953
954 // package changes
955 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
956 UserHandle.ALL, true);
957 }
958
Svet Ganov53a441c2016-04-19 19:38:00 -0700959 private void startWatchingUserRestrictionChanges() {
960 // TODO: The current design of settings looking different based on user restrictions
961 // should be reworked to keep them separate and system code should check the setting
962 // first followed by checking the user restriction before performing an operation.
963 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
964 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
965 Bundle prevRestrictions) -> {
966 // We are changing the settings affected by restrictions to their current
967 // value with a forced update to ensure that all cross profile dependencies
968 // are taken into account. Also make sure the settings update to.. the same
969 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800970 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
971 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700972 final long identity = Binder.clearCallingIdentity();
973 try {
974 synchronized (mLock) {
975 Setting setting = getSecureSetting(
976 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
977 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800978 setting != null ? setting.getValue() : null, null,
979 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700980 }
981 } finally {
982 Binder.restoreCallingIdentity(identity);
983 }
984 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800985 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100986 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
987 newRestrictions.getBoolean(
988 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
989 != prevRestrictions.getBoolean(
990 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700991 final long identity = Binder.clearCallingIdentity();
992 try {
993 synchronized (mLock) {
994 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800995 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700996 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800997 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700998 }
999 } finally {
1000 Binder.restoreCallingIdentity(identity);
1001 }
1002 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001003 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
1004 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001005 final long identity = Binder.clearCallingIdentity();
1006 try {
1007 synchronized (mLock) {
1008 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001009 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001010 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001011 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001012 }
1013 } finally {
1014 Binder.restoreCallingIdentity(identity);
1015 }
1016 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001017 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
1018 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001019 final long identity = Binder.clearCallingIdentity();
1020 try {
1021 synchronized (mLock) {
1022 Setting enable = getGlobalSetting(
1023 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001024 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001025 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001026 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001027 Setting include = getGlobalSetting(
1028 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001029 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001030 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001031 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001032 }
1033 } finally {
1034 Binder.restoreCallingIdentity(identity);
1035 }
1036 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001037 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
1038 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001039 final long identity = Binder.clearCallingIdentity();
1040 try {
1041 synchronized (mLock) {
1042 Setting setting = getGlobalSetting(
1043 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001044 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001045 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001046 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001047 }
1048 } finally {
1049 Binder.restoreCallingIdentity(identity);
1050 }
1051 }
1052 });
1053 }
1054
Matt Pape1b31a332018-10-17 09:58:28 -07001055 private Setting getConfigSetting(String name) {
1056 if (DEBUG) {
1057 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1058 }
1059
1060 // TODO(b/117663715): Ensure the caller can access the setting.
1061 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1062
1063 // Get the value.
1064 synchronized (mLock) {
1065 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1066 UserHandle.USER_SYSTEM, name);
1067 }
1068 }
1069
1070 private boolean insertConfigSetting(String name, String value, String tag,
1071 boolean makeDefault, int requestingUserId, boolean forceNotify) {
1072 if (DEBUG) {
1073 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
1074 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1075 + ", " + forceNotify + ")");
1076 }
1077 return mutateConfigSetting(name, value, tag, makeDefault, requestingUserId,
1078 MUTATION_OPERATION_INSERT, forceNotify, 0);
1079 }
1080
Matt Pape6bfc62e2018-11-28 13:16:03 -08001081 private boolean deleteConfigSetting(String name, int requestingUserId, boolean forceNotify) {
1082 if (DEBUG) {
1083 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ", " + requestingUserId
1084 + ", " + forceNotify + ")");
1085 }
1086 return mutateConfigSetting(name, null, null, false, requestingUserId,
1087 MUTATION_OPERATION_DELETE, forceNotify, 0);
1088 }
1089
1090 private void resetConfigSetting(int requestingUserId, int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001091 if (DEBUG) {
1092 Slog.v(LOG_TAG, "resetConfigSetting(" + requestingUserId + ", "
Matt Pape6bfc62e2018-11-28 13:16:03 -08001093 + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001094 }
Matt Pape6bfc62e2018-11-28 13:16:03 -08001095 mutateConfigSetting(null, null, prefix, false, requestingUserId,
Matt Pape1b31a332018-10-17 09:58:28 -07001096 MUTATION_OPERATION_RESET, false, mode);
1097 }
1098
Matt Pape6bfc62e2018-11-28 13:16:03 -08001099 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Pape1b31a332018-10-17 09:58:28 -07001100 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1101 int mode) {
1102 // TODO(b/117663715): check the new permission when it's added.
1103 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1104
Matt Pape1b31a332018-10-17 09:58:28 -07001105 // Perform the mutation.
1106 synchronized (mLock) {
1107 switch (operation) {
1108 case MUTATION_OPERATION_INSERT: {
1109 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Pape6bfc62e2018-11-28 13:16:03 -08001110 UserHandle.USER_SYSTEM, name, value, null, makeDefault,
Matt Pape1b31a332018-10-17 09:58:28 -07001111 getCallingPackage(), forceNotify, null);
1112 }
1113
Matt Pape6bfc62e2018-11-28 13:16:03 -08001114 case MUTATION_OPERATION_DELETE: {
1115 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
1116 UserHandle.USER_SYSTEM, name, forceNotify, null);
1117 }
1118
Matt Pape1b31a332018-10-17 09:58:28 -07001119 case MUTATION_OPERATION_RESET: {
1120 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape6bfc62e2018-11-28 13:16:03 -08001121 UserHandle.USER_SYSTEM, getCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001122 } return true;
1123 }
1124 }
1125
1126 return false;
1127 }
1128
Matt Pape6bfc62e2018-11-28 13:16:03 -08001129 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1130 if (DEBUG) {
1131 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1132 }
1133
1134 synchronized (mLock) {
1135 // Get the settings.
1136 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1137 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1138
1139 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1140 UserHandle.USER_SYSTEM);
1141
1142 final int nameCount = names.size();
1143 Map<String, String> flagsToValues = new HashMap<>(names.size());
1144
1145 for (int i = 0; i < nameCount; i++) {
1146 String name = names.get(i);
1147 Setting setting = settingsState.getSettingLocked(name);
1148 if (prefix == null || setting.getName().startsWith(prefix)) {
1149 flagsToValues.put(setting.getName(), setting.getValue());
1150 }
1151 }
1152
1153 return flagsToValues;
1154 }
1155 }
1156
Svetoslav7ec28e82015-05-20 17:01:10 -07001157 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001158 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001159 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001160 }
1161
Svetoslav7ec28e82015-05-20 17:01:10 -07001162 synchronized (mLock) {
1163 // Get the settings.
1164 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001165 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001166
Chad Brubaker97bccee2017-01-05 15:51:41 -08001167 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1168 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001169
Svetoslav7ec28e82015-05-20 17:01:10 -07001170 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001171
Svetoslav7ec28e82015-05-20 17:01:10 -07001172 String[] normalizedProjection = normalizeProjection(projection);
1173 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001174
Svetoslav7ec28e82015-05-20 17:01:10 -07001175 // Anyone can get the global settings, so no security checks.
1176 for (int i = 0; i < nameCount; i++) {
1177 String name = names.get(i);
1178 Setting setting = settingsState.getSettingLocked(name);
1179 appendSettingToCursor(result, setting);
1180 }
1181
1182 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001183 }
Svetoslav683914b2015-01-15 14:22:26 -08001184 }
1185
Svetoslav7ec28e82015-05-20 17:01:10 -07001186 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001187 if (DEBUG) {
1188 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1189 }
1190
Chad Brubakera6830e72017-04-28 17:34:36 -07001191 // Ensure the caller can access the setting.
1192 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1193
Svetoslav683914b2015-01-15 14:22:26 -08001194 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001195 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001196 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001197 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001198 }
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
1200
Svetoslav Ganove080da92016-12-21 17:10:35 -08001201 private boolean updateGlobalSetting(String name, String value, String tag,
1202 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001203 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001204 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1205 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1206 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001207 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001208 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1209 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001210 }
1211
Svetoslav Ganove080da92016-12-21 17:10:35 -08001212 private boolean insertGlobalSetting(String name, String value, String tag,
1213 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001214 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001215 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1216 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1217 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001218 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001219 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1220 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001221 }
1222
Svet Ganov53a441c2016-04-19 19:38:00 -07001223 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001224 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001225 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1226 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001227 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001228 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1229 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001230 }
1231
Svetoslav Ganove080da92016-12-21 17:10:35 -08001232 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1233 if (DEBUG) {
1234 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1235 + mode + ", " + tag + ")");
1236 }
1237 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1238 MUTATION_OPERATION_RESET, false, mode);
1239 }
1240
1241 private boolean mutateGlobalSetting(String name, String value, String tag,
1242 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1243 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001244 // Make sure the caller can change the settings - treated as secure.
1245 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1246
Svetoslav683914b2015-01-15 14:22:26 -08001247 // Resolve the userId on whose behalf the call is made.
1248 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1249
Makoto Onuki28da2e32015-11-20 11:30:44 -08001250 // If this is a setting that is currently restricted for this user, do not allow
1251 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001252 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1253 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001254 return false;
1255 }
1256
1257 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 synchronized (mLock) {
1259 switch (operation) {
1260 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001261 return mSettingsRegistry.insertSettingLocked(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 }
Svetoslav683914b2015-01-15 14:22:26 -08001265
Svetoslav7ec28e82015-05-20 17:01:10 -07001266 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001267 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001268 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001269 }
Svetoslav683914b2015-01-15 14:22:26 -08001270
Svetoslav7ec28e82015-05-20 17:01:10 -07001271 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001272 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1273 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001274 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001276
1277 case MUTATION_OPERATION_RESET: {
1278 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1279 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1280 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001281 }
1282 }
1283
1284 return false;
1285 }
1286
Christopher Tateb218e762017-04-05 16:34:07 -07001287 private PackageInfo getCallingPackageInfo(int userId) {
1288 try {
1289 return mPackageManager.getPackageInfo(getCallingPackage(),
1290 PackageManager.GET_SIGNATURES, userId);
1291 } catch (RemoteException e) {
1292 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1293 }
1294 }
1295
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001297 if (DEBUG) {
1298 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1299 }
1300
1301 // Resolve the userId on whose behalf the call is made.
1302 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1303
Christopher Tateb218e762017-04-05 16:34:07 -07001304 // The relevant "calling package" userId will be the owning userId for some
1305 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1306 // up front who the effective "new SSAID" user ID for that settings name will be.
1307 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1308 Settings.Secure.ANDROID_ID);
1309 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1310
Svetoslav7ec28e82015-05-20 17:01:10 -07001311 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001312 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001313
Svetoslav7ec28e82015-05-20 17:01:10 -07001314 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001315
Svetoslav7ec28e82015-05-20 17:01:10 -07001316 String[] normalizedProjection = normalizeProjection(projection);
1317 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001318
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 for (int i = 0; i < nameCount; i++) {
1320 String name = names.get(i);
1321 // Determine the owning user as some profile settings are cloned from the parent.
1322 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1323 name);
Svetoslav683914b2015-01-15 14:22:26 -08001324
Alex Klyubin1991f572017-03-03 14:08:36 -08001325 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1326 // This caller is not permitted to access this setting. Pretend the setting
1327 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001328 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001329 }
Svetoslav683914b2015-01-15 14:22:26 -08001330
Mark Rathjen7599f132017-01-23 14:15:54 -08001331 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001332 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1333 final Setting setting;
1334 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001335 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001336 } else {
1337 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1338 name);
1339 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001340 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001341 }
1342
Svetoslav7ec28e82015-05-20 17:01:10 -07001343 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001344 }
Svetoslav683914b2015-01-15 14:22:26 -08001345 }
1346
Svetoslav7ec28e82015-05-20 17:01:10 -07001347 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001348 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1349 }
1350
1351 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001352 if (DEBUG) {
1353 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1354 }
1355
1356 // Resolve the userId on whose behalf the call is made.
1357 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1358
Chad Brubakera6830e72017-04-28 17:34:36 -07001359 // Ensure the caller can access the setting.
1360 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1361
Svetoslav683914b2015-01-15 14:22:26 -08001362 // Determine the owning user as some profile settings are cloned from the parent.
1363 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1364
Alex Klyubin1991f572017-03-03 14:08:36 -08001365 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1366 // This caller is not permitted to access this setting. Pretend the setting doesn't
1367 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001368 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1369 owningUserId);
1370 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001371 }
1372
Christopher Tateb218e762017-04-05 16:34:07 -07001373 // As of Android O, the SSAID is read from an app-specific entry in table
1374 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1375 if (isNewSsaidSetting(name)) {
1376 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1377 synchronized (mLock) {
1378 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001379 }
Christopher Tateb218e762017-04-05 16:34:07 -07001380 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001381 if (enableOverride) {
1382 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1383 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1384 if (overridden != null) {
1385 return overridden;
1386 }
1387 }
1388 }
Mark Rathjend891f012017-01-19 04:10:37 +00001389
Christopher Tateb218e762017-04-05 16:34:07 -07001390 // Not the SSAID; do a straight lookup
1391 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001392 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001393 owningUserId, name);
1394 }
Svetoslav683914b2015-01-15 14:22:26 -08001395 }
1396
Mark Rathjend891f012017-01-19 04:10:37 +00001397 private boolean isNewSsaidSetting(String name) {
1398 return Settings.Secure.ANDROID_ID.equals(name)
1399 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1400 }
1401
Andreas Gampeb58893072018-09-05 16:52:31 -07001402 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001403 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001404 // Get uid of caller (key) used to store ssaid value
1405 String name = Integer.toString(
1406 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1407
1408 if (DEBUG) {
1409 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1410 }
1411
1412 // Retrieve the ssaid from the table if present.
1413 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1414 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001415 // If the app is an Instant App use its stored SSAID instead of our own.
1416 final String instantSsaid;
1417 final long token = Binder.clearCallingIdentity();
1418 try {
1419 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1420 owningUserId);
1421 } catch (RemoteException e) {
1422 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1423 return null;
1424 } finally {
1425 Binder.restoreCallingIdentity(token);
1426 }
Svet Ganov96c99462017-05-05 14:27:13 -07001427
1428 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1429 SETTINGS_TYPE_SSAID, owningUserId);
1430
Chad Brubaker0d277a72017-04-12 16:56:53 -07001431 if (instantSsaid != null) {
1432 // Use the stored value if it is still valid.
1433 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001434 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001435 }
1436 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001437 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1438 true, callingPkg.packageName);
1439 if (!success) {
1440 throw new IllegalStateException("Failed to update instant app android id");
1441 }
Svet Ganov96c99462017-05-05 14:27:13 -07001442 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1443 owningUserId, name);
1444 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001445 }
Mark Rathjend891f012017-01-19 04:10:37 +00001446
1447 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001448 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001449 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1450 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001451 }
1452
Svet Ganov96c99462017-05-05 14:27:13 -07001453 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1454 }
1455
1456 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1457 // SSAID settings are located in a dedicated table for internal bookkeeping
1458 // but for the world they reside in the secure table, so adjust the key here.
1459 // We have a special name when looking it up but want the world to see it as
1460 // "android_id".
1461 if (ssaidSetting != null) {
1462 return settingsState.new Setting(ssaidSetting) {
1463 @Override
1464 public int getKey() {
1465 final int userId = getUserIdFromKey(super.getKey());
1466 return makeKey(SETTINGS_TYPE_SECURE, userId);
1467 }
1468
1469 @Override
1470 public String getName() {
1471 return Settings.Secure.ANDROID_ID;
1472 }
1473 };
1474 }
1475 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001476 }
1477
Makoto Onuki0000d322017-11-28 16:31:47 -08001478 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1479 synchronized (mLock) {
1480 final Setting setting = getGlobalSetting(
1481 Global.LOCATION_GLOBAL_KILL_SWITCH);
1482 if (!"1".equals(setting.getValue())) {
1483 return null;
1484 }
1485 // Global kill-switch is enabled. Return an empty value.
1486 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1487 SETTINGS_TYPE_SECURE, owningUserId);
1488 return settingsState.new Setting(
1489 Secure.LOCATION_PROVIDERS_ALLOWED,
1490 "", // value
1491 "", // tag
1492 "", // default value
1493 "", // package name
1494 false, // from system
1495 "0" // id
1496 ) {
1497 @Override
1498 public boolean update(String value, boolean setDefault, String packageName,
1499 String tag, boolean forceNonSystemPackage) {
1500 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1501 return false;
1502 }
1503 };
1504 }
1505 }
1506
Svetoslav Ganove080da92016-12-21 17:10:35 -08001507 private boolean insertSecureSetting(String name, String value, String tag,
1508 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001509 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001510 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001511 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1512 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001513 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001514 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1515 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001516 }
1517
Svet Ganov53a441c2016-04-19 19:38:00 -07001518 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001519 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001520 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1521 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001522 }
1523
Svetoslav Ganove080da92016-12-21 17:10:35 -08001524 return mutateSecureSetting(name, null, null, false, requestingUserId,
1525 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001526 }
1527
Svetoslav Ganove080da92016-12-21 17:10:35 -08001528 private boolean updateSecureSetting(String name, String value, String tag,
1529 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001530 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001531 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001532 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1533 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001534 }
1535
Svetoslav Ganove080da92016-12-21 17:10:35 -08001536 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1537 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001538 }
1539
Svetoslav Ganove080da92016-12-21 17:10:35 -08001540 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1541 if (DEBUG) {
1542 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1543 + mode + ", " + tag + ")");
1544 }
1545
1546 mutateSecureSetting(null, null, tag, false, requestingUserId,
1547 MUTATION_OPERATION_RESET, false, mode);
1548 }
1549
1550 private boolean mutateSecureSetting(String name, String value, String tag,
1551 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1552 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001553 // Make sure the caller can change the settings.
1554 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1555
Svetoslav683914b2015-01-15 14:22:26 -08001556 // Resolve the userId on whose behalf the call is made.
1557 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1558
Makoto Onuki28da2e32015-11-20 11:30:44 -08001559 // If this is a setting that is currently restricted for this user, do not allow
1560 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001561 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1562 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001563 return false;
1564 }
1565
1566 // Determine the owning user as some profile settings are cloned from the parent.
1567 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1568
1569 // Only the owning user can change the setting.
1570 if (owningUserId != callingUserId) {
1571 return false;
1572 }
1573
1574 // Special cases for location providers (sigh).
1575 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001576 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1577 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001578 }
1579
1580 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001581 synchronized (mLock) {
1582 switch (operation) {
1583 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001584 return mSettingsRegistry.insertSettingLocked(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 }
Svetoslav683914b2015-01-15 14:22:26 -08001588
Svetoslav7ec28e82015-05-20 17:01:10 -07001589 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001590 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001591 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001592 }
Svetoslav683914b2015-01-15 14:22:26 -08001593
Svetoslav7ec28e82015-05-20 17:01:10 -07001594 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001595 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001596 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001597 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001598 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001599
1600 case MUTATION_OPERATION_RESET: {
1601 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1602 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1603 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001604 }
1605 }
1606
1607 return false;
1608 }
1609
Svetoslav7ec28e82015-05-20 17:01:10 -07001610 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001611 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001612 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001613 }
1614
1615 // Resolve the userId on whose behalf the call is made.
1616 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1617
Svetoslav7ec28e82015-05-20 17:01:10 -07001618 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001619 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001620
Svetoslav7ec28e82015-05-20 17:01:10 -07001621 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001622
Svetoslav7ec28e82015-05-20 17:01:10 -07001623 String[] normalizedProjection = normalizeProjection(projection);
1624 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001625
Svetoslav7ec28e82015-05-20 17:01:10 -07001626 for (int i = 0; i < nameCount; i++) {
1627 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001628
Svetoslav7ec28e82015-05-20 17:01:10 -07001629 // Determine the owning user as some profile settings are cloned from the parent.
1630 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1631 name);
Svetoslav683914b2015-01-15 14:22:26 -08001632
Svetoslav7ec28e82015-05-20 17:01:10 -07001633 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001634 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001635 appendSettingToCursor(result, setting);
1636 }
1637
1638 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001639 }
Svetoslav683914b2015-01-15 14:22:26 -08001640 }
1641
Svetoslav7ec28e82015-05-20 17:01:10 -07001642 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001643 if (DEBUG) {
1644 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1645 }
1646
1647 // Resolve the userId on whose behalf the call is made.
1648 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1649
Chad Brubakera6830e72017-04-28 17:34:36 -07001650 // Ensure the caller can access the setting.
1651 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001652
Svetoslav683914b2015-01-15 14:22:26 -08001653 // Determine the owning user as some profile settings are cloned from the parent.
1654 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1655
1656 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001657 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001658 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001659 }
Svetoslav683914b2015-01-15 14:22:26 -08001660 }
1661
Svetoslav7ec28e82015-05-20 17:01:10 -07001662 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001663 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001664 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001665 + requestingUserId + ")");
1666 }
1667
Svetoslav7ec28e82015-05-20 17:01:10 -07001668 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001669 }
1670
Svetoslav7ec28e82015-05-20 17:01:10 -07001671 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001672 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001673 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001674 }
1675
Svetoslav7ec28e82015-05-20 17:01:10 -07001676 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001677 }
1678
Svetoslav7ec28e82015-05-20 17:01:10 -07001679 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001680 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001681 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001682 + requestingUserId + ")");
1683 }
1684
Svetoslav7ec28e82015-05-20 17:01:10 -07001685 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001686 }
1687
Svetoslav7ec28e82015-05-20 17:01:10 -07001688 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001689 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001690 if (!hasWriteSecureSettingsPermission()) {
1691 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1692 // operation is allowed for the calling package through appops.
1693 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1694 Binder.getCallingUid(), getCallingPackage(), true)) {
1695 return false;
1696 }
Svetoslav683914b2015-01-15 14:22:26 -08001697 }
1698
Svetoslav683914b2015-01-15 14:22:26 -08001699 // Resolve the userId on whose behalf the call is made.
1700 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1701
yuemingw1d13eae2018-01-30 17:27:54 +00001702 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1703 name, callingUserId, value, Binder.getCallingUid())) {
1704 return false;
1705 }
1706
Svetoslavd8d25e02015-11-20 13:09:26 -08001707 // Enforce what the calling package can mutate the system settings.
1708 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1709
Svetoslav683914b2015-01-15 14:22:26 -08001710 // Determine the owning user as some profile settings are cloned from the parent.
1711 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1712
1713 // Only the owning user id can change the setting.
1714 if (owningUserId != callingUserId) {
1715 return false;
1716 }
1717
Jeff Sharkey413573a2016-02-22 17:52:45 -07001718 // Invalidate any relevant cache files
1719 String cacheName = null;
1720 if (Settings.System.RINGTONE.equals(name)) {
1721 cacheName = Settings.System.RINGTONE_CACHE;
1722 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1723 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1724 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1725 cacheName = Settings.System.ALARM_ALERT_CACHE;
1726 }
1727 if (cacheName != null) {
1728 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001729 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001730 cacheFile.delete();
1731 }
1732
Svetoslav683914b2015-01-15 14:22:26 -08001733 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001734 synchronized (mLock) {
1735 switch (operation) {
1736 case MUTATION_OPERATION_INSERT: {
1737 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001738 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001739 owningUserId, name, value, null, false, getCallingPackage(),
1740 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001741 }
1742
1743 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001744 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001745 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001746 }
1747
1748 case MUTATION_OPERATION_UPDATE: {
1749 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001750 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001751 owningUserId, name, value, null, false, getCallingPackage(),
1752 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001753 }
Svetoslav683914b2015-01-15 14:22:26 -08001754 }
1755
Svetoslav7ec28e82015-05-20 17:01:10 -07001756 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001757 }
Svetoslav683914b2015-01-15 14:22:26 -08001758 }
1759
Billy Lau6ad2d662015-07-18 00:26:58 +01001760 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001761 // Write secure settings is a more protected permission. If caller has it we are good.
1762 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1763 == PackageManager.PERMISSION_GRANTED) {
1764 return true;
1765 }
1766
Svetoslavf41334b2015-06-23 12:06:03 -07001767 return false;
1768 }
1769
Svetoslav683914b2015-01-15 14:22:26 -08001770 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001771 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001772 if (validator != null && !validator.validate(value)) {
1773 throw new IllegalArgumentException("Invalid value: " + value
1774 + " for setting: " + name);
1775 }
1776 }
1777
Alex Klyubin1991f572017-03-03 14:08:36 -08001778 /**
1779 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1780 */
1781 private boolean isSecureSettingAccessible(String name, int callingUserId,
1782 int owningUserId) {
1783 // Special case for location (sigh).
1784 // This check is not inside the name-based checks below because this method performs checks
1785 // only if the calling user ID is not the same as the owning user ID.
1786 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1787 return false;
1788 }
1789
1790 switch (name) {
1791 case "bluetooth_address":
1792 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1793 // address in this secure setting. Secure settings can normally be read by any app,
1794 // which thus enables them to bypass the recently introduced restrictions on access
1795 // to device identifiers.
1796 // To mitigate this we make this setting available only to callers privileged to see
1797 // this device's MAC addresses, same as through public API
1798 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1799 return getContext().checkCallingOrSelfPermission(
1800 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1801 default:
1802 return true;
1803 }
1804 }
1805
Svetoslav683914b2015-01-15 14:22:26 -08001806 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1807 int owningUserId) {
1808 // Optimization - location providers are restricted only for managed profiles.
1809 if (callingUserId == owningUserId) {
1810 return false;
1811 }
1812 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1813 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1814 new UserHandle(callingUserId))) {
1815 return true;
1816 }
1817 return false;
1818 }
1819
Svetoslav683914b2015-01-15 14:22:26 -08001820 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1821 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1822 }
1823
1824 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001825 final int parentId;
1826 // Resolves dependency if setting has a dependency and the calling user has a parent
1827 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1828 && (parentId = getGroupParentLocked(userId)) != userId) {
1829 // The setting has a dependency and the profile has a parent
1830 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001831 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1832 final long token = Binder.clearCallingIdentity();
1833 try {
1834 Setting settingObj = getSecureSetting(dependency, userId);
1835 if (settingObj != null && settingObj.getValue().equals("1")) {
1836 return parentId;
1837 }
1838 } finally {
1839 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001840 }
1841 }
Svetoslav683914b2015-01-15 14:22:26 -08001842 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1843 }
1844
1845 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1846 final int parentId = getGroupParentLocked(userId);
1847 if (parentId != userId && keys.contains(name)) {
1848 return parentId;
1849 }
1850 return userId;
1851 }
1852
Svetoslavf41334b2015-06-23 12:06:03 -07001853 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001854 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001855 // System/root/shell can mutate whatever secure settings they want.
1856 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001857 final int appId = UserHandle.getAppId(callingUid);
1858 if (appId == android.os.Process.SYSTEM_UID
1859 || appId == Process.SHELL_UID
1860 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001861 return;
1862 }
1863
1864 switch (operation) {
1865 case MUTATION_OPERATION_INSERT:
1866 // Insert updates.
1867 case MUTATION_OPERATION_UPDATE: {
1868 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1869 return;
1870 }
1871
1872 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001873 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001874
1875 // Privileged apps can do whatever they want.
1876 if ((packageInfo.applicationInfo.privateFlags
1877 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1878 return;
1879 }
1880
1881 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1882 packageInfo.applicationInfo.targetSdkVersion, name);
1883 } break;
1884
1885 case MUTATION_OPERATION_DELETE: {
1886 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1887 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1888 throw new IllegalArgumentException("You cannot delete system defined"
1889 + " secure settings.");
1890 }
1891
1892 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001893 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001894
1895 // Privileged apps can do whatever they want.
1896 if ((packageInfo.applicationInfo.privateFlags &
1897 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1898 return;
1899 }
1900
1901 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1902 packageInfo.applicationInfo.targetSdkVersion, name);
1903 } break;
1904 }
1905 }
1906
Todd Kennedybe0b8892017-02-15 14:13:52 -08001907 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001908 switch (settingsType) {
1909 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001910 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001911 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001912 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001913 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001914 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001915 default:
1916 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1917 }
1918 }
1919
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001920 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1921 switch (settingsType) {
1922 case SETTINGS_TYPE_GLOBAL:
1923 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1924 case SETTINGS_TYPE_SYSTEM:
1925 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1926 case SETTINGS_TYPE_SECURE:
1927 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1928 default:
1929 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1930 }
1931 }
1932
Andreas Gampeb58893072018-09-05 16:52:31 -07001933 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001934 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001935 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1936 // in the current form.
1937 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001938 }
1939
Chad Brubakera6830e72017-04-28 17:34:36 -07001940 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001941 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1942 return;
1943 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001944 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001945 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001946 return;
1947 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001948 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1949 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001950 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1951 // breakage in the current form.
1952 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1953 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001954 }
1955 }
1956
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001957 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1958 // We always use the callingUid for this lookup. This means that if hypothetically an
1959 // app was installed in user A with cross user and in user B as an Instant App
1960 // the app in A would be able to see all the settings in user B. However since cross
1961 // user is a system permission and the app must be uninstalled in B and then installed as
1962 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001963 ApplicationInfo ai = null;
1964 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001965 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1966 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001967 } catch (RemoteException ignored) {
1968 }
1969 if (ai == null) {
1970 throw new IllegalStateException("Failed to lookup info for package "
1971 + getCallingPackage());
1972 }
1973 return ai;
1974 }
1975
Xiaohui Chen43765b72015-08-31 10:57:33 -07001976 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001977 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001978 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1979 getCallingPackage(), 0, userId);
1980 if (packageInfo != null) {
1981 return packageInfo;
1982 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001983 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001984 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001985 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001986 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001987 }
1988
1989 private int getGroupParentLocked(int userId) {
1990 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001991 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001992 return userId;
1993 }
1994 // We are in the same process with the user manager and the returned
1995 // user info is a cached instance, so just look up instead of cache.
1996 final long identity = Binder.clearCallingIdentity();
1997 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001998 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001999 UserInfo userInfo = mUserManager.getProfileParent(userId);
2000 return (userInfo != null) ? userInfo.id : userId;
2001 } finally {
2002 Binder.restoreCallingIdentity(identity);
2003 }
2004 }
2005
Svetoslav683914b2015-01-15 14:22:26 -08002006 private void enforceWritePermission(String permission) {
2007 if (getContext().checkCallingOrSelfPermission(permission)
2008 != PackageManager.PERMISSION_GRANTED) {
2009 throw new SecurityException("Permission denial: writing to settings requires:"
2010 + permission);
2011 }
2012 }
2013
2014 /*
2015 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2016 * This setting contains a list of the currently enabled location providers.
2017 * But helper functions in android.providers.Settings can enable or disable
2018 * a single provider by using a "+" or "-" prefix before the provider name.
2019 *
yuemingw1d13eae2018-01-30 17:27:54 +00002020 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2021 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2022 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002023 *
Svetoslav683914b2015-01-15 14:22:26 -08002024 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002025 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002026 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002027 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2028 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002029 if (TextUtils.isEmpty(value)) {
2030 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002031 }
Maggie83e03f52018-03-16 12:22:20 -07002032 Setting oldSetting = getSecureSetting(
2033 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2034 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002035 return false;
2036 }
Maggie83e03f52018-03-16 12:22:20 -07002037 String oldProviders = oldSetting.getValue();
2038 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2039 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2040 Set<String> newProvidersSet = new ArraySet<>();
2041 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002042
Maggie83e03f52018-03-16 12:22:20 -07002043 String[] providerUpdates = value.split(",");
2044 boolean inputError = false;
2045 for (String provider : providerUpdates) {
2046 // do not update location_providers_allowed when input is invalid
2047 if (TextUtils.isEmpty(provider)) {
2048 inputError = true;
2049 break;
Svetoslav683914b2015-01-15 14:22:26 -08002050 }
Maggie83e03f52018-03-16 12:22:20 -07002051 final char prefix = provider.charAt(0);
2052 // do not update location_providers_allowed when input is invalid
2053 if (prefix != '+' && prefix != '-') {
2054 inputError = true;
2055 break;
Svetoslav683914b2015-01-15 14:22:26 -08002056 }
Maggie83e03f52018-03-16 12:22:20 -07002057 // skip prefix
2058 provider = provider.substring(1);
2059 if (prefix == '+') {
2060 newProvidersSet.add(provider);
2061 } else if (prefix == '-') {
2062 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002063 }
Maggie83e03f52018-03-16 12:22:20 -07002064 }
2065 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2066 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002067 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002068 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002069 mSettingsRegistry.notifyForSettingsChange(
2070 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002071 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2072 }
Svetoslav683914b2015-01-15 14:22:26 -08002073 return false;
2074 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002075 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002076 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2077 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002078 }
2079
Svetoslav683914b2015-01-15 14:22:26 -08002080 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2081 int targetSdkVersion, String name) {
2082 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2083 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2084 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2085 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2086 + " This will soon become an error.");
2087 } else {
2088 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2089 + " This will soon become an error.");
2090 }
2091 } else {
2092 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2093 throw new IllegalArgumentException("You cannot change private secure settings.");
2094 } else {
2095 throw new IllegalArgumentException("You cannot keep your settings in"
2096 + " the secure settings.");
2097 }
2098 }
2099 }
2100
2101 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2102 if (requestingUserId == UserHandle.getCallingUserId()) {
2103 return requestingUserId;
2104 }
2105 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2106 Binder.getCallingUid(), requestingUserId, false, true,
2107 "get/set setting for user", null);
2108 }
2109
Svet Ganov53a441c2016-04-19 19:38:00 -07002110 private Bundle packageValueForCallResult(Setting setting,
2111 boolean trackingGeneration) {
2112 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002113 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002114 return NULL_SETTING_BUNDLE;
2115 }
2116 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002117 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002118 Bundle result = new Bundle();
2119 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002120 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002121
Svetoslav Ganove080da92016-12-21 17:10:35 -08002122 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002123 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002124 }
2125
2126 private static int getRequestingUserId(Bundle args) {
2127 final int callingUserId = UserHandle.getCallingUserId();
2128 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2129 : callingUserId;
2130 }
2131
Svet Ganov53a441c2016-04-19 19:38:00 -07002132 private boolean isTrackingGeneration(Bundle args) {
2133 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2134 }
2135
Svetoslav683914b2015-01-15 14:22:26 -08002136 private static String getSettingValue(Bundle args) {
2137 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2138 }
2139
Svetoslav Ganove080da92016-12-21 17:10:35 -08002140 private static String getSettingTag(Bundle args) {
2141 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2142 }
2143
Matt Pape6bfc62e2018-11-28 13:16:03 -08002144 private static String getSettingPrefix(Bundle args) {
2145 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2146 // Append '/' to ensure we only match properties with this exact prefix.
2147 // i.e. "foo" should match "foo/property" but not "foobar/property"
2148 return prefix != null ? prefix + "/" : null;
2149 }
2150
Svetoslav Ganove080da92016-12-21 17:10:35 -08002151 private static boolean getSettingMakeDefault(Bundle args) {
2152 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2153 }
2154
2155 private static int getResetModeEnforcingPermission(Bundle args) {
2156 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2157 switch (mode) {
2158 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2159 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2160 throw new SecurityException("Only system, shell/root on a "
2161 + "debuggable build can reset to untrusted defaults");
2162 }
2163 return mode;
2164 }
2165 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2166 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2167 throw new SecurityException("Only system, shell/root on a "
2168 + "debuggable build can reset untrusted changes");
2169 }
2170 return mode;
2171 }
2172 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2173 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2174 throw new SecurityException("Only system, shell/root on a "
2175 + "debuggable build can reset to trusted defaults");
2176 }
2177 return mode;
2178 }
2179 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2180 return mode;
2181 }
2182 }
2183 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2184 }
2185
2186 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2187 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2188 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2189 && (appId == SHELL_UID || appId == ROOT_UID));
2190 }
2191
Svetoslav683914b2015-01-15 14:22:26 -08002192 private static String getValidTableOrThrow(Uri uri) {
2193 if (uri.getPathSegments().size() > 0) {
2194 String table = uri.getPathSegments().get(0);
2195 if (DatabaseHelper.isValidTable(table)) {
2196 return table;
2197 }
2198 throw new IllegalArgumentException("Bad root path: " + table);
2199 }
2200 throw new IllegalArgumentException("Invalid URI:" + uri);
2201 }
2202
2203 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002204 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002205 return new MatrixCursor(projection, 0);
2206 }
2207 MatrixCursor cursor = new MatrixCursor(projection, 1);
2208 appendSettingToCursor(cursor, setting);
2209 return cursor;
2210 }
2211
2212 private static String[] normalizeProjection(String[] projection) {
2213 if (projection == null) {
2214 return ALL_COLUMNS;
2215 }
2216
2217 final int columnCount = projection.length;
2218 for (int i = 0; i < columnCount; i++) {
2219 String column = projection[i];
2220 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2221 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002222 }
2223 }
2224
Svetoslav683914b2015-01-15 14:22:26 -08002225 return projection;
2226 }
2227
2228 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002229 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002230 return;
2231 }
Svetoslav683914b2015-01-15 14:22:26 -08002232 final int columnCount = cursor.getColumnCount();
2233
2234 String[] values = new String[columnCount];
2235
2236 for (int i = 0; i < columnCount; i++) {
2237 String column = cursor.getColumnName(i);
2238
2239 switch (column) {
2240 case Settings.NameValueTable._ID: {
2241 values[i] = setting.getId();
2242 } break;
2243
2244 case Settings.NameValueTable.NAME: {
2245 values[i] = setting.getName();
2246 } break;
2247
2248 case Settings.NameValueTable.VALUE: {
2249 values[i] = setting.getValue();
2250 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002251 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002252 }
2253
Svetoslav683914b2015-01-15 14:22:26 -08002254 cursor.addRow(values);
2255 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002256
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002257 private static boolean isKeyValid(String key) {
2258 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2259 }
2260
Svetoslav683914b2015-01-15 14:22:26 -08002261 private static final class Arguments {
2262 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2263 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2264
2265 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2266 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2267
2268 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2269 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2270
2271 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2272 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2273
2274 public final String table;
2275 public final String name;
2276
2277 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2278 final int segmentSize = uri.getPathSegments().size();
2279 switch (segmentSize) {
2280 case 1: {
2281 if (where != null
2282 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2283 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2284 && whereArgs.length == 1) {
2285 name = whereArgs[0];
2286 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002287 return;
Svetoslav683914b2015-01-15 14:22:26 -08002288 } else if (where != null
2289 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2290 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2291 final int startIndex = Math.max(where.indexOf("'"),
2292 where.indexOf("\"")) + 1;
2293 final int endIndex = Math.max(where.lastIndexOf("'"),
2294 where.lastIndexOf("\""));
2295 name = where.substring(startIndex, endIndex);
2296 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002297 return;
Svetoslav683914b2015-01-15 14:22:26 -08002298 } else if (supportAll && where == null && whereArgs == null) {
2299 name = null;
2300 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002301 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002302 }
Svetoslav683914b2015-01-15 14:22:26 -08002303 } break;
2304
Svetoslav28494652015-02-12 14:11:42 -08002305 case 2: {
2306 if (where == null && whereArgs == null) {
2307 name = uri.getPathSegments().get(1);
2308 table = computeTableForSetting(uri, name);
2309 return;
2310 }
2311 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002312 }
Svetoslav28494652015-02-12 14:11:42 -08002313
2314 EventLogTags.writeUnsupportedSettingsQuery(
2315 uri.toSafeString(), where, Arrays.toString(whereArgs));
2316 String message = String.format( "Supported SQL:\n"
2317 + " uri content://some_table/some_property with null where and where args\n"
2318 + " uri content://some_table with query name=? and single name as arg\n"
2319 + " uri content://some_table with query name=some_name and null args\n"
2320 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2321 Arrays.toString(whereArgs));
2322 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002323 }
2324
Svetoslav28494652015-02-12 14:11:42 -08002325 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002326 String table = getValidTableOrThrow(uri);
2327
2328 if (name != null) {
2329 if (sSystemMovedToSecureSettings.contains(name)) {
2330 table = TABLE_SECURE;
2331 }
2332
2333 if (sSystemMovedToGlobalSettings.contains(name)) {
2334 table = TABLE_GLOBAL;
2335 }
2336
2337 if (sSecureMovedToGlobalSettings.contains(name)) {
2338 table = TABLE_GLOBAL;
2339 }
2340
2341 if (sGlobalMovedToSecureSettings.contains(name)) {
2342 table = TABLE_SECURE;
2343 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002344 }
Svetoslav683914b2015-01-15 14:22:26 -08002345
2346 return table;
2347 }
2348 }
2349
2350 final class SettingsRegistry {
2351 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2352
Svetoslav683914b2015-01-15 14:22:26 -08002353 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2354 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2355 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002356 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002357 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002358
2359 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002360
2361 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2362
Svet Ganov53a441c2016-04-19 19:38:00 -07002363 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002364
Svetoslav7e0683b2015-08-03 16:02:52 -07002365 private final Handler mHandler;
2366
Svet Ganov53a441c2016-04-19 19:38:00 -07002367 private final BackupManager mBackupManager;
2368
Amith Yamasani39452022017-03-21 15:23:47 -07002369 private String mSettingsCreationBuildId;
2370
Svetoslav683914b2015-01-15 14:22:26 -08002371 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002372 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002373 mGenerationRegistry = new GenerationRegistry(mLock);
2374 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002375 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002376 syncSsaidTableOnStart();
2377 }
2378
2379 private void generateUserKeyLocked(int userId) {
2380 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002381 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002382 final SecureRandom rand = new SecureRandom();
2383 rand.nextBytes(keyBytes);
2384
2385 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002386 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002387
2388 // Store the key in the ssaid table.
2389 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2390 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2391 true, SettingsState.SYSTEM_PACKAGE_NAME);
2392
2393 if (!success) {
2394 throw new IllegalStateException("Ssaid settings not accessible");
2395 }
2396 }
2397
Mark Rathjen7599f132017-01-23 14:15:54 -08002398 private byte[] getLengthPrefix(byte[] data) {
2399 return ByteBuffer.allocate(4).putInt(data.length).array();
2400 }
2401
Christopher Tateb218e762017-04-05 16:34:07 -07002402 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002403 // Read the user's key from the ssaid table.
2404 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002405 if (userKeySetting == null || userKeySetting.isNull()
2406 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002407 // Lazy initialize and store the user key.
2408 generateUserKeyLocked(userId);
2409 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002410 if (userKeySetting == null || userKeySetting.isNull()
2411 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002412 throw new IllegalStateException("User key not accessible");
2413 }
2414 }
2415 final String userKey = userKeySetting.getValue();
2416
2417 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002418 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2419
2420 // Validate that the key is of expected length.
2421 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2422 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002423 throw new IllegalStateException("User key invalid");
2424 }
2425
Mark Rathjen7599f132017-01-23 14:15:54 -08002426 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002427 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002428 m = Mac.getInstance("HmacSHA256");
2429 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002430 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002431 throw new IllegalStateException("HmacSHA256 is not available", e);
2432 } catch (InvalidKeyException e) {
2433 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002434 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002435
Mark Rathjenf42dd912017-06-05 19:04:34 -07002436 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002437 for (int i = 0; i < callingPkg.signatures.length; i++) {
2438 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002439 m.update(getLengthPrefix(sig), 0, 4);
2440 m.update(sig);
2441 }
Mark Rathjend891f012017-01-19 04:10:37 +00002442
2443 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002444 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2445 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002446
2447 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002448 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002449 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2450 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002451 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002452
2453 if (!success) {
2454 throw new IllegalStateException("Ssaid settings not accessible");
2455 }
2456
2457 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2458 }
2459
2460 public void syncSsaidTableOnStart() {
2461 synchronized (mLock) {
2462 // Verify that each user's packages and ssaid's are in sync.
2463 for (UserInfo user : mUserManager.getUsers(true)) {
2464 // Get all uids for the user's packages.
2465 final List<PackageInfo> packages;
2466 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002467 packages = mPackageManager.getInstalledPackages(
2468 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2469 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002470 } catch (RemoteException e) {
2471 throw new IllegalStateException("Package manager not available");
2472 }
2473 final Set<String> appUids = new HashSet<>();
2474 for (PackageInfo info : packages) {
2475 appUids.add(Integer.toString(info.applicationInfo.uid));
2476 }
2477
2478 // Get all uids currently stored in the user's ssaid table.
2479 final Set<String> ssaidUids = new HashSet<>(
2480 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2481 ssaidUids.remove(SSAID_USER_KEY);
2482
2483 // Perform a set difference for the appUids and ssaidUids.
2484 ssaidUids.removeAll(appUids);
2485
2486 // If there are ssaidUids left over they need to be removed from the table.
2487 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2488 user.id);
2489 for (String uid : ssaidUids) {
2490 ssaidSettings.deleteSettingLocked(uid);
2491 }
2492 }
2493 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002494 }
2495
Svetoslav683914b2015-01-15 14:22:26 -08002496 public List<String> getSettingsNamesLocked(int type, int userId) {
2497 final int key = makeKey(type, userId);
2498 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002499 if (settingsState == null) {
2500 return new ArrayList<String>();
2501 }
Svetoslav683914b2015-01-15 14:22:26 -08002502 return settingsState.getSettingNamesLocked();
2503 }
2504
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002505 public SparseBooleanArray getKnownUsersLocked() {
2506 SparseBooleanArray users = new SparseBooleanArray();
2507 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2508 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2509 }
2510 return users;
2511 }
2512
Kweku Adamsb0886f32017-10-31 15:32:09 -07002513 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002514 public SettingsState getSettingsLocked(int type, int userId) {
2515 final int key = makeKey(type, userId);
2516 return peekSettingsStateLocked(key);
2517 }
2518
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002519 public boolean ensureSettingsForUserLocked(int userId) {
2520 // First make sure this user actually exists.
2521 if (mUserManager.getUserInfo(userId) == null) {
2522 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2523 return false;
2524 }
2525
Svetoslav683914b2015-01-15 14:22:26 -08002526 // Migrate the setting for this user if needed.
2527 migrateLegacySettingsForUserIfNeededLocked(userId);
2528
Matt Pape1b31a332018-10-17 09:58:28 -07002529 // Ensure config settings loaded if owner.
2530 if (userId == UserHandle.USER_SYSTEM) {
2531 final int configKey
2532 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2533 ensureSettingsStateLocked(configKey);
2534 }
2535
Svetoslav683914b2015-01-15 14:22:26 -08002536 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002537 if (userId == UserHandle.USER_SYSTEM) {
2538 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002539 ensureSettingsStateLocked(globalKey);
2540 }
2541
2542 // Ensure secure settings loaded.
2543 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2544 ensureSettingsStateLocked(secureKey);
2545
2546 // Make sure the secure settings have an Android id set.
2547 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2548 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2549
2550 // Ensure system settings loaded.
2551 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2552 ensureSettingsStateLocked(systemKey);
2553
Mark Rathjend891f012017-01-19 04:10:37 +00002554 // Ensure secure settings loaded.
2555 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2556 ensureSettingsStateLocked(ssaidKey);
2557
Svetoslav683914b2015-01-15 14:22:26 -08002558 // Upgrade the settings to the latest version.
2559 UpgradeController upgrader = new UpgradeController(userId);
2560 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002561 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002562 }
2563
2564 private void ensureSettingsStateLocked(int key) {
2565 if (mSettingsStates.get(key) == null) {
2566 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002567 SettingsState settingsState = new SettingsState(getContext(), mLock,
2568 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002569 mSettingsStates.put(key, settingsState);
2570 }
2571 }
2572
2573 public void removeUserStateLocked(int userId, boolean permanently) {
2574 // We always keep the global settings in memory.
2575
2576 // Nuke system settings.
2577 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2578 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2579 if (systemSettingsState != null) {
2580 if (permanently) {
2581 mSettingsStates.remove(systemKey);
2582 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002583 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002584 systemSettingsState.destroyLocked(new Runnable() {
2585 @Override
2586 public void run() {
2587 mSettingsStates.remove(systemKey);
2588 }
2589 });
2590 }
2591 }
2592
2593 // Nuke secure settings.
2594 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2595 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2596 if (secureSettingsState != null) {
2597 if (permanently) {
2598 mSettingsStates.remove(secureKey);
2599 secureSettingsState.destroyLocked(null);
2600 } else {
2601 secureSettingsState.destroyLocked(new Runnable() {
2602 @Override
2603 public void run() {
2604 mSettingsStates.remove(secureKey);
2605 }
2606 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002607 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002608 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002609
Mark Rathjend891f012017-01-19 04:10:37 +00002610 // Nuke ssaid settings.
2611 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2612 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2613 if (ssaidSettingsState != null) {
2614 if (permanently) {
2615 mSettingsStates.remove(ssaidKey);
2616 ssaidSettingsState.destroyLocked(null);
2617 } else {
2618 ssaidSettingsState.destroyLocked(new Runnable() {
2619 @Override
2620 public void run() {
2621 mSettingsStates.remove(ssaidKey);
2622 }
2623 });
2624 }
2625 }
2626
Svet Ganov53a441c2016-04-19 19:38:00 -07002627 // Nuke generation tracking data
2628 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002629 }
2630
Svetoslav683914b2015-01-15 14:22:26 -08002631 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002632 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2633 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002634 final int key = makeKey(type, userId);
2635
Svetoslav Ganove080da92016-12-21 17:10:35 -08002636 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002637 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002638 if (settingsState != null) {
2639 success = settingsState.insertSettingLocked(name, value,
2640 tag, makeDefault, packageName);
2641 }
Svetoslav683914b2015-01-15 14:22:26 -08002642
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002643 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2644 settingsState.persistSyncLocked();
2645 }
2646
Svet Ganov53a441c2016-04-19 19:38:00 -07002647 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002648 notifyForSettingsChange(key, name);
2649 }
2650 return success;
2651 }
2652
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002653 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2654 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002655 final int key = makeKey(type, userId);
2656
Svetoslav Ganove080da92016-12-21 17:10:35 -08002657 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002658 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002659 if (settingsState != null) {
2660 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002661 }
Svetoslav683914b2015-01-15 14:22:26 -08002662
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002663 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2664 settingsState.persistSyncLocked();
2665 }
2666
Svet Ganov53a441c2016-04-19 19:38:00 -07002667 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002668 notifyForSettingsChange(key, name);
2669 }
2670 return success;
2671 }
2672
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002673 public boolean updateSettingLocked(int type, int userId, String name, String value,
2674 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2675 Set<String> criticalSettings) {
2676 final int key = makeKey(type, userId);
2677
2678 boolean success = false;
2679 SettingsState settingsState = peekSettingsStateLocked(key);
2680 if (settingsState != null) {
2681 success = settingsState.updateSettingLocked(name, value, tag,
2682 makeDefault, packageName);
2683 }
2684
2685 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2686 settingsState.persistSyncLocked();
2687 }
2688
2689 if (forceNotify || success) {
2690 notifyForSettingsChange(key, name);
2691 }
2692
2693 return success;
2694 }
2695
Svetoslav683914b2015-01-15 14:22:26 -08002696 public Setting getSettingLocked(int type, int userId, String name) {
2697 final int key = makeKey(type, userId);
2698
2699 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002700 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002701 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002702 }
Mark Rathjend891f012017-01-19 04:10:37 +00002703
2704 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002705 return settingsState.getSettingLocked(name);
2706 }
2707
Svetoslav Ganove080da92016-12-21 17:10:35 -08002708 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2709 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002710 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2711 }
2712
2713 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2714 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002715 final int key = makeKey(type, userId);
2716 SettingsState settingsState = peekSettingsStateLocked(key);
2717 if (settingsState == null) {
2718 return;
2719 }
2720
2721 switch (mode) {
2722 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2723 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002724 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002725 Setting setting = settingsState.getSettingLocked(name);
2726 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002727 if ((tag != null && !tag.equals(setting.getTag()))
2728 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002729 continue;
2730 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002731 if (settingsState.resetSettingLocked(name)) {
2732 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002733 notifyForSettingsChange(key, name);
2734 }
2735 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002736 if (someSettingChanged) {
2737 settingsState.persistSyncLocked();
2738 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002739 }
2740 } break;
2741
2742 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2743 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002744 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002745 Setting setting = settingsState.getSettingLocked(name);
2746 if (!SettingsState.isSystemPackage(getContext(),
2747 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002748 if (prefix != null && !setting.getName().startsWith(prefix)) {
2749 continue;
2750 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002751 if (settingsState.resetSettingLocked(name)) {
2752 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002753 notifyForSettingsChange(key, name);
2754 }
2755 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002756 if (someSettingChanged) {
2757 settingsState.persistSyncLocked();
2758 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002759 }
2760 } break;
2761
2762 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2763 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002764 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002765 Setting setting = settingsState.getSettingLocked(name);
2766 if (!SettingsState.isSystemPackage(getContext(),
2767 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002768 if (prefix != null && !setting.getName().startsWith(prefix)) {
2769 continue;
2770 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002771 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002772 if (settingsState.resetSettingLocked(name)) {
2773 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002774 notifyForSettingsChange(key, name);
2775 }
2776 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002777 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002778 notifyForSettingsChange(key, name);
2779 }
2780 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002781 if (someSettingChanged) {
2782 settingsState.persistSyncLocked();
2783 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002784 }
2785 } break;
2786
2787 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2788 for (String name : settingsState.getSettingNamesLocked()) {
2789 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002790 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002791 if (prefix != null && !setting.getName().startsWith(prefix)) {
2792 continue;
2793 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002794 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002795 if (settingsState.resetSettingLocked(name)) {
2796 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002797 notifyForSettingsChange(key, name);
2798 }
2799 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002800 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002801 notifyForSettingsChange(key, name);
2802 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002803 if (someSettingChanged) {
2804 settingsState.persistSyncLocked();
2805 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002806 }
2807 } break;
2808 }
2809 }
2810
Zimuzoc56192c2018-07-25 10:40:01 +01002811 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002812 // Global and secure settings are signature protected. Apps signed
2813 // by the platform certificate are generally not uninstalled and
2814 // the main exception is tests. We trust components signed
2815 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002816
2817 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2818 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002819 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002820 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002821 }
Svetoslav683914b2015-01-15 14:22:26 -08002822 }
2823
Mark Rathjend891f012017-01-19 04:10:37 +00002824 public void onUidRemovedLocked(int uid) {
2825 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2826 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002827 if (ssaidSettings != null) {
2828 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2829 }
Mark Rathjend891f012017-01-19 04:10:37 +00002830 }
2831
Kweku Adamsb0886f32017-10-31 15:32:09 -07002832 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002833 private SettingsState peekSettingsStateLocked(int key) {
2834 SettingsState settingsState = mSettingsStates.get(key);
2835 if (settingsState != null) {
2836 return settingsState;
2837 }
2838
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002839 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2840 return null;
2841 }
Svetoslav683914b2015-01-15 14:22:26 -08002842 return mSettingsStates.get(key);
2843 }
2844
2845 private void migrateAllLegacySettingsIfNeeded() {
2846 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002847 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002848 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002849 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002850 return;
2851 }
2852
Amith Yamasani39452022017-03-21 15:23:47 -07002853 mSettingsCreationBuildId = Build.ID;
2854
Svetoslav683914b2015-01-15 14:22:26 -08002855 final long identity = Binder.clearCallingIdentity();
2856 try {
2857 List<UserInfo> users = mUserManager.getUsers(true);
2858
2859 final int userCount = users.size();
2860 for (int i = 0; i < userCount; i++) {
2861 final int userId = users.get(i).id;
2862
2863 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2864 SQLiteDatabase database = dbHelper.getWritableDatabase();
2865 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2866
2867 // Upgrade to the latest version.
2868 UpgradeController upgrader = new UpgradeController(userId);
2869 upgrader.upgradeIfNeededLocked();
2870
2871 // Drop from memory if not a running user.
2872 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2873 removeUserStateLocked(userId, false);
2874 }
2875 }
2876 } finally {
2877 Binder.restoreCallingIdentity(identity);
2878 }
2879 }
2880 }
2881
2882 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2883 // Every user has secure settings and if no file we need to migrate.
2884 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2885 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002886 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002887 return;
2888 }
2889
2890 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2891 SQLiteDatabase database = dbHelper.getWritableDatabase();
2892
2893 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2894 }
2895
2896 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2897 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002898 // Move over the system settings.
2899 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2900 ensureSettingsStateLocked(systemKey);
2901 SettingsState systemSettings = mSettingsStates.get(systemKey);
2902 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2903 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002904
2905 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002906 // Do this after System settings, since this is the first thing we check when deciding
2907 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002908 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2909 ensureSettingsStateLocked(secureKey);
2910 SettingsState secureSettings = mSettingsStates.get(secureKey);
2911 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2912 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2913 secureSettings.persistSyncLocked();
2914
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002915 // Move over the global settings if owner.
2916 // Do this last, since this is the first thing we check when deciding
2917 // to skip over migration from db to xml for owner user.
2918 if (userId == UserHandle.USER_SYSTEM) {
2919 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2920 ensureSettingsStateLocked(globalKey);
2921 SettingsState globalSettings = mSettingsStates.get(globalKey);
2922 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002923 // If this was just created
2924 if (mSettingsCreationBuildId != null) {
2925 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2926 mSettingsCreationBuildId, null, true,
2927 SettingsState.SYSTEM_PACKAGE_NAME);
2928 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002929 globalSettings.persistSyncLocked();
2930 }
Svetoslav683914b2015-01-15 14:22:26 -08002931
2932 // Drop the database as now all is moved and persisted.
2933 if (DROP_DATABASE_ON_MIGRATION) {
2934 dbHelper.dropDatabase();
2935 } else {
2936 dbHelper.backupDatabase();
2937 }
2938 }
2939
2940 private void migrateLegacySettingsLocked(SettingsState settingsState,
2941 SQLiteDatabase database, String table) {
2942 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2943 queryBuilder.setTables(table);
2944
2945 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2946 null, null, null, null, null);
2947
2948 if (cursor == null) {
2949 return;
2950 }
2951
2952 try {
2953 if (!cursor.moveToFirst()) {
2954 return;
2955 }
2956
2957 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2958 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2959
2960 settingsState.setVersionLocked(database.getVersion());
2961
2962 while (!cursor.isAfterLast()) {
2963 String name = cursor.getString(nameColumnIdx);
2964 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002965 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002966 SettingsState.SYSTEM_PACKAGE_NAME);
2967 cursor.moveToNext();
2968 }
2969 } finally {
2970 cursor.close();
2971 }
2972 }
2973
Andreas Gampeb58893072018-09-05 16:52:31 -07002974 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002975 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2976 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2977
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002978 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002979 return;
2980 }
2981
2982 final int userId = getUserIdFromKey(secureSettings.mKey);
2983
2984 final UserInfo user;
2985 final long identity = Binder.clearCallingIdentity();
2986 try {
2987 user = mUserManager.getUserInfo(userId);
2988 } finally {
2989 Binder.restoreCallingIdentity(identity);
2990 }
2991 if (user == null) {
2992 // Can happen due to races when deleting users - treat as benign.
2993 return;
2994 }
2995
2996 String androidId = Long.toHexString(new SecureRandom().nextLong());
2997 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002998 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002999
3000 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3001 + "] for user " + userId);
3002
3003 // Write a drop box entry if it's a restricted profile
3004 if (user.isRestricted()) {
3005 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3006 Context.DROPBOX_SERVICE);
3007 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3008 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3009 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3010 }
3011 }
3012 }
3013
3014 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003015 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003016 mGenerationRegistry.incrementGeneration(key);
3017
Svet Ganov945864c2018-03-22 21:49:10 -07003018 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003019 final long token = Binder.clearCallingIdentity();
3020 try {
3021 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3022 // When the global kill switch is updated, send the
3023 // change notification for the location setting.
3024 notifyLocationChangeForRunningUsers();
3025 }
3026 notifyGlobalSettingChangeForRunningUsers(key, name);
3027 } finally {
3028 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003029 }
Svet Ganov945864c2018-03-22 21:49:10 -07003030 } else {
3031 final int userId = getUserIdFromKey(key);
3032 final Uri uri = getNotificationUriFor(key, name);
3033 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3034 userId, 0, uri).sendToTarget();
3035 if (isSecureSettingsKey(key)) {
3036 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3037 sSecureCloneToManagedSettings);
3038 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3039 sSystemCloneFromParentOnDependency.values());
3040 } else if (isSystemSettingsKey(key)) {
3041 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3042 sSystemCloneToManagedSettings);
3043 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003044 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003045
Svet Ganov945864c2018-03-22 21:49:10 -07003046 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003047 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003048 }
3049
Svet Ganov53a441c2016-04-19 19:38:00 -07003050 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003051 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003052 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003053 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003054 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003055 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003056 final int key = makeKey(type, profileId);
3057 // Increment the generation first, so observers always see the new value
3058 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003059 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003060 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003061 }
3062 }
3063 }
Svetoslav683914b2015-01-15 14:22:26 -08003064 }
3065
Svet Ganov945864c2018-03-22 21:49:10 -07003066 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3067 // Important: No need to update generation for each user as there
3068 // is a singleton generation entry for the global settings which
3069 // is already incremented be the caller.
3070 final Uri uri = getNotificationUriFor(key, name);
3071 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3072 for (int i = 0; i < users.size(); i++) {
3073 final int userId = users.get(i).id;
3074 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3075 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3076 userId, 0, uri).sendToTarget();
3077 }
3078 }
3079 }
3080
Makoto Onuki0000d322017-11-28 16:31:47 -08003081 private void notifyLocationChangeForRunningUsers() {
3082 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3083
3084 for (int i = 0; i < users.size(); i++) {
3085 final int userId = users.get(i).id;
3086
3087 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3088 continue;
3089 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003090
Svet Ganov945864c2018-03-22 21:49:10 -07003091 // Increment the generation first, so observers always see the new value
3092 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3093 mGenerationRegistry.incrementGeneration(key);
3094
3095 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003096 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3097 userId, 0, uri).sendToTarget();
3098 }
3099 }
3100
Matt Pape1b31a332018-10-17 09:58:28 -07003101 private boolean isConfigSettingsKey(int key) {
3102 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3103 }
3104
Svetoslav683914b2015-01-15 14:22:26 -08003105 private boolean isGlobalSettingsKey(int key) {
3106 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3107 }
3108
3109 private boolean isSystemSettingsKey(int key) {
3110 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3111 }
3112
3113 private boolean isSecureSettingsKey(int key) {
3114 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3115 }
3116
Mark Rathjend891f012017-01-19 04:10:37 +00003117 private boolean isSsaidSettingsKey(int key) {
3118 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3119 }
3120
Svetoslav683914b2015-01-15 14:22:26 -08003121 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003122 if (isConfigSettingsKey(key)) {
3123 final int userId = getUserIdFromKey(key);
3124 return new File(Environment.getUserSystemDirectory(userId),
3125 SETTINGS_FILE_CONFIG);
3126 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003127 final int userId = getUserIdFromKey(key);
3128 return new File(Environment.getUserSystemDirectory(userId),
3129 SETTINGS_FILE_GLOBAL);
3130 } else if (isSystemSettingsKey(key)) {
3131 final int userId = getUserIdFromKey(key);
3132 return new File(Environment.getUserSystemDirectory(userId),
3133 SETTINGS_FILE_SYSTEM);
3134 } else if (isSecureSettingsKey(key)) {
3135 final int userId = getUserIdFromKey(key);
3136 return new File(Environment.getUserSystemDirectory(userId),
3137 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003138 } else if (isSsaidSettingsKey(key)) {
3139 final int userId = getUserIdFromKey(key);
3140 return new File(Environment.getUserSystemDirectory(userId),
3141 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003142 } else {
3143 throw new IllegalArgumentException("Invalid settings key:" + key);
3144 }
3145 }
3146
3147 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003148 if (isConfigSettingsKey(key)) {
3149 return (name != null) ? Uri.withAppendedPath(CONFIG_CONTENT_URI, name)
3150 : CONFIG_CONTENT_URI;
3151 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003152 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3153 : Settings.Global.CONTENT_URI;
3154 } else if (isSecureSettingsKey(key)) {
3155 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3156 : Settings.Secure.CONTENT_URI;
3157 } else if (isSystemSettingsKey(key)) {
3158 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3159 : Settings.System.CONTENT_URI;
3160 } else {
3161 throw new IllegalArgumentException("Invalid settings key:" + key);
3162 }
3163 }
3164
3165 private int getMaxBytesPerPackageForType(int type) {
3166 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003167 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003168 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003169 case SETTINGS_TYPE_SECURE:
3170 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003171 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3172 }
3173
3174 default: {
3175 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3176 }
3177 }
3178 }
3179
Svetoslav7e0683b2015-08-03 16:02:52 -07003180 private final class MyHandler extends Handler {
3181 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3182 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3183
3184 public MyHandler(Looper looper) {
3185 super(looper);
3186 }
3187
3188 @Override
3189 public void handleMessage(Message msg) {
3190 switch (msg.what) {
3191 case MSG_NOTIFY_URI_CHANGED: {
3192 final int userId = msg.arg1;
3193 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003194 try {
3195 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3196 } catch (SecurityException e) {
3197 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3198 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003199 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003200 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3201 }
3202 } break;
3203
3204 case MSG_NOTIFY_DATA_CHANGED: {
3205 mBackupManager.dataChanged();
3206 } break;
3207 }
3208 }
3209 }
3210
Svetoslav683914b2015-01-15 14:22:26 -08003211 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003212 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003213
3214 private final int mUserId;
3215
3216 public UpgradeController(int userId) {
3217 mUserId = userId;
3218 }
3219
3220 public void upgradeIfNeededLocked() {
3221 // The version of all settings for a user is the same (all users have secure).
3222 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003223 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003224
3225 // Try an update from the current state.
3226 final int oldVersion = secureSettings.getVersionLocked();
3227 final int newVersion = SETTINGS_VERSION;
3228
Svet Ganovc9755bc2015-03-28 13:21:22 -07003229 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003230 if (oldVersion == newVersion) {
3231 return;
3232 }
3233
3234 // Try to upgrade.
3235 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3236
3237 // If upgrade failed start from scratch and upgrade.
3238 if (curVersion != newVersion) {
3239 // Drop state we have for this user.
3240 removeUserStateLocked(mUserId, true);
3241
3242 // Recreate the database.
3243 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3244 SQLiteDatabase database = dbHelper.getWritableDatabase();
3245 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3246
3247 // Migrate the settings for this user.
3248 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3249
3250 // Now upgrade should work fine.
3251 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003252
3253 // Make a note what happened, so we don't wonder why data was lost
3254 String reason = "Settings rebuilt! Current version: "
3255 + curVersion + " while expected: " + newVersion;
3256 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003257 Settings.Global.DATABASE_DOWNGRADE_REASON,
3258 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003259 }
3260
3261 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003262 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003263 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003264 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003265 globalSettings.setVersionLocked(newVersion);
3266 }
3267
3268 // Set the secure settings version.
3269 secureSettings.setVersionLocked(newVersion);
3270
3271 // Set the system settings version.
3272 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003273 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003274 systemSettings.setVersionLocked(newVersion);
3275 }
3276
3277 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003278 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003279 }
3280
3281 private SettingsState getSecureSettingsLocked(int userId) {
3282 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3283 }
3284
Mark Rathjend891f012017-01-19 04:10:37 +00003285 private SettingsState getSsaidSettingsLocked(int userId) {
3286 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3287 }
3288
Svetoslav683914b2015-01-15 14:22:26 -08003289 private SettingsState getSystemSettingsLocked(int userId) {
3290 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3291 }
3292
Jeff Brown503cffc2015-03-26 18:08:51 -07003293 /**
3294 * You must perform all necessary mutations to bring the settings
3295 * for this user from the old to the new version. When you add a new
3296 * upgrade step you *must* update SETTINGS_VERSION.
3297 *
3298 * This is an example of moving a setting from secure to global.
3299 *
3300 * // v119: Example settings changes.
3301 * if (currentVersion == 118) {
3302 * if (userId == UserHandle.USER_OWNER) {
3303 * // Remove from the secure settings.
3304 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3305 * String name = "example_setting_to_move";
3306 * String value = secureSettings.getSetting(name);
3307 * secureSettings.deleteSetting(name);
3308 *
3309 * // Add to the global settings.
3310 * SettingsState globalSettings = getGlobalSettingsLocked();
3311 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3312 * }
3313 *
3314 * // Update the current version.
3315 * currentVersion = 119;
3316 * }
3317 */
Svetoslav683914b2015-01-15 14:22:26 -08003318 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3319 if (DEBUG) {
3320 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3321 + oldVersion + " to version: " + newVersion);
3322 }
3323
Jeff Brown503cffc2015-03-26 18:08:51 -07003324 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003325
John Spurlocke11ae112015-05-11 16:09:03 -04003326 // v119: Reset zen + ringer mode.
3327 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003328 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003329 final SettingsState globalSettings = getGlobalSettingsLocked();
3330 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003331 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3332 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003333 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003334 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3335 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003336 }
3337 currentVersion = 119;
3338 }
3339
Jason Monk27bbb2d2015-03-31 16:46:39 -04003340 // v120: Add double tap to wake setting.
3341 if (currentVersion == 119) {
3342 SettingsState secureSettings = getSecureSettingsLocked(userId);
3343 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3344 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003345 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003346 SettingsState.SYSTEM_PACKAGE_NAME);
3347
3348 currentVersion = 120;
3349 }
3350
Svetoslav7e0683b2015-08-03 16:02:52 -07003351 if (currentVersion == 120) {
3352 // Before 121, we used a different string encoding logic. We just bump the
3353 // version here; SettingsState knows how to handle pre-version 120 files.
3354 currentVersion = 121;
3355 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003356
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003357 if (currentVersion == 121) {
3358 // Version 122: allow OEMs to set a default payment component in resources.
3359 // Note that we only write the default if no default has been set;
3360 // if there is, we just leave the default at whatever it currently is.
3361 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3362 String defaultComponent = (getContext().getResources().getString(
3363 R.string.def_nfc_payment_component));
3364 Setting currentSetting = secureSettings.getSettingLocked(
3365 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3366 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003367 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003368 secureSettings.insertSettingLocked(
3369 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003370 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003371 }
3372 currentVersion = 122;
3373 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003374
3375 if (currentVersion == 122) {
3376 // Version 123: Adding a default value for the ability to add a user from
3377 // the lock screen.
3378 if (userId == UserHandle.USER_SYSTEM) {
3379 final SettingsState globalSettings = getGlobalSettingsLocked();
3380 Setting currentSetting = globalSettings.getSettingLocked(
3381 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003382 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003383 globalSettings.insertSettingLocked(
3384 Settings.Global.ADD_USERS_WHEN_LOCKED,
3385 getContext().getResources().getBoolean(
3386 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003387 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003388 }
3389 }
3390 currentVersion = 123;
3391 }
Bryce Leebd179282015-12-17 19:01:37 -08003392
3393 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003394 final SettingsState globalSettings = getGlobalSettingsLocked();
3395 String defaultDisabledProfiles = (getContext().getResources().getString(
3396 R.string.def_bluetooth_disabled_profiles));
3397 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003398 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003399 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003400 }
3401
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003402 if (currentVersion == 124) {
3403 // Version 124: allow OEMs to set a default value for whether IME should be
3404 // shown when a physical keyboard is connected.
3405 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3406 Setting currentSetting = secureSettings.getSettingLocked(
3407 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003408 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003409 secureSettings.insertSettingLocked(
3410 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3411 getContext().getResources().getBoolean(
3412 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003413 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003414 }
3415 currentVersion = 125;
3416 }
3417
Ruben Brunk98576cf2016-03-07 18:54:28 -08003418 if (currentVersion == 125) {
3419 // Version 125: Allow OEMs to set the default VR service.
3420 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3421
3422 Setting currentSetting = secureSettings.getSettingLocked(
3423 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003424 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003425 ArraySet<ComponentName> l =
3426 SystemConfig.getInstance().getDefaultVrComponents();
3427
3428 if (l != null && !l.isEmpty()) {
3429 StringBuilder b = new StringBuilder();
3430 boolean start = true;
3431 for (ComponentName c : l) {
3432 if (!start) {
3433 b.append(':');
3434 }
3435 b.append(c.flattenToString());
3436 start = false;
3437 }
3438 secureSettings.insertSettingLocked(
3439 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003440 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003441 }
3442
3443 }
3444 currentVersion = 126;
3445 }
3446
Daniel U02ba6122016-04-01 18:41:42 +01003447 if (currentVersion == 126) {
3448 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3449 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3450 if (mUserManager.isManagedProfile(userId)) {
3451 final SettingsState systemSecureSettings =
3452 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3453
3454 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3455 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003456 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003457 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3458 secureSettings.insertSettingLocked(
3459 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003460 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003461 SettingsState.SYSTEM_PACKAGE_NAME);
3462 }
3463
3464 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3465 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003466 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003467 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3468 secureSettings.insertSettingLocked(
3469 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003470 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003471 SettingsState.SYSTEM_PACKAGE_NAME);
3472 }
3473 }
3474 currentVersion = 127;
3475 }
3476
Steven Ngdc20ba62016-04-26 18:19:04 +01003477 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003478 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003479 currentVersion = 128;
3480 }
3481
Julia Reynolds1f721e12016-07-11 08:50:58 -04003482 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003483 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003484 currentVersion = 129;
3485 }
3486
Dan Sandler71f85e92016-07-20 13:46:05 -04003487 if (currentVersion == 129) {
3488 // default longpress timeout changed from 500 to 400. If unchanged from the old
3489 // default, update to the new default.
3490 final SettingsState systemSecureSettings =
3491 getSecureSettingsLocked(userId);
3492 final String oldValue = systemSecureSettings.getSettingLocked(
3493 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3494 if (TextUtils.equals("500", oldValue)) {
3495 systemSecureSettings.insertSettingLocked(
3496 Settings.Secure.LONG_PRESS_TIMEOUT,
3497 String.valueOf(getContext().getResources().getInteger(
3498 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003499 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003500 }
3501 currentVersion = 130;
3502 }
3503
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003504 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003505 // Split Ambient settings
3506 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3507 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3508 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3509
3510 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003511 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003512 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003513 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003514 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003515 }
3516 currentVersion = 131;
3517 }
3518
3519 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003520 // Initialize new multi-press timeout to default value
3521 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3522 final String oldValue = systemSecureSettings.getSettingLocked(
3523 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3524 if (TextUtils.equals(null, oldValue)) {
3525 systemSecureSettings.insertSettingLocked(
3526 Settings.Secure.MULTI_PRESS_TIMEOUT,
3527 String.valueOf(getContext().getResources().getInteger(
3528 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003529 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003530 }
3531
Adrian Roos69741a22016-10-21 14:49:17 -07003532 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003533 }
3534
Adrian Roos69741a22016-10-21 14:49:17 -07003535 if (currentVersion == 132) {
3536 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003537 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3538 String defaultSyncParentSounds = (getContext().getResources()
3539 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3540 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003541 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3542 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003543 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003544 }
3545
Adrian Roos69741a22016-10-21 14:49:17 -07003546 if (currentVersion == 133) {
3547 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003548 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003549 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3550 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003551 String defaultEndButtonBehavior = Integer.toString(getContext()
3552 .getResources().getInteger(R.integer.def_end_button_behavior));
3553 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003554 defaultEndButtonBehavior, null, true,
3555 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003556 }
Adrian Roos69741a22016-10-21 14:49:17 -07003557 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003558 }
3559
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003560 if (currentVersion == 134) {
3561 // Remove setting that specifies if magnification values should be preserved.
3562 // This setting defaulted to true and never has a UI.
3563 getSecureSettingsLocked(userId).deleteSettingLocked(
3564 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3565 currentVersion = 135;
3566 }
3567
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003568 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003569 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003570 currentVersion = 136;
3571 }
3572
Mark Rathjend891f012017-01-19 04:10:37 +00003573 if (currentVersion == 136) {
3574 // Version 136: Store legacy SSAID for all apps currently installed on the
3575 // device as first step in migrating SSAID to be unique per application.
3576
3577 final boolean isUpgrade;
3578 try {
3579 isUpgrade = mPackageManager.isUpgrade();
3580 } catch (RemoteException e) {
3581 throw new IllegalStateException("Package manager not available");
3582 }
3583 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3584 // user data or first boot on a new device should use new ssaid generation.
3585 if (isUpgrade) {
3586 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003587 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3588 userId, Settings.Secure.ANDROID_ID);
3589 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3590 || legacySsaidSetting.getValue() == null) {
3591 throw new IllegalStateException("Legacy ssaid not accessible");
3592 }
3593 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003594
3595 // Fill each uid with the legacy ssaid to be backwards compatible.
3596 final List<PackageInfo> packages;
3597 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003598 packages = mPackageManager.getInstalledPackages(
3599 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3600 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003601 } catch (RemoteException e) {
3602 throw new IllegalStateException("Package manager not available");
3603 }
3604
3605 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3606 for (PackageInfo info : packages) {
3607 // Check if the UID already has an entry in the table.
3608 final String uid = Integer.toString(info.applicationInfo.uid);
3609 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3610
3611 if (ssaid.isNull() || ssaid.getValue() == null) {
3612 // Android Id doesn't exist for this package so create it.
3613 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3614 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003615 if (DEBUG) {
3616 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3617 }
Mark Rathjend891f012017-01-19 04:10:37 +00003618 }
3619 }
3620 }
3621
3622 currentVersion = 137;
3623 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003624 if (currentVersion == 137) {
3625 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3626 // default value set to 1. The user can no longer change the value of this
3627 // setting through the UI.
3628 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3629 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003630 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3631 && secureSetting.getSettingLocked(
3632 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3633
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003634 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3635 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003636 // For managed profiles with profile owners, DevicePolicyManagerService
3637 // may want to set the user restriction in this case
3638 secureSetting.insertSettingLocked(
3639 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3640 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003641 }
3642 currentVersion = 138;
3643 }
Mark Rathjend891f012017-01-19 04:10:37 +00003644
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003645 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003646 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003647 currentVersion = 139;
3648 }
3649
Phil Weaver385912e2017-02-10 10:06:56 -08003650 if (currentVersion == 139) {
3651 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3652 // the user can no longer change the value of this setting through the UI.
3653 // Force to true.
3654 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3655 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3656 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3657 currentVersion = 140;
3658 }
3659
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003660 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003661 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003662 currentVersion = 141;
3663 }
3664
Svet Ganov13701552017-02-23 12:45:17 -08003665 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003666 // This implementation was incorrectly setting the current value of
3667 // settings changed by non-system packages as the default which default
3668 // is set by the system. We add a new upgrade step at the end to properly
3669 // handle this case which would also fix incorrect changes made by the
3670 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003671 currentVersion = 142;
3672 }
3673
Stephen Chen5d0922f2017-03-27 10:28:04 -07003674 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003675 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003676 if (userId == UserHandle.USER_SYSTEM) {
3677 final SettingsState globalSettings = getGlobalSettingsLocked();
3678 Setting currentSetting = globalSettings.getSettingLocked(
3679 Settings.Global.WIFI_WAKEUP_ENABLED);
3680 if (currentSetting.isNull()) {
3681 globalSettings.insertSettingLocked(
3682 Settings.Global.WIFI_WAKEUP_ENABLED,
3683 getContext().getResources().getBoolean(
3684 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3685 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3686 }
3687 }
3688
3689 currentVersion = 143;
3690 }
3691
Felipe Lemeff355092017-04-03 12:55:02 -07003692 if (currentVersion == 143) {
3693 // Version 144: Set a default value for Autofill service.
3694 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3695 final Setting currentSetting = secureSettings
3696 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3697 if (currentSetting.isNull()) {
3698 final String defaultValue = getContext().getResources().getString(
3699 com.android.internal.R.string.config_defaultAutofillService);
3700 if (defaultValue != null) {
3701 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3702 + "for user " + userId);
3703 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3704 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3705 }
3706 }
3707
3708 currentVersion = 144;
3709 }
3710
Jeremy Joslin45caa252017-05-04 11:22:46 -07003711 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003712 // Version 145: Removed
3713 currentVersion = 145;
3714 }
3715
3716 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003717 // Version 146: In step 142 we had a bug where incorrectly
3718 // some settings were considered system set and as a result
3719 // made the default and marked as the default being set by
3720 // the system. Here reevaluate the default and default system
3721 // set flags. This would both fix corruption by the old impl
3722 // of step 142 and also properly handle devices which never
3723 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003724 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003725 SettingsState globalSettings = getGlobalSettingsLocked();
3726 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3727 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003728 }
3729
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003730 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3731 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3732 secureSettings.persistSyncLocked();
3733
3734 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3735 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3736 systemSettings.persistSyncLocked();
3737
Amin Shaikh86367962017-06-07 08:58:22 -07003738 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003739 }
3740
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003741 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003742 // Version 147: Removed. (This version previously allowed showing the
3743 // "wifi_wakeup_available" setting).
3744 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003745 currentVersion = 147;
3746 }
3747
3748 if (currentVersion == 147) {
3749 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003750 if (userId == UserHandle.USER_SYSTEM) {
3751 final SettingsState globalSettings = getGlobalSettingsLocked();
3752 final Setting currentSetting = globalSettings.getSettingLocked(
3753 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3754 if (currentSetting.isNull()) {
3755 globalSettings.insertSettingLocked(
3756 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3757 getContext().getResources().getBoolean(
3758 R.bool.def_restrict_background_data) ? "1" : "0",
3759 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3760 }
3761 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003762 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003763 }
3764
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003765 if (currentVersion == 148) {
3766 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3767 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3768 final String oldValue = systemSecureSettings.getSettingLocked(
3769 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3770 if (TextUtils.equals(null, oldValue)) {
3771 final String defaultValue = getContext().getResources().getString(
3772 R.string.def_backup_manager_constants);
3773 if (!TextUtils.isEmpty(defaultValue)) {
3774 systemSecureSettings.insertSettingLocked(
3775 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3776 true, SettingsState.SYSTEM_PACKAGE_NAME);
3777 }
3778 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003779 currentVersion = 149;
3780 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003781
3782 if (currentVersion == 149) {
3783 // Version 150: Set a default value for mobile data always on
3784 final SettingsState globalSettings = getGlobalSettingsLocked();
3785 final Setting currentSetting = globalSettings.getSettingLocked(
3786 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3787 if (currentSetting.isNull()) {
3788 globalSettings.insertSettingLocked(
3789 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3790 getContext().getResources().getBoolean(
3791 R.bool.def_mobile_data_always_on) ? "1" : "0",
3792 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3793 }
3794
3795 currentVersion = 150;
3796 }
3797
Mike Digman4af4a6f2018-01-16 14:49:38 -08003798 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003799 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003800 currentVersion = 151;
3801 }
3802
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003803 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003804 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3805 // by default but it is now no longer configurable).
3806 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003807 currentVersion = 152;
3808 }
3809
Joe LaPenna250d7842018-01-25 10:19:42 -08003810 if (currentVersion == 152) {
3811 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3812 currentVersion = 153;
3813 }
3814
Ben Linb4df8bc2018-01-29 11:48:20 -08003815 if (currentVersion == 153) {
3816 // Version 154: Read notification badge configuration from config.
3817 // If user has already set the value, don't do anything.
3818 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3819 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3820 Settings.Secure.NOTIFICATION_BADGING);
3821 if (showNotificationBadges.isNull()) {
3822 final boolean defaultValue = getContext().getResources().getBoolean(
3823 com.android.internal.R.bool.config_notificationBadging);
3824 systemSecureSettings.insertSettingLocked(
3825 Secure.NOTIFICATION_BADGING,
3826 defaultValue ? "1" : "0",
3827 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3828 }
3829 currentVersion = 154;
3830 }
3831
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003832 if (currentVersion == 154) {
3833 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3834 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3835 final String oldValue = systemSecureSettings.getSettingLocked(
3836 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3837 if (TextUtils.equals(null, oldValue)) {
3838 final String defaultValue = getContext().getResources().getString(
3839 R.string.def_backup_local_transport_parameters);
3840 if (!TextUtils.isEmpty(defaultValue)) {
3841 systemSecureSettings.insertSettingLocked(
3842 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3843 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3844 }
3845
3846 }
3847 currentVersion = 155;
3848 }
3849
Beverlyda904812018-03-02 09:55:30 -05003850 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003851 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003852 final SettingsState globalSettings = getGlobalSettingsLocked();
3853 final String oldValue = globalSettings.getSettingLocked(
3854 Global.CHARGING_STARTED_SOUND).getValue();
3855 final String oldDefault = getContext().getResources().getString(
3856 R.string.def_wireless_charging_started_sound);
3857 if (TextUtils.equals(null, oldValue)
3858 || TextUtils.equals(oldValue, oldDefault)) {
3859 final String defaultValue = getContext().getResources().getString(
3860 R.string.def_charging_started_sound);
3861 if (!TextUtils.isEmpty(defaultValue)) {
3862 globalSettings.insertSettingLocked(
3863 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3864 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3865 }
3866
3867 }
3868 currentVersion = 156;
3869 }
3870
Beverly09da25f2018-02-26 09:17:07 -05003871 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003872 // Version 157: Set a default value for zen duration,
3873 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003874 final SettingsState globalSettings = getGlobalSettingsLocked();
3875 final Setting currentSetting = globalSettings.getSettingLocked(
3876 Global.ZEN_DURATION);
3877 if (currentSetting.isNull()) {
3878 String defaultZenDuration = Integer.toString(getContext()
3879 .getResources().getInteger(R.integer.def_zen_duration));
3880 globalSettings.insertSettingLocked(
3881 Global.ZEN_DURATION, defaultZenDuration,
3882 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3883 }
Beverly09da25f2018-02-26 09:17:07 -05003884 currentVersion = 157;
3885 }
Annie Mengd069a882018-03-13 15:31:40 +00003886
3887 if (currentVersion == 157) {
3888 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3889 final SettingsState globalSettings = getGlobalSettingsLocked();
3890 final String oldValue = globalSettings.getSettingLocked(
3891 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3892 if (TextUtils.equals(null, oldValue)) {
3893 final String defaultValue = getContext().getResources().getString(
3894 R.string.def_backup_agent_timeout_parameters);
3895 if (!TextUtils.isEmpty(defaultValue)) {
3896 globalSettings.insertSettingLocked(
3897 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3898 null, true,
3899 SettingsState.SYSTEM_PACKAGE_NAME);
3900 }
3901 }
3902 currentVersion = 158;
3903 }
Roshan Pius9c396672018-03-02 14:54:13 -08003904
3905 if (currentVersion == 158) {
3906 // Remove setting that specifies wifi bgscan throttling params
3907 getGlobalSettingsLocked().deleteSettingLocked(
3908 "wifi_scan_background_throttle_interval_ms");
3909 getGlobalSettingsLocked().deleteSettingLocked(
3910 "wifi_scan_background_throttle_package_whitelist");
3911 currentVersion = 159;
3912 }
3913
Pavel Grafovc5c97302018-03-19 13:37:15 +00003914 if (currentVersion == 159) {
3915 // Version 160: Hiding notifications from the lockscreen is only available as
3916 // primary user option, profiles can only make them redacted. If a profile was
3917 // configured to not show lockscreen notifications, ensure that at the very
3918 // least these will be come hidden.
3919 if (mUserManager.isManagedProfile(userId)) {
3920 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3921 Setting showNotifications = secureSettings.getSettingLocked(
3922 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3923 // The default value is "1", check if user has turned it off.
3924 if ("0".equals(showNotifications.getValue())) {
3925 secureSettings.insertSettingLocked(
3926 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3927 null /* tag */, false /* makeDefault */,
3928 SettingsState.SYSTEM_PACKAGE_NAME);
3929 }
3930 // The setting is no longer valid for managed profiles, it should be
3931 // treated as if it was set to "1".
3932 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3933 }
3934 currentVersion = 160;
3935 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003936
3937 if (currentVersion == 160) {
3938 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003939 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003940 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3941 final SettingsState globalSettings = getGlobalSettingsLocked();
3942
3943 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003944 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3945 if (TextUtils.equals(null, oldValue)) {
3946 globalSettings.insertSettingLocked(
3947 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3948 Integer.toString(getContext().getResources().getInteger(
3949 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3950 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3951 }
3952
3953 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003954 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3955 if (TextUtils.equals(null, oldValue)) {
3956 globalSettings.insertSettingLocked(
3957 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3958 Integer.toString(getContext().getResources().getInteger(
3959 R.integer.def_sound_trigger_detection_service_op_timeout)),
3960 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3961 }
3962 currentVersion = 161;
3963 }
3964
Mike Digman55272862018-02-20 14:35:17 -08003965 if (currentVersion == 161) {
3966 // Version 161: Add a gesture for silencing phones
3967 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3968 final Setting currentSetting = secureSettings.getSettingLocked(
3969 Secure.VOLUME_HUSH_GESTURE);
3970 if (currentSetting.isNull()) {
3971 secureSettings.insertSettingLocked(
3972 Secure.VOLUME_HUSH_GESTURE,
3973 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3974 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3975 }
3976
3977 currentVersion = 162;
3978 }
3979
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003980 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003981 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003982 currentVersion = 163;
3983 }
3984
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003985 if (currentVersion == 163) {
3986 // Version 163: Update default value of
3987 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3988 final SettingsState settings = getGlobalSettingsLocked();
3989 final Setting currentSetting = settings.getSettingLocked(
3990 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3991 if (currentSetting.isDefaultFromSystem()) {
3992 settings.insertSettingLocked(
3993 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3994 Integer.toString(getContext().getResources().getInteger(
3995 R.integer
3996 .def_max_sound_trigger_detection_service_ops_per_day)),
3997 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3998 }
3999
4000 currentVersion = 164;
4001 }
4002
Julia Reynolds76bfa602018-04-23 09:38:47 -04004003 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004004 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004005 currentVersion = 165;
4006 }
4007
Beverly301e92a2018-04-27 09:43:05 -04004008 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004009 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4010 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004011 currentVersion = 166;
4012 }
4013
Beverly38fcfd02018-05-18 17:33:40 -04004014 if (currentVersion == 166) {
4015 // Version 166: add default values for hush gesture used and manual ringer
4016 // toggle
4017 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4018 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4019 Secure.HUSH_GESTURE_USED);
4020 if (currentHushUsedSetting.isNull()) {
4021 secureSettings.insertSettingLocked(
4022 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4023 SettingsState.SYSTEM_PACKAGE_NAME);
4024 }
4025
4026 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4027 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4028 if (currentRingerToggleCountSetting.isNull()) {
4029 secureSettings.insertSettingLocked(
4030 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4031 SettingsState.SYSTEM_PACKAGE_NAME);
4032 }
4033 currentVersion = 167;
4034 }
4035
Beverly155c9d22018-05-23 18:03:23 -04004036 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004037 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4038 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004039 currentVersion = 168;
4040 }
4041
Michael Wright0e9eeee2018-05-26 00:31:20 +01004042 if (currentVersion == 168) {
4043 // Version 168: by default, vibrate for phone calls
4044 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4045 final Setting currentSetting = systemSettings.getSettingLocked(
4046 Settings.System.VIBRATE_WHEN_RINGING);
4047 if (currentSetting.isNull()) {
4048 systemSettings.insertSettingLocked(
4049 Settings.System.VIBRATE_WHEN_RINGING,
4050 getContext().getResources().getBoolean(
4051 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4052 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4053 }
4054 currentVersion = 169;
4055 }
4056
Nadav Barf9f115d2018-06-24 10:06:50 +03004057 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004058 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4059 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4060 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004061
Beverly91d0a632018-07-02 16:45:00 -04004062 final SettingsState globalSettings = getGlobalSettingsLocked();
4063 final Setting globalZenDuration = globalSettings.getSettingLocked(
4064 Global.ZEN_DURATION);
4065
4066 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4067 final Setting secureZenDuration = secureSettings.getSettingLocked(
4068 Secure.ZEN_DURATION);
4069
4070 // ZEN_DURATION
4071 if (!globalZenDuration.isNull()) {
4072 secureSettings.insertSettingLocked(
4073 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4074 SettingsState.SYSTEM_PACKAGE_NAME);
4075
4076 // set global zen duration setting to null since it's deprecated
4077 globalSettings.insertSettingLocked(
4078 Global.ZEN_DURATION, null, null, true,
4079 SettingsState.SYSTEM_PACKAGE_NAME);
4080 } else if (secureZenDuration.isNull()) {
4081 String defaultZenDuration = Integer.toString(getContext()
4082 .getResources().getInteger(R.integer.def_zen_duration));
4083 secureSettings.insertSettingLocked(
4084 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4085 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004086 }
Beverly91d0a632018-07-02 16:45:00 -04004087
4088 // SHOW_ZEN_SETTINGS_SUGGESTION
4089 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4090 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4091 if (currentShowZenSettingSuggestion.isNull()) {
4092 secureSettings.insertSettingLocked(
4093 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4094 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4095 }
4096
4097 // ZEN_SETTINGS_UPDATED
4098 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4099 Secure.ZEN_SETTINGS_UPDATED);
4100 if (currentUpdatedSetting.isNull()) {
4101 secureSettings.insertSettingLocked(
4102 Secure.ZEN_SETTINGS_UPDATED, "0",
4103 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4104 }
4105
4106 // ZEN_SETTINGS_SUGGESTION_VIEWED
4107 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4108 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4109 if (currentSettingSuggestionViewed.isNull()) {
4110 secureSettings.insertSettingLocked(
4111 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4112 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4113 }
4114
Nadav Barf9f115d2018-06-24 10:06:50 +03004115 currentVersion = 170;
4116 }
4117
Beverly91d0a632018-07-02 16:45:00 -04004118 if (currentVersion == 170) {
4119 // Version 170: Set the default value for Secure Settings:
4120 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4121
4122 final SettingsState globalSettings = getGlobalSettingsLocked();
4123 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4124
4125 // CHARGING_SOUNDS_ENABLED
4126 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4127 Global.CHARGING_SOUNDS_ENABLED);
4128 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4129 Secure.CHARGING_SOUNDS_ENABLED);
4130
4131 if (!globalChargingSoundEnabled.isNull()) {
4132 secureSettings.insertSettingLocked(
4133 Secure.CHARGING_SOUNDS_ENABLED,
4134 globalChargingSoundEnabled.getValue(), null, false,
4135 SettingsState.SYSTEM_PACKAGE_NAME);
4136
4137 // set global charging_sounds_enabled setting to null since it's deprecated
4138 globalSettings.insertSettingLocked(
4139 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4140 SettingsState.SYSTEM_PACKAGE_NAME);
4141 } else if (secureChargingSoundsEnabled.isNull()) {
4142 String defChargingSoundsEnabled = getContext().getResources()
4143 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4144 secureSettings.insertSettingLocked(
4145 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4146 true, SettingsState.SYSTEM_PACKAGE_NAME);
4147 }
4148
4149 // CHARGING_VIBRATION_ENABLED
4150 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4151 Secure.CHARGING_VIBRATION_ENABLED);
4152
4153 if (secureChargingVibrationEnabled.isNull()) {
4154 String defChargingVibrationEnabled = getContext().getResources()
4155 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4156 secureSettings.insertSettingLocked(
4157 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4158 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4159 }
4160
4161 currentVersion = 171;
4162 }
4163
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004164 if (currentVersion == 171) {
4165 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4166 // be muted.
4167 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4168 final Setting currentSetting = systemSettings.getSettingLocked(
4169 Settings.System.MUTE_STREAMS_AFFECTED);
4170 if (!currentSetting.isNull()) {
4171 try {
4172 int currentSettingIntegerValue = Integer.parseInt(
4173 currentSetting.getValue());
4174 if ((currentSettingIntegerValue
4175 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4176 systemSettings.insertSettingLocked(
4177 Settings.System.MUTE_STREAMS_AFFECTED,
4178 Integer.toString(
4179 currentSettingIntegerValue
4180 | (1 << AudioManager.STREAM_VOICE_CALL)),
4181 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4182 }
4183 } catch (NumberFormatException e) {
4184 // remove the setting in case it is not a valid integer
4185 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4186 + "setting, removing setting", e);
4187 systemSettings.deleteSettingLocked(
4188 Settings.System.MUTE_STREAMS_AFFECTED);
4189 }
4190
4191 }
4192 currentVersion = 172;
4193 }
4194
Felipe Lemeff355092017-04-03 12:55:02 -07004195 // vXXX: Add new settings above this point.
4196
Dan Sandler71f85e92016-07-20 13:46:05 -04004197 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004198 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004199 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004200 + currentVersion +
4201 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4202 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004203 if (DEBUG) {
4204 throw new RuntimeException("db upgrade error");
4205 }
4206 }
4207
Jeff Brown503cffc2015-03-26 18:08:51 -07004208 // Return the current version.
4209 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004210 }
4211 }
Svet Ganov13701552017-02-23 12:45:17 -08004212
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004213 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4214 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004215 List<String> names = settings.getSettingNamesLocked();
4216 final int nameCount = names.size();
4217 for (int i = 0; i < nameCount; i++) {
4218 String name = names.get(i);
4219 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004220
4221 // In the upgrade case we pretend the call is made from the app
4222 // that made the last change to the setting to properly determine
4223 // whether the call has been made by a system component.
4224 int callingUid = -1;
4225 try {
4226 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4227 } catch (RemoteException e) {
4228 /* ignore - handled below */
4229 }
4230 if (callingUid < 0) {
4231 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4232 continue;
4233 }
4234 try {
4235 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4236 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004237 if (systemSet) {
4238 settings.insertSettingLocked(name, setting.getValue(),
4239 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004240 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4241 // We had a bug where changes by non-system packages were marked
4242 // as system made and as a result set as the default. Therefore, if
4243 // the package changed the setting last is not a system one but the
4244 // setting is marked as its default coming from the system we clear
4245 // the default and clear the system set flag.
4246 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004247 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004248 } catch (IllegalStateException e) {
4249 // If the package goes over its quota during the upgrade, don't
4250 // crash but just log the error as the system does the upgrade.
4251 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4252
Svet Ganov13701552017-02-23 12:45:17 -08004253 }
4254 }
4255 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004256 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004257}