blob: 140a5a3f859020218ca6ce67e557468eb67aa9aa [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));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700338 return true;
339 }
340
Michal Karpinski2c37b082018-01-18 16:14:27 +0000341 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000342 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
343 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000344
345 failToBootIfOffendersPresent(offenders, "Settings.System");
346 }
347
348 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000349 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
350 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000351
352 failToBootIfOffendersPresent(offenders, "Settings.Global");
353 }
354
Michal Karpinski964943a2018-01-19 16:28:26 +0000355 private void ensureAllBackedUpSecureSettingsHaveValidators() {
356 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
357 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
358
359 failToBootIfOffendersPresent(offenders, "Settings.Secure");
360 }
361
Michal Karpinski5db1e432018-01-18 20:10:24 +0000362 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
363 if (offenders.length() > 0) {
364 throw new RuntimeException("All " + settingsType + " settings that are backed up"
365 + " have to have a non-null validator, but those don't: " + offenders);
366 }
367 }
368
369 private String getOffenders(String[] settingsToBackup, Map<String,
370 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000371 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000372 for (String setting : settingsToBackup) {
373 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000374 offenders.append(setting).append(" ");
375 }
376 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000377 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000378 }
379
Michal Karpinski964943a2018-01-19 16:28:26 +0000380 private final String[] concat(String[] first, String[] second) {
381 if (second == null || second.length == 0) {
382 return first;
383 }
384 final int firstLen = first.length;
385 final int secondLen = second.length;
386 String[] both = new String[firstLen + secondLen];
387 System.arraycopy(first, 0, both, 0, firstLen);
388 System.arraycopy(second, 0, both, firstLen, secondLen);
389 return both;
390 }
391
Svetoslav683914b2015-01-15 14:22:26 -0800392 @Override
393 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700394 final int requestingUserId = getRequestingUserId(args);
395 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700396 case Settings.CALL_METHOD_GET_CONFIG: {
397 Setting setting = getConfigSetting(name);
398 return packageValueForCallResult(setting, isTrackingGeneration(args));
399 }
400
Svetoslav7ec28e82015-05-20 17:01:10 -0700401 case Settings.CALL_METHOD_GET_GLOBAL: {
402 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700403 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800404 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700405
406 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800407 Setting setting = getSecureSetting(name, requestingUserId,
408 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700409 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700410 }
411
412 case Settings.CALL_METHOD_GET_SYSTEM: {
413 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700414 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700415 }
416
Matt Pape1b31a332018-10-17 09:58:28 -0700417 case Settings.CALL_METHOD_PUT_CONFIG: {
418 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700419 final boolean makeDefault = getSettingMakeDefault(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800420 insertConfigSetting(name, value, null, makeDefault, requestingUserId, false);
Matt Pape1b31a332018-10-17 09:58:28 -0700421 break;
422 }
423
Svetoslav7ec28e82015-05-20 17:01:10 -0700424 case Settings.CALL_METHOD_PUT_GLOBAL: {
425 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800426 String tag = getSettingTag(args);
427 final boolean makeDefault = getSettingMakeDefault(args);
428 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700429 break;
430 }
431
432 case Settings.CALL_METHOD_PUT_SECURE: {
433 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800434 String tag = getSettingTag(args);
435 final boolean makeDefault = getSettingMakeDefault(args);
436 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700437 break;
438 }
439
440 case Settings.CALL_METHOD_PUT_SYSTEM: {
441 String value = getSettingValue(args);
442 insertSystemSetting(name, value, requestingUserId);
443 break;
444 }
445
Matt Pape1b31a332018-10-17 09:58:28 -0700446 case Settings.CALL_METHOD_RESET_CONFIG: {
447 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800448 String prefix = getSettingPrefix(args);
449 resetConfigSetting(requestingUserId, mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700450 break;
451 }
452
Svetoslav Ganove080da92016-12-21 17:10:35 -0800453 case Settings.CALL_METHOD_RESET_GLOBAL: {
454 final int mode = getResetModeEnforcingPermission(args);
455 String tag = getSettingTag(args);
456 resetGlobalSetting(requestingUserId, mode, tag);
457 break;
458 }
459
460 case Settings.CALL_METHOD_RESET_SECURE: {
461 final int mode = getResetModeEnforcingPermission(args);
462 String tag = getSettingTag(args);
463 resetSecureSetting(requestingUserId, mode, tag);
464 break;
465 }
466
Matt Pape6bfc62e2018-11-28 13:16:03 -0800467 case Settings.CALL_METHOD_DELETE_CONFIG: {
468 int rows = deleteConfigSetting(name, requestingUserId, false) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800469 Bundle result = new Bundle();
470 result.putInt(RESULT_ROWS_DELETED, rows);
471 return result;
472 }
473
474 case Settings.CALL_METHOD_DELETE_GLOBAL: {
475 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
476 Bundle result = new Bundle();
477 result.putInt(RESULT_ROWS_DELETED, rows);
478 return result;
479 }
480
Matt Pape6bfc62e2018-11-28 13:16:03 -0800481 case Settings.CALL_METHOD_DELETE_SECURE: {
482 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
483 Bundle result = new Bundle();
484 result.putInt(RESULT_ROWS_DELETED, rows);
485 return result;
486 }
487
488 case Settings.CALL_METHOD_DELETE_SYSTEM: {
489 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
490 Bundle result = new Bundle();
491 result.putInt(RESULT_ROWS_DELETED, rows);
492 return result;
493 }
494
495 case Settings.CALL_METHOD_LIST_CONFIG: {
496 String prefix = getSettingPrefix(args);
497 Bundle result = new Bundle();
498 result.putSerializable(
499 Settings.NameValueTable.VALUE, (HashMap) getAllConfigFlags(prefix));
500 return result;
501 }
502
503 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800504 Bundle result = new Bundle();
505 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800506 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800507 return result;
508 }
509
510 case Settings.CALL_METHOD_LIST_SECURE: {
511 Bundle result = new Bundle();
512 result.putStringArrayList(RESULT_SETTINGS_LIST,
513 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
514 return result;
515 }
516
Matt Pape6bfc62e2018-11-28 13:16:03 -0800517 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800518 Bundle result = new Bundle();
519 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800520 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800521 return result;
522 }
523
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 default: {
525 Slog.w(LOG_TAG, "call() with invalid method: " + method);
526 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700527 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700528
Christopher Tate06efb532012-08-24 15:29:27 -0700529 return null;
530 }
531
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800532 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800533 public String getType(Uri uri) {
534 Arguments args = new Arguments(uri, null, null, true);
535 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536 return "vnd.android.cursor.dir/" + args.table;
537 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700538 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700539 }
540 }
541
542 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800543 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
544 String order) {
545 if (DEBUG) {
546 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700547 }
548
Svetoslav683914b2015-01-15 14:22:26 -0800549 Arguments args = new Arguments(uri, where, whereArgs, true);
550 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700551
Svetoslav683914b2015-01-15 14:22:26 -0800552 // If a legacy table that is gone, done.
553 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
554 return new MatrixCursor(normalizedProjection, 0);
555 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700556
Svetoslav7ec28e82015-05-20 17:01:10 -0700557 switch (args.table) {
558 case TABLE_GLOBAL: {
559 if (args.name != null) {
560 Setting setting = getGlobalSetting(args.name);
561 return packageSettingForQuery(setting, normalizedProjection);
562 } else {
563 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700564 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700565 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700566
Svetoslav7ec28e82015-05-20 17:01:10 -0700567 case TABLE_SECURE: {
568 final int userId = UserHandle.getCallingUserId();
569 if (args.name != null) {
570 Setting setting = getSecureSetting(args.name, userId);
571 return packageSettingForQuery(setting, normalizedProjection);
572 } else {
573 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800574 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700575 }
Svetoslav683914b2015-01-15 14:22:26 -0800576
Svetoslav7ec28e82015-05-20 17:01:10 -0700577 case TABLE_SYSTEM: {
578 final int userId = UserHandle.getCallingUserId();
579 if (args.name != null) {
580 Setting setting = getSystemSetting(args.name, userId);
581 return packageSettingForQuery(setting, normalizedProjection);
582 } else {
583 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800584 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700585 }
Svetoslav683914b2015-01-15 14:22:26 -0800586
Svetoslav7ec28e82015-05-20 17:01:10 -0700587 default: {
588 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700589 }
590 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700591 }
592
Nicholas Sauer72500532018-11-21 10:30:58 -0800593 private ArrayList<String> buildSettingsList(Cursor cursor) {
594 final ArrayList<String> lines = new ArrayList<String>();
595 try {
596 while (cursor != null && cursor.moveToNext()) {
597 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
598 }
599 } finally {
600 if (cursor != null) {
601 cursor.close();
602 }
603 }
604 return lines;
605 }
606
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700607 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800608 public Uri insert(Uri uri, ContentValues values) {
609 if (DEBUG) {
610 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700611 }
612
Svetoslav683914b2015-01-15 14:22:26 -0800613 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700614
Svetoslav683914b2015-01-15 14:22:26 -0800615 // If a legacy table that is gone, done.
616 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 return null;
618 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700619
Svetoslav683914b2015-01-15 14:22:26 -0800620 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700621 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800622 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700623 }
624
Svetoslav683914b2015-01-15 14:22:26 -0800625 String value = values.getAsString(Settings.Secure.VALUE);
626
Svetoslav7ec28e82015-05-20 17:01:10 -0700627 switch (table) {
628 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800629 if (insertGlobalSetting(name, value, null, false,
630 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700631 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700632 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700633 } break;
634
635 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800636 if (insertSecureSetting(name, value, null, false,
637 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700638 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
639 }
640 } break;
641
642 case TABLE_SYSTEM: {
643 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
644 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
645 }
646 } break;
647
648 default: {
649 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700650 }
651 }
652
Svetoslav683914b2015-01-15 14:22:26 -0800653 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700654 }
655
656 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800657 public int bulkInsert(Uri uri, ContentValues[] allValues) {
658 if (DEBUG) {
659 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700661
Svetoslav683914b2015-01-15 14:22:26 -0800662 int insertionCount = 0;
663 final int valuesCount = allValues.length;
664 for (int i = 0; i < valuesCount; i++) {
665 ContentValues values = allValues[i];
666 if (insert(uri, values) != null) {
667 insertionCount++;
668 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700669 }
Svetoslav683914b2015-01-15 14:22:26 -0800670
671 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700672 }
673
674 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800675 public int delete(Uri uri, String where, String[] whereArgs) {
676 if (DEBUG) {
677 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700679
Svetoslav683914b2015-01-15 14:22:26 -0800680 Arguments args = new Arguments(uri, where, whereArgs, false);
681
682 // If a legacy table that is gone, done.
683 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
684 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700685 }
Svetoslav683914b2015-01-15 14:22:26 -0800686
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700687 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800688 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700689 }
Svetoslav683914b2015-01-15 14:22:26 -0800690
Svetoslav7ec28e82015-05-20 17:01:10 -0700691 switch (args.table) {
692 case TABLE_GLOBAL: {
693 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700694 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700695 }
Svetoslav683914b2015-01-15 14:22:26 -0800696
Svetoslav7ec28e82015-05-20 17:01:10 -0700697 case TABLE_SECURE: {
698 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700699 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700700 }
Svetoslav683914b2015-01-15 14:22:26 -0800701
Svetoslav7ec28e82015-05-20 17:01:10 -0700702 case TABLE_SYSTEM: {
703 final int userId = UserHandle.getCallingUserId();
704 return deleteSystemSetting(args.name, userId) ? 1 : 0;
705 }
706
707 default: {
708 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800709 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700710 }
Svetoslav683914b2015-01-15 14:22:26 -0800711 }
712
713 @Override
714 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
715 if (DEBUG) {
716 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700717 }
Svetoslav683914b2015-01-15 14:22:26 -0800718
719 Arguments args = new Arguments(uri, where, whereArgs, false);
720
721 // If a legacy table that is gone, done.
722 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
723 return 0;
724 }
725
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700726 String name = values.getAsString(Settings.Secure.NAME);
727 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800728 return 0;
729 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700730 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800731
Svetoslav7ec28e82015-05-20 17:01:10 -0700732 switch (args.table) {
733 case TABLE_GLOBAL: {
734 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800735 return updateGlobalSetting(args.name, value, null, false,
736 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700737 }
Svetoslav683914b2015-01-15 14:22:26 -0800738
Svetoslav7ec28e82015-05-20 17:01:10 -0700739 case TABLE_SECURE: {
740 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800741 return updateSecureSetting(args.name, value, null, false,
742 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700743 }
Svetoslav683914b2015-01-15 14:22:26 -0800744
Svetoslav7ec28e82015-05-20 17:01:10 -0700745 case TABLE_SYSTEM: {
746 final int userId = UserHandle.getCallingUserId();
747 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
748 }
Svetoslav683914b2015-01-15 14:22:26 -0800749
Svetoslav7ec28e82015-05-20 17:01:10 -0700750 default: {
751 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800752 }
753 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700754 }
755
756 @Override
757 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100758 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
759 if (userId != UserHandle.getCallingUserId()) {
760 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
761 "Access files from the settings of another user");
762 }
763 uri = ContentProvider.getUriWithoutUserId(uri);
764
Andre Lago3fa139c2016-08-04 13:53:44 +0100765 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700766 final String cacheName;
767 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100768 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700769 cacheName = Settings.System.RINGTONE_CACHE;
770 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100771 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700772 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
773 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100774 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700775 cacheName = Settings.System.ALARM_ALERT_CACHE;
776 } else {
777 throw new FileNotFoundException("Direct file access no longer supported; "
778 + "ringtone playback is available through android.media.Ringtone");
779 }
780
Andre Lago3fa139c2016-08-04 13:53:44 +0100781 int actualCacheOwner;
782 // Redirect cache to parent if ringtone setting is owned by profile parent
783 synchronized (mLock) {
784 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
785 cacheRingtoneSetting);
786 }
787 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700788 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
789 }
790
791 private File getRingtoneCacheDir(int userId) {
792 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
793 cacheDir.mkdir();
794 SELinux.restorecon(cacheDir);
795 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700796 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800797
Eugene Suslad72c3972016-12-27 15:49:30 -0800798 /**
799 * Dump all settings as a proto buf.
800 *
801 * @param fd The file to dump to
802 */
803 void dumpProto(@NonNull FileDescriptor fd) {
804 ProtoOutputStream proto = new ProtoOutputStream(fd);
805
806 synchronized (mLock) {
807 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800808 }
809
810 proto.flush();
811 }
812
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700813 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800814 synchronized (mLock) {
815 final long identity = Binder.clearCallingIdentity();
816 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700817 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800818 final int userCount = users.size();
819 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700820 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800821 }
822 } finally {
823 Binder.restoreCallingIdentity(identity);
824 }
825 }
826 }
827
Andreas Gampeb58893072018-09-05 16:52:31 -0700828 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700829 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700830 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700831 pw.println("CONFIG SETTINGS (user " + userId + ")");
832 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
833 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
834 if (configSettings != null) {
835 dumpSettingsLocked(configSettings, pw);
836 pw.println();
837 configSettings.dumpHistoricalOperations(pw);
838 }
839
Svetoslavb505ccc2015-02-17 12:41:04 -0800840 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700841 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
842 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700843 if (globalSettings != null) {
844 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800845 pw.println();
846 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700847 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800848 }
849
850 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700851 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
852 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700853 if (secureSettings != null) {
854 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800855 pw.println();
856 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700857 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700858
Svetoslavb505ccc2015-02-17 12:41:04 -0800859 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700860 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
861 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700862 if (systemSettings != null) {
863 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800864 pw.println();
865 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700866 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800867 }
868
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700869 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
870 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800871
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700872 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800873
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700874 for (int i = 0; i < nameCount; i++) {
875 String name = names.get(i);
876 Setting setting = settingsState.getSettingLocked(name);
877 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
878 pw.print(" name:"); pw.print(toDumpString(name));
879 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800880 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700881 }
882 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800883 if (setting.getDefaultValue() != null) {
884 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800885 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800886 }
887 if (setting.getTag() != null) {
888 pw.print(" tag:"); pw.print(setting.getTag());
889 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800890 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700891 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800892 }
893
Svetoslav7e0683b2015-08-03 16:02:52 -0700894 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700895 if (s != null) {
896 return s;
897 }
898 return "{null}";
899 }
900
Svetoslav683914b2015-01-15 14:22:26 -0800901 private void registerBroadcastReceivers() {
902 IntentFilter userFilter = new IntentFilter();
903 userFilter.addAction(Intent.ACTION_USER_REMOVED);
904 userFilter.addAction(Intent.ACTION_USER_STOPPED);
905
906 getContext().registerReceiver(new BroadcastReceiver() {
907 @Override
908 public void onReceive(Context context, Intent intent) {
909 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700910 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800911
912 switch (intent.getAction()) {
913 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700914 synchronized (mLock) {
915 mSettingsRegistry.removeUserStateLocked(userId, true);
916 }
Svetoslav683914b2015-01-15 14:22:26 -0800917 } break;
918
919 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700920 synchronized (mLock) {
921 mSettingsRegistry.removeUserStateLocked(userId, false);
922 }
Svetoslav683914b2015-01-15 14:22:26 -0800923 } break;
924 }
925 }
926 }, userFilter);
927
928 PackageMonitor monitor = new PackageMonitor() {
929 @Override
930 public void onPackageRemoved(String packageName, int uid) {
931 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100932 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800933 UserHandle.getUserId(uid));
934 }
935 }
Mark Rathjend891f012017-01-19 04:10:37 +0000936
937 @Override
938 public void onUidRemoved(int uid) {
939 synchronized (mLock) {
940 mSettingsRegistry.onUidRemovedLocked(uid);
941 }
942 }
Zimuzoc56192c2018-07-25 10:40:01 +0100943
944 @Override
945 public void onPackageDataCleared(String packageName, int uid) {
946 synchronized (mLock) {
947 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
948 UserHandle.getUserId(uid));
949 }
950 }
Svetoslav683914b2015-01-15 14:22:26 -0800951 };
952
953 // package changes
954 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
955 UserHandle.ALL, true);
956 }
957
Svet Ganov53a441c2016-04-19 19:38:00 -0700958 private void startWatchingUserRestrictionChanges() {
959 // TODO: The current design of settings looking different based on user restrictions
960 // should be reworked to keep them separate and system code should check the setting
961 // first followed by checking the user restriction before performing an operation.
962 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
963 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
964 Bundle prevRestrictions) -> {
965 // We are changing the settings affected by restrictions to their current
966 // value with a forced update to ensure that all cross profile dependencies
967 // are taken into account. Also make sure the settings update to.. the same
968 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800969 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
970 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700971 final long identity = Binder.clearCallingIdentity();
972 try {
973 synchronized (mLock) {
974 Setting setting = getSecureSetting(
975 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
976 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800977 setting != null ? setting.getValue() : null, null,
978 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700979 }
980 } finally {
981 Binder.restoreCallingIdentity(identity);
982 }
983 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800984 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100985 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
986 newRestrictions.getBoolean(
987 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
988 != prevRestrictions.getBoolean(
989 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700990 final long identity = Binder.clearCallingIdentity();
991 try {
992 synchronized (mLock) {
993 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800994 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700995 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800996 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700997 }
998 } finally {
999 Binder.restoreCallingIdentity(identity);
1000 }
1001 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001002 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
1003 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001004 final long identity = Binder.clearCallingIdentity();
1005 try {
1006 synchronized (mLock) {
1007 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001008 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001009 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001010 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001011 }
1012 } finally {
1013 Binder.restoreCallingIdentity(identity);
1014 }
1015 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001016 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
1017 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001018 final long identity = Binder.clearCallingIdentity();
1019 try {
1020 synchronized (mLock) {
1021 Setting enable = getGlobalSetting(
1022 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001023 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001024 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001025 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001026 Setting include = getGlobalSetting(
1027 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001028 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001029 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001030 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001031 }
1032 } finally {
1033 Binder.restoreCallingIdentity(identity);
1034 }
1035 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001036 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
1037 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001038 final long identity = Binder.clearCallingIdentity();
1039 try {
1040 synchronized (mLock) {
1041 Setting setting = getGlobalSetting(
1042 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001043 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001044 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001045 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001046 }
1047 } finally {
1048 Binder.restoreCallingIdentity(identity);
1049 }
1050 }
1051 });
1052 }
1053
Matt Pape1b31a332018-10-17 09:58:28 -07001054 private Setting getConfigSetting(String name) {
1055 if (DEBUG) {
1056 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1057 }
1058
1059 // TODO(b/117663715): Ensure the caller can access the setting.
1060 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1061
1062 // Get the value.
1063 synchronized (mLock) {
1064 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1065 UserHandle.USER_SYSTEM, name);
1066 }
1067 }
1068
1069 private boolean insertConfigSetting(String name, String value, String tag,
1070 boolean makeDefault, int requestingUserId, boolean forceNotify) {
1071 if (DEBUG) {
1072 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
1073 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1074 + ", " + forceNotify + ")");
1075 }
1076 return mutateConfigSetting(name, value, tag, makeDefault, requestingUserId,
1077 MUTATION_OPERATION_INSERT, forceNotify, 0);
1078 }
1079
Matt Pape6bfc62e2018-11-28 13:16:03 -08001080 private boolean deleteConfigSetting(String name, int requestingUserId, boolean forceNotify) {
1081 if (DEBUG) {
1082 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ", " + requestingUserId
1083 + ", " + forceNotify + ")");
1084 }
1085 return mutateConfigSetting(name, null, null, false, requestingUserId,
1086 MUTATION_OPERATION_DELETE, forceNotify, 0);
1087 }
1088
1089 private void resetConfigSetting(int requestingUserId, int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001090 if (DEBUG) {
1091 Slog.v(LOG_TAG, "resetConfigSetting(" + requestingUserId + ", "
Matt Pape6bfc62e2018-11-28 13:16:03 -08001092 + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001093 }
Matt Pape6bfc62e2018-11-28 13:16:03 -08001094 mutateConfigSetting(null, null, prefix, false, requestingUserId,
Matt Pape1b31a332018-10-17 09:58:28 -07001095 MUTATION_OPERATION_RESET, false, mode);
1096 }
1097
Matt Pape6bfc62e2018-11-28 13:16:03 -08001098 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Pape1b31a332018-10-17 09:58:28 -07001099 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1100 int mode) {
1101 // TODO(b/117663715): check the new permission when it's added.
1102 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1103
Matt Pape1b31a332018-10-17 09:58:28 -07001104 // Perform the mutation.
1105 synchronized (mLock) {
1106 switch (operation) {
1107 case MUTATION_OPERATION_INSERT: {
1108 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Pape6bfc62e2018-11-28 13:16:03 -08001109 UserHandle.USER_SYSTEM, name, value, null, makeDefault,
Matt Pape1b31a332018-10-17 09:58:28 -07001110 getCallingPackage(), forceNotify, null);
1111 }
1112
Matt Pape6bfc62e2018-11-28 13:16:03 -08001113 case MUTATION_OPERATION_DELETE: {
1114 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
1115 UserHandle.USER_SYSTEM, name, forceNotify, null);
1116 }
1117
Matt Pape1b31a332018-10-17 09:58:28 -07001118 case MUTATION_OPERATION_RESET: {
1119 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape6bfc62e2018-11-28 13:16:03 -08001120 UserHandle.USER_SYSTEM, getCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001121 } return true;
1122 }
1123 }
1124
1125 return false;
1126 }
1127
Matt Pape6bfc62e2018-11-28 13:16:03 -08001128 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1129 if (DEBUG) {
1130 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1131 }
1132
1133 synchronized (mLock) {
1134 // Get the settings.
1135 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1136 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1137
1138 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1139 UserHandle.USER_SYSTEM);
1140
1141 final int nameCount = names.size();
1142 Map<String, String> flagsToValues = new HashMap<>(names.size());
1143
1144 for (int i = 0; i < nameCount; i++) {
1145 String name = names.get(i);
1146 Setting setting = settingsState.getSettingLocked(name);
1147 if (prefix == null || setting.getName().startsWith(prefix)) {
1148 flagsToValues.put(setting.getName(), setting.getValue());
1149 }
1150 }
1151
1152 return flagsToValues;
1153 }
1154 }
1155
Svetoslav7ec28e82015-05-20 17:01:10 -07001156 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001157 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001158 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001159 }
1160
Svetoslav7ec28e82015-05-20 17:01:10 -07001161 synchronized (mLock) {
1162 // Get the settings.
1163 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001164 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001165
Chad Brubaker97bccee2017-01-05 15:51:41 -08001166 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1167 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001168
Svetoslav7ec28e82015-05-20 17:01:10 -07001169 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001170
Svetoslav7ec28e82015-05-20 17:01:10 -07001171 String[] normalizedProjection = normalizeProjection(projection);
1172 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001173
Svetoslav7ec28e82015-05-20 17:01:10 -07001174 // Anyone can get the global settings, so no security checks.
1175 for (int i = 0; i < nameCount; i++) {
1176 String name = names.get(i);
1177 Setting setting = settingsState.getSettingLocked(name);
1178 appendSettingToCursor(result, setting);
1179 }
1180
1181 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001182 }
Svetoslav683914b2015-01-15 14:22:26 -08001183 }
1184
Svetoslav7ec28e82015-05-20 17:01:10 -07001185 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001186 if (DEBUG) {
1187 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1188 }
1189
Chad Brubakera6830e72017-04-28 17:34:36 -07001190 // Ensure the caller can access the setting.
1191 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1192
Svetoslav683914b2015-01-15 14:22:26 -08001193 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001194 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001195 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001196 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001197 }
Svetoslav683914b2015-01-15 14:22:26 -08001198 }
1199
Svetoslav Ganove080da92016-12-21 17:10:35 -08001200 private boolean updateGlobalSetting(String name, String value, String tag,
1201 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001202 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001203 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1204 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1205 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001206 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001207 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1208 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001209 }
1210
Svetoslav Ganove080da92016-12-21 17:10:35 -08001211 private boolean insertGlobalSetting(String name, String value, String tag,
1212 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1215 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1216 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001217 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001218 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1219 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001220 }
1221
Svet Ganov53a441c2016-04-19 19:38:00 -07001222 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001223 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001224 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1225 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001226 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001227 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1228 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001229 }
1230
Svetoslav Ganove080da92016-12-21 17:10:35 -08001231 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1232 if (DEBUG) {
1233 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1234 + mode + ", " + tag + ")");
1235 }
1236 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1237 MUTATION_OPERATION_RESET, false, mode);
1238 }
1239
1240 private boolean mutateGlobalSetting(String name, String value, String tag,
1241 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1242 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001243 // Make sure the caller can change the settings - treated as secure.
1244 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1245
Svetoslav683914b2015-01-15 14:22:26 -08001246 // Resolve the userId on whose behalf the call is made.
1247 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1248
Makoto Onuki28da2e32015-11-20 11:30:44 -08001249 // If this is a setting that is currently restricted for this user, do not allow
1250 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001251 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1252 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001253 return false;
1254 }
1255
1256 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001257 synchronized (mLock) {
1258 switch (operation) {
1259 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001260 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1261 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001262 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001263 }
Svetoslav683914b2015-01-15 14:22:26 -08001264
Svetoslav7ec28e82015-05-20 17:01:10 -07001265 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001266 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001267 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001268 }
Svetoslav683914b2015-01-15 14:22:26 -08001269
Svetoslav7ec28e82015-05-20 17:01:10 -07001270 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001271 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1272 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001273 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001275
1276 case MUTATION_OPERATION_RESET: {
1277 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1278 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1279 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001280 }
1281 }
1282
1283 return false;
1284 }
1285
Christopher Tateb218e762017-04-05 16:34:07 -07001286 private PackageInfo getCallingPackageInfo(int userId) {
1287 try {
1288 return mPackageManager.getPackageInfo(getCallingPackage(),
1289 PackageManager.GET_SIGNATURES, userId);
1290 } catch (RemoteException e) {
1291 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1292 }
1293 }
1294
Svetoslav7ec28e82015-05-20 17:01:10 -07001295 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001296 if (DEBUG) {
1297 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1298 }
1299
1300 // Resolve the userId on whose behalf the call is made.
1301 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1302
Christopher Tateb218e762017-04-05 16:34:07 -07001303 // The relevant "calling package" userId will be the owning userId for some
1304 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1305 // up front who the effective "new SSAID" user ID for that settings name will be.
1306 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1307 Settings.Secure.ANDROID_ID);
1308 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1309
Svetoslav7ec28e82015-05-20 17:01:10 -07001310 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001311 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001312
Svetoslav7ec28e82015-05-20 17:01:10 -07001313 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001314
Svetoslav7ec28e82015-05-20 17:01:10 -07001315 String[] normalizedProjection = normalizeProjection(projection);
1316 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001317
Svetoslav7ec28e82015-05-20 17:01:10 -07001318 for (int i = 0; i < nameCount; i++) {
1319 String name = names.get(i);
1320 // Determine the owning user as some profile settings are cloned from the parent.
1321 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1322 name);
Svetoslav683914b2015-01-15 14:22:26 -08001323
Alex Klyubin1991f572017-03-03 14:08:36 -08001324 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1325 // This caller is not permitted to access this setting. Pretend the setting
1326 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001327 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001328 }
Svetoslav683914b2015-01-15 14:22:26 -08001329
Mark Rathjen7599f132017-01-23 14:15:54 -08001330 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001331 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1332 final Setting setting;
1333 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001334 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001335 } else {
1336 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1337 name);
1338 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001339 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001340 }
1341
Svetoslav7ec28e82015-05-20 17:01:10 -07001342 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001343 }
Svetoslav683914b2015-01-15 14:22:26 -08001344 }
1345
Svetoslav7ec28e82015-05-20 17:01:10 -07001346 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001347 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1348 }
1349
1350 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001351 if (DEBUG) {
1352 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1353 }
1354
1355 // Resolve the userId on whose behalf the call is made.
1356 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1357
Chad Brubakera6830e72017-04-28 17:34:36 -07001358 // Ensure the caller can access the setting.
1359 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1360
Svetoslav683914b2015-01-15 14:22:26 -08001361 // Determine the owning user as some profile settings are cloned from the parent.
1362 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1363
Alex Klyubin1991f572017-03-03 14:08:36 -08001364 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1365 // This caller is not permitted to access this setting. Pretend the setting doesn't
1366 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001367 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1368 owningUserId);
1369 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001370 }
1371
Christopher Tateb218e762017-04-05 16:34:07 -07001372 // As of Android O, the SSAID is read from an app-specific entry in table
1373 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1374 if (isNewSsaidSetting(name)) {
1375 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1376 synchronized (mLock) {
1377 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001378 }
Christopher Tateb218e762017-04-05 16:34:07 -07001379 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001380 if (enableOverride) {
1381 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1382 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1383 if (overridden != null) {
1384 return overridden;
1385 }
1386 }
1387 }
Mark Rathjend891f012017-01-19 04:10:37 +00001388
Christopher Tateb218e762017-04-05 16:34:07 -07001389 // Not the SSAID; do a straight lookup
1390 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001391 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001392 owningUserId, name);
1393 }
Svetoslav683914b2015-01-15 14:22:26 -08001394 }
1395
Mark Rathjend891f012017-01-19 04:10:37 +00001396 private boolean isNewSsaidSetting(String name) {
1397 return Settings.Secure.ANDROID_ID.equals(name)
1398 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1399 }
1400
Andreas Gampeb58893072018-09-05 16:52:31 -07001401 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001402 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001403 // Get uid of caller (key) used to store ssaid value
1404 String name = Integer.toString(
1405 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1406
1407 if (DEBUG) {
1408 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1409 }
1410
1411 // Retrieve the ssaid from the table if present.
1412 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1413 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001414 // If the app is an Instant App use its stored SSAID instead of our own.
1415 final String instantSsaid;
1416 final long token = Binder.clearCallingIdentity();
1417 try {
1418 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1419 owningUserId);
1420 } catch (RemoteException e) {
1421 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1422 return null;
1423 } finally {
1424 Binder.restoreCallingIdentity(token);
1425 }
Svet Ganov96c99462017-05-05 14:27:13 -07001426
1427 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1428 SETTINGS_TYPE_SSAID, owningUserId);
1429
Chad Brubaker0d277a72017-04-12 16:56:53 -07001430 if (instantSsaid != null) {
1431 // Use the stored value if it is still valid.
1432 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001433 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001434 }
1435 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001436 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1437 true, callingPkg.packageName);
1438 if (!success) {
1439 throw new IllegalStateException("Failed to update instant app android id");
1440 }
Svet Ganov96c99462017-05-05 14:27:13 -07001441 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1442 owningUserId, name);
1443 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001444 }
Mark Rathjend891f012017-01-19 04:10:37 +00001445
1446 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001447 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001448 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1449 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001450 }
1451
Svet Ganov96c99462017-05-05 14:27:13 -07001452 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1453 }
1454
1455 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1456 // SSAID settings are located in a dedicated table for internal bookkeeping
1457 // but for the world they reside in the secure table, so adjust the key here.
1458 // We have a special name when looking it up but want the world to see it as
1459 // "android_id".
1460 if (ssaidSetting != null) {
1461 return settingsState.new Setting(ssaidSetting) {
1462 @Override
1463 public int getKey() {
1464 final int userId = getUserIdFromKey(super.getKey());
1465 return makeKey(SETTINGS_TYPE_SECURE, userId);
1466 }
1467
1468 @Override
1469 public String getName() {
1470 return Settings.Secure.ANDROID_ID;
1471 }
1472 };
1473 }
1474 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001475 }
1476
Makoto Onuki0000d322017-11-28 16:31:47 -08001477 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1478 synchronized (mLock) {
1479 final Setting setting = getGlobalSetting(
1480 Global.LOCATION_GLOBAL_KILL_SWITCH);
1481 if (!"1".equals(setting.getValue())) {
1482 return null;
1483 }
1484 // Global kill-switch is enabled. Return an empty value.
1485 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1486 SETTINGS_TYPE_SECURE, owningUserId);
1487 return settingsState.new Setting(
1488 Secure.LOCATION_PROVIDERS_ALLOWED,
1489 "", // value
1490 "", // tag
1491 "", // default value
1492 "", // package name
1493 false, // from system
1494 "0" // id
1495 ) {
1496 @Override
1497 public boolean update(String value, boolean setDefault, String packageName,
1498 String tag, boolean forceNonSystemPackage) {
1499 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1500 return false;
1501 }
1502 };
1503 }
1504 }
1505
Svetoslav Ganove080da92016-12-21 17:10:35 -08001506 private boolean insertSecureSetting(String name, String value, String tag,
1507 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001508 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001509 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001510 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1511 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001512 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001513 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1514 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001515 }
1516
Svet Ganov53a441c2016-04-19 19:38:00 -07001517 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001518 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001519 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1520 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001521 }
1522
Svetoslav Ganove080da92016-12-21 17:10:35 -08001523 return mutateSecureSetting(name, null, null, false, requestingUserId,
1524 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001525 }
1526
Svetoslav Ganove080da92016-12-21 17:10:35 -08001527 private boolean updateSecureSetting(String name, String value, String tag,
1528 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001529 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001530 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001531 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1532 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001533 }
1534
Svetoslav Ganove080da92016-12-21 17:10:35 -08001535 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1536 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001537 }
1538
Svetoslav Ganove080da92016-12-21 17:10:35 -08001539 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1540 if (DEBUG) {
1541 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1542 + mode + ", " + tag + ")");
1543 }
1544
1545 mutateSecureSetting(null, null, tag, false, requestingUserId,
1546 MUTATION_OPERATION_RESET, false, mode);
1547 }
1548
1549 private boolean mutateSecureSetting(String name, String value, String tag,
1550 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1551 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001552 // Make sure the caller can change the settings.
1553 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1554
Svetoslav683914b2015-01-15 14:22:26 -08001555 // Resolve the userId on whose behalf the call is made.
1556 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1557
Makoto Onuki28da2e32015-11-20 11:30:44 -08001558 // If this is a setting that is currently restricted for this user, do not allow
1559 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001560 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1561 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001562 return false;
1563 }
1564
1565 // Determine the owning user as some profile settings are cloned from the parent.
1566 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1567
1568 // Only the owning user can change the setting.
1569 if (owningUserId != callingUserId) {
1570 return false;
1571 }
1572
1573 // Special cases for location providers (sigh).
1574 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001575 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1576 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001577 }
1578
1579 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001580 synchronized (mLock) {
1581 switch (operation) {
1582 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001583 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001584 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001585 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001586 }
Svetoslav683914b2015-01-15 14:22:26 -08001587
Svetoslav7ec28e82015-05-20 17:01:10 -07001588 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001589 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001590 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001591 }
Svetoslav683914b2015-01-15 14:22:26 -08001592
Svetoslav7ec28e82015-05-20 17:01:10 -07001593 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001594 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001595 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001596 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001597 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001598
1599 case MUTATION_OPERATION_RESET: {
1600 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1601 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1602 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001603 }
1604 }
1605
1606 return false;
1607 }
1608
Svetoslav7ec28e82015-05-20 17:01:10 -07001609 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001610 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001611 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001612 }
1613
1614 // Resolve the userId on whose behalf the call is made.
1615 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1616
Svetoslav7ec28e82015-05-20 17:01:10 -07001617 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001618 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001619
Svetoslav7ec28e82015-05-20 17:01:10 -07001620 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001621
Svetoslav7ec28e82015-05-20 17:01:10 -07001622 String[] normalizedProjection = normalizeProjection(projection);
1623 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001624
Svetoslav7ec28e82015-05-20 17:01:10 -07001625 for (int i = 0; i < nameCount; i++) {
1626 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001627
Svetoslav7ec28e82015-05-20 17:01:10 -07001628 // Determine the owning user as some profile settings are cloned from the parent.
1629 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1630 name);
Svetoslav683914b2015-01-15 14:22:26 -08001631
Svetoslav7ec28e82015-05-20 17:01:10 -07001632 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001633 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001634 appendSettingToCursor(result, setting);
1635 }
1636
1637 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001638 }
Svetoslav683914b2015-01-15 14:22:26 -08001639 }
1640
Svetoslav7ec28e82015-05-20 17:01:10 -07001641 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001642 if (DEBUG) {
1643 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1644 }
1645
1646 // Resolve the userId on whose behalf the call is made.
1647 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1648
Chad Brubakera6830e72017-04-28 17:34:36 -07001649 // Ensure the caller can access the setting.
1650 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001651
Svetoslav683914b2015-01-15 14:22:26 -08001652 // Determine the owning user as some profile settings are cloned from the parent.
1653 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1654
1655 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001656 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001657 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001658 }
Svetoslav683914b2015-01-15 14:22:26 -08001659 }
1660
Svetoslav7ec28e82015-05-20 17:01:10 -07001661 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001662 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001663 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001664 + requestingUserId + ")");
1665 }
1666
Svetoslav7ec28e82015-05-20 17:01:10 -07001667 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001668 }
1669
Svetoslav7ec28e82015-05-20 17:01:10 -07001670 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001671 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001672 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001673 }
1674
Svetoslav7ec28e82015-05-20 17:01:10 -07001675 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001676 }
1677
Svetoslav7ec28e82015-05-20 17:01:10 -07001678 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001679 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001680 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001681 + requestingUserId + ")");
1682 }
1683
Svetoslav7ec28e82015-05-20 17:01:10 -07001684 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001685 }
1686
Svetoslav7ec28e82015-05-20 17:01:10 -07001687 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001688 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001689 if (!hasWriteSecureSettingsPermission()) {
1690 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1691 // operation is allowed for the calling package through appops.
1692 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1693 Binder.getCallingUid(), getCallingPackage(), true)) {
1694 return false;
1695 }
Svetoslav683914b2015-01-15 14:22:26 -08001696 }
1697
Svetoslav683914b2015-01-15 14:22:26 -08001698 // Resolve the userId on whose behalf the call is made.
1699 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1700
yuemingw1d13eae2018-01-30 17:27:54 +00001701 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1702 name, callingUserId, value, Binder.getCallingUid())) {
1703 return false;
1704 }
1705
Svetoslavd8d25e02015-11-20 13:09:26 -08001706 // Enforce what the calling package can mutate the system settings.
1707 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1708
Svetoslav683914b2015-01-15 14:22:26 -08001709 // Determine the owning user as some profile settings are cloned from the parent.
1710 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1711
1712 // Only the owning user id can change the setting.
1713 if (owningUserId != callingUserId) {
1714 return false;
1715 }
1716
Jeff Sharkey413573a2016-02-22 17:52:45 -07001717 // Invalidate any relevant cache files
1718 String cacheName = null;
1719 if (Settings.System.RINGTONE.equals(name)) {
1720 cacheName = Settings.System.RINGTONE_CACHE;
1721 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1722 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1723 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1724 cacheName = Settings.System.ALARM_ALERT_CACHE;
1725 }
1726 if (cacheName != null) {
1727 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001728 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001729 cacheFile.delete();
1730 }
1731
Svetoslav683914b2015-01-15 14:22:26 -08001732 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001733 synchronized (mLock) {
1734 switch (operation) {
1735 case MUTATION_OPERATION_INSERT: {
1736 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001737 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001738 owningUserId, name, value, null, false, getCallingPackage(),
1739 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001740 }
1741
1742 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001743 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001744 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001745 }
1746
1747 case MUTATION_OPERATION_UPDATE: {
1748 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001749 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001750 owningUserId, name, value, null, false, getCallingPackage(),
1751 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001752 }
Svetoslav683914b2015-01-15 14:22:26 -08001753 }
1754
Svetoslav7ec28e82015-05-20 17:01:10 -07001755 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001756 }
Svetoslav683914b2015-01-15 14:22:26 -08001757 }
1758
Billy Lau6ad2d662015-07-18 00:26:58 +01001759 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001760 // Write secure settings is a more protected permission. If caller has it we are good.
1761 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1762 == PackageManager.PERMISSION_GRANTED) {
1763 return true;
1764 }
1765
Svetoslavf41334b2015-06-23 12:06:03 -07001766 return false;
1767 }
1768
Svetoslav683914b2015-01-15 14:22:26 -08001769 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001770 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001771 if (validator != null && !validator.validate(value)) {
1772 throw new IllegalArgumentException("Invalid value: " + value
1773 + " for setting: " + name);
1774 }
1775 }
1776
Alex Klyubin1991f572017-03-03 14:08:36 -08001777 /**
1778 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1779 */
1780 private boolean isSecureSettingAccessible(String name, int callingUserId,
1781 int owningUserId) {
1782 // Special case for location (sigh).
1783 // This check is not inside the name-based checks below because this method performs checks
1784 // only if the calling user ID is not the same as the owning user ID.
1785 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1786 return false;
1787 }
1788
1789 switch (name) {
1790 case "bluetooth_address":
1791 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1792 // address in this secure setting. Secure settings can normally be read by any app,
1793 // which thus enables them to bypass the recently introduced restrictions on access
1794 // to device identifiers.
1795 // To mitigate this we make this setting available only to callers privileged to see
1796 // this device's MAC addresses, same as through public API
1797 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1798 return getContext().checkCallingOrSelfPermission(
1799 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1800 default:
1801 return true;
1802 }
1803 }
1804
Svetoslav683914b2015-01-15 14:22:26 -08001805 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1806 int owningUserId) {
1807 // Optimization - location providers are restricted only for managed profiles.
1808 if (callingUserId == owningUserId) {
1809 return false;
1810 }
1811 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1812 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1813 new UserHandle(callingUserId))) {
1814 return true;
1815 }
1816 return false;
1817 }
1818
Svetoslav683914b2015-01-15 14:22:26 -08001819 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1820 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1821 }
1822
1823 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001824 final int parentId;
1825 // Resolves dependency if setting has a dependency and the calling user has a parent
1826 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1827 && (parentId = getGroupParentLocked(userId)) != userId) {
1828 // The setting has a dependency and the profile has a parent
1829 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001830 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1831 final long token = Binder.clearCallingIdentity();
1832 try {
1833 Setting settingObj = getSecureSetting(dependency, userId);
1834 if (settingObj != null && settingObj.getValue().equals("1")) {
1835 return parentId;
1836 }
1837 } finally {
1838 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001839 }
1840 }
Svetoslav683914b2015-01-15 14:22:26 -08001841 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1842 }
1843
1844 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1845 final int parentId = getGroupParentLocked(userId);
1846 if (parentId != userId && keys.contains(name)) {
1847 return parentId;
1848 }
1849 return userId;
1850 }
1851
Svetoslavf41334b2015-06-23 12:06:03 -07001852 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001853 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001854 // System/root/shell can mutate whatever secure settings they want.
1855 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001856 final int appId = UserHandle.getAppId(callingUid);
1857 if (appId == android.os.Process.SYSTEM_UID
1858 || appId == Process.SHELL_UID
1859 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001860 return;
1861 }
1862
1863 switch (operation) {
1864 case MUTATION_OPERATION_INSERT:
1865 // Insert updates.
1866 case MUTATION_OPERATION_UPDATE: {
1867 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1868 return;
1869 }
1870
1871 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001872 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001873
1874 // Privileged apps can do whatever they want.
1875 if ((packageInfo.applicationInfo.privateFlags
1876 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1877 return;
1878 }
1879
1880 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1881 packageInfo.applicationInfo.targetSdkVersion, name);
1882 } break;
1883
1884 case MUTATION_OPERATION_DELETE: {
1885 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1886 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1887 throw new IllegalArgumentException("You cannot delete system defined"
1888 + " secure settings.");
1889 }
1890
1891 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001892 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001893
1894 // Privileged apps can do whatever they want.
1895 if ((packageInfo.applicationInfo.privateFlags &
1896 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1897 return;
1898 }
1899
1900 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1901 packageInfo.applicationInfo.targetSdkVersion, name);
1902 } break;
1903 }
1904 }
1905
Todd Kennedybe0b8892017-02-15 14:13:52 -08001906 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001907 switch (settingsType) {
1908 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001909 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001910 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001911 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001912 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001913 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001914 default:
1915 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1916 }
1917 }
1918
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001919 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1920 switch (settingsType) {
1921 case SETTINGS_TYPE_GLOBAL:
1922 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1923 case SETTINGS_TYPE_SYSTEM:
1924 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1925 case SETTINGS_TYPE_SECURE:
1926 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1927 default:
1928 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1929 }
1930 }
1931
Andreas Gampeb58893072018-09-05 16:52:31 -07001932 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001933 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001934 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1935 // in the current form.
1936 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001937 }
1938
Chad Brubakera6830e72017-04-28 17:34:36 -07001939 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001940 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1941 return;
1942 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001943 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001944 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001945 return;
1946 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001947 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1948 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001949 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1950 // breakage in the current form.
1951 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1952 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001953 }
1954 }
1955
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001956 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1957 // We always use the callingUid for this lookup. This means that if hypothetically an
1958 // app was installed in user A with cross user and in user B as an Instant App
1959 // the app in A would be able to see all the settings in user B. However since cross
1960 // user is a system permission and the app must be uninstalled in B and then installed as
1961 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001962 ApplicationInfo ai = null;
1963 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001964 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1965 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001966 } catch (RemoteException ignored) {
1967 }
1968 if (ai == null) {
1969 throw new IllegalStateException("Failed to lookup info for package "
1970 + getCallingPackage());
1971 }
1972 return ai;
1973 }
1974
Xiaohui Chen43765b72015-08-31 10:57:33 -07001975 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001976 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001977 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1978 getCallingPackage(), 0, userId);
1979 if (packageInfo != null) {
1980 return packageInfo;
1981 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001982 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001983 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001984 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001985 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001986 }
1987
1988 private int getGroupParentLocked(int userId) {
1989 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001990 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001991 return userId;
1992 }
1993 // We are in the same process with the user manager and the returned
1994 // user info is a cached instance, so just look up instead of cache.
1995 final long identity = Binder.clearCallingIdentity();
1996 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001997 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001998 UserInfo userInfo = mUserManager.getProfileParent(userId);
1999 return (userInfo != null) ? userInfo.id : userId;
2000 } finally {
2001 Binder.restoreCallingIdentity(identity);
2002 }
2003 }
2004
Svetoslav683914b2015-01-15 14:22:26 -08002005 private void enforceWritePermission(String permission) {
2006 if (getContext().checkCallingOrSelfPermission(permission)
2007 != PackageManager.PERMISSION_GRANTED) {
2008 throw new SecurityException("Permission denial: writing to settings requires:"
2009 + permission);
2010 }
2011 }
2012
2013 /*
2014 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2015 * This setting contains a list of the currently enabled location providers.
2016 * But helper functions in android.providers.Settings can enable or disable
2017 * a single provider by using a "+" or "-" prefix before the provider name.
2018 *
yuemingw1d13eae2018-01-30 17:27:54 +00002019 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2020 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2021 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002022 *
Svetoslav683914b2015-01-15 14:22:26 -08002023 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002024 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002025 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002026 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2027 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002028 if (TextUtils.isEmpty(value)) {
2029 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002030 }
Maggie83e03f52018-03-16 12:22:20 -07002031 Setting oldSetting = getSecureSetting(
2032 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2033 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002034 return false;
2035 }
Maggie83e03f52018-03-16 12:22:20 -07002036 String oldProviders = oldSetting.getValue();
2037 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2038 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2039 Set<String> newProvidersSet = new ArraySet<>();
2040 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002041
Maggie83e03f52018-03-16 12:22:20 -07002042 String[] providerUpdates = value.split(",");
2043 boolean inputError = false;
2044 for (String provider : providerUpdates) {
2045 // do not update location_providers_allowed when input is invalid
2046 if (TextUtils.isEmpty(provider)) {
2047 inputError = true;
2048 break;
Svetoslav683914b2015-01-15 14:22:26 -08002049 }
Maggie83e03f52018-03-16 12:22:20 -07002050 final char prefix = provider.charAt(0);
2051 // do not update location_providers_allowed when input is invalid
2052 if (prefix != '+' && prefix != '-') {
2053 inputError = true;
2054 break;
Svetoslav683914b2015-01-15 14:22:26 -08002055 }
Maggie83e03f52018-03-16 12:22:20 -07002056 // skip prefix
2057 provider = provider.substring(1);
2058 if (prefix == '+') {
2059 newProvidersSet.add(provider);
2060 } else if (prefix == '-') {
2061 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002062 }
Maggie83e03f52018-03-16 12:22:20 -07002063 }
2064 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2065 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002066 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002067 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002068 mSettingsRegistry.notifyForSettingsChange(
2069 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002070 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2071 }
Svetoslav683914b2015-01-15 14:22:26 -08002072 return false;
2073 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002074 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002075 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2076 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002077 }
2078
Svetoslav683914b2015-01-15 14:22:26 -08002079 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2080 int targetSdkVersion, String name) {
2081 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2082 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2083 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2084 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2085 + " This will soon become an error.");
2086 } else {
2087 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2088 + " This will soon become an error.");
2089 }
2090 } else {
2091 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2092 throw new IllegalArgumentException("You cannot change private secure settings.");
2093 } else {
2094 throw new IllegalArgumentException("You cannot keep your settings in"
2095 + " the secure settings.");
2096 }
2097 }
2098 }
2099
2100 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2101 if (requestingUserId == UserHandle.getCallingUserId()) {
2102 return requestingUserId;
2103 }
2104 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2105 Binder.getCallingUid(), requestingUserId, false, true,
2106 "get/set setting for user", null);
2107 }
2108
Svet Ganov53a441c2016-04-19 19:38:00 -07002109 private Bundle packageValueForCallResult(Setting setting,
2110 boolean trackingGeneration) {
2111 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002112 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002113 return NULL_SETTING_BUNDLE;
2114 }
2115 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002116 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002117 Bundle result = new Bundle();
2118 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002119 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002120
Svetoslav Ganove080da92016-12-21 17:10:35 -08002121 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002122 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002123 }
2124
2125 private static int getRequestingUserId(Bundle args) {
2126 final int callingUserId = UserHandle.getCallingUserId();
2127 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2128 : callingUserId;
2129 }
2130
Svet Ganov53a441c2016-04-19 19:38:00 -07002131 private boolean isTrackingGeneration(Bundle args) {
2132 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2133 }
2134
Svetoslav683914b2015-01-15 14:22:26 -08002135 private static String getSettingValue(Bundle args) {
2136 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2137 }
2138
Svetoslav Ganove080da92016-12-21 17:10:35 -08002139 private static String getSettingTag(Bundle args) {
2140 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2141 }
2142
Matt Pape6bfc62e2018-11-28 13:16:03 -08002143 private static String getSettingPrefix(Bundle args) {
2144 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2145 // Append '/' to ensure we only match properties with this exact prefix.
2146 // i.e. "foo" should match "foo/property" but not "foobar/property"
2147 return prefix != null ? prefix + "/" : null;
2148 }
2149
Svetoslav Ganove080da92016-12-21 17:10:35 -08002150 private static boolean getSettingMakeDefault(Bundle args) {
2151 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2152 }
2153
2154 private static int getResetModeEnforcingPermission(Bundle args) {
2155 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2156 switch (mode) {
2157 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2158 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2159 throw new SecurityException("Only system, shell/root on a "
2160 + "debuggable build can reset to untrusted defaults");
2161 }
2162 return mode;
2163 }
2164 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2165 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2166 throw new SecurityException("Only system, shell/root on a "
2167 + "debuggable build can reset untrusted changes");
2168 }
2169 return mode;
2170 }
2171 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2172 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2173 throw new SecurityException("Only system, shell/root on a "
2174 + "debuggable build can reset to trusted defaults");
2175 }
2176 return mode;
2177 }
2178 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2179 return mode;
2180 }
2181 }
2182 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2183 }
2184
2185 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2186 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2187 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2188 && (appId == SHELL_UID || appId == ROOT_UID));
2189 }
2190
Svetoslav683914b2015-01-15 14:22:26 -08002191 private static String getValidTableOrThrow(Uri uri) {
2192 if (uri.getPathSegments().size() > 0) {
2193 String table = uri.getPathSegments().get(0);
2194 if (DatabaseHelper.isValidTable(table)) {
2195 return table;
2196 }
2197 throw new IllegalArgumentException("Bad root path: " + table);
2198 }
2199 throw new IllegalArgumentException("Invalid URI:" + uri);
2200 }
2201
2202 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002203 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002204 return new MatrixCursor(projection, 0);
2205 }
2206 MatrixCursor cursor = new MatrixCursor(projection, 1);
2207 appendSettingToCursor(cursor, setting);
2208 return cursor;
2209 }
2210
2211 private static String[] normalizeProjection(String[] projection) {
2212 if (projection == null) {
2213 return ALL_COLUMNS;
2214 }
2215
2216 final int columnCount = projection.length;
2217 for (int i = 0; i < columnCount; i++) {
2218 String column = projection[i];
2219 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2220 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002221 }
2222 }
2223
Svetoslav683914b2015-01-15 14:22:26 -08002224 return projection;
2225 }
2226
2227 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002228 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002229 return;
2230 }
Svetoslav683914b2015-01-15 14:22:26 -08002231 final int columnCount = cursor.getColumnCount();
2232
2233 String[] values = new String[columnCount];
2234
2235 for (int i = 0; i < columnCount; i++) {
2236 String column = cursor.getColumnName(i);
2237
2238 switch (column) {
2239 case Settings.NameValueTable._ID: {
2240 values[i] = setting.getId();
2241 } break;
2242
2243 case Settings.NameValueTable.NAME: {
2244 values[i] = setting.getName();
2245 } break;
2246
2247 case Settings.NameValueTable.VALUE: {
2248 values[i] = setting.getValue();
2249 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002250 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002251 }
2252
Svetoslav683914b2015-01-15 14:22:26 -08002253 cursor.addRow(values);
2254 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002255
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002256 private static boolean isKeyValid(String key) {
2257 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2258 }
2259
Svetoslav683914b2015-01-15 14:22:26 -08002260 private static final class Arguments {
2261 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2262 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2263
2264 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2265 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2266
2267 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2268 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2269
2270 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2271 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2272
2273 public final String table;
2274 public final String name;
2275
2276 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2277 final int segmentSize = uri.getPathSegments().size();
2278 switch (segmentSize) {
2279 case 1: {
2280 if (where != null
2281 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2282 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2283 && whereArgs.length == 1) {
2284 name = whereArgs[0];
2285 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002286 return;
Svetoslav683914b2015-01-15 14:22:26 -08002287 } else if (where != null
2288 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2289 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2290 final int startIndex = Math.max(where.indexOf("'"),
2291 where.indexOf("\"")) + 1;
2292 final int endIndex = Math.max(where.lastIndexOf("'"),
2293 where.lastIndexOf("\""));
2294 name = where.substring(startIndex, endIndex);
2295 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002296 return;
Svetoslav683914b2015-01-15 14:22:26 -08002297 } else if (supportAll && where == null && whereArgs == null) {
2298 name = null;
2299 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002300 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002301 }
Svetoslav683914b2015-01-15 14:22:26 -08002302 } break;
2303
Svetoslav28494652015-02-12 14:11:42 -08002304 case 2: {
2305 if (where == null && whereArgs == null) {
2306 name = uri.getPathSegments().get(1);
2307 table = computeTableForSetting(uri, name);
2308 return;
2309 }
2310 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002311 }
Svetoslav28494652015-02-12 14:11:42 -08002312
2313 EventLogTags.writeUnsupportedSettingsQuery(
2314 uri.toSafeString(), where, Arrays.toString(whereArgs));
2315 String message = String.format( "Supported SQL:\n"
2316 + " uri content://some_table/some_property with null where and where args\n"
2317 + " uri content://some_table with query name=? and single name as arg\n"
2318 + " uri content://some_table with query name=some_name and null args\n"
2319 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2320 Arrays.toString(whereArgs));
2321 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002322 }
2323
Svetoslav28494652015-02-12 14:11:42 -08002324 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002325 String table = getValidTableOrThrow(uri);
2326
2327 if (name != null) {
2328 if (sSystemMovedToSecureSettings.contains(name)) {
2329 table = TABLE_SECURE;
2330 }
2331
2332 if (sSystemMovedToGlobalSettings.contains(name)) {
2333 table = TABLE_GLOBAL;
2334 }
2335
2336 if (sSecureMovedToGlobalSettings.contains(name)) {
2337 table = TABLE_GLOBAL;
2338 }
2339
2340 if (sGlobalMovedToSecureSettings.contains(name)) {
2341 table = TABLE_SECURE;
2342 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002343 }
Svetoslav683914b2015-01-15 14:22:26 -08002344
2345 return table;
2346 }
2347 }
2348
2349 final class SettingsRegistry {
2350 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2351
Svetoslav683914b2015-01-15 14:22:26 -08002352 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2353 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2354 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002355 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002356 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002357
2358 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002359
2360 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2361
Svet Ganov53a441c2016-04-19 19:38:00 -07002362 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002363
Svetoslav7e0683b2015-08-03 16:02:52 -07002364 private final Handler mHandler;
2365
Svet Ganov53a441c2016-04-19 19:38:00 -07002366 private final BackupManager mBackupManager;
2367
Amith Yamasani39452022017-03-21 15:23:47 -07002368 private String mSettingsCreationBuildId;
2369
Svetoslav683914b2015-01-15 14:22:26 -08002370 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002371 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002372 mGenerationRegistry = new GenerationRegistry(mLock);
2373 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002374 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002375 syncSsaidTableOnStart();
2376 }
2377
2378 private void generateUserKeyLocked(int userId) {
2379 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002380 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002381 final SecureRandom rand = new SecureRandom();
2382 rand.nextBytes(keyBytes);
2383
2384 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002385 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002386
2387 // Store the key in the ssaid table.
2388 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2389 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2390 true, SettingsState.SYSTEM_PACKAGE_NAME);
2391
2392 if (!success) {
2393 throw new IllegalStateException("Ssaid settings not accessible");
2394 }
2395 }
2396
Mark Rathjen7599f132017-01-23 14:15:54 -08002397 private byte[] getLengthPrefix(byte[] data) {
2398 return ByteBuffer.allocate(4).putInt(data.length).array();
2399 }
2400
Christopher Tateb218e762017-04-05 16:34:07 -07002401 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002402 // Read the user's key from the ssaid table.
2403 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002404 if (userKeySetting == null || userKeySetting.isNull()
2405 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002406 // Lazy initialize and store the user key.
2407 generateUserKeyLocked(userId);
2408 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002409 if (userKeySetting == null || userKeySetting.isNull()
2410 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002411 throw new IllegalStateException("User key not accessible");
2412 }
2413 }
2414 final String userKey = userKeySetting.getValue();
2415
2416 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002417 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2418
2419 // Validate that the key is of expected length.
2420 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2421 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002422 throw new IllegalStateException("User key invalid");
2423 }
2424
Mark Rathjen7599f132017-01-23 14:15:54 -08002425 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002426 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002427 m = Mac.getInstance("HmacSHA256");
2428 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002429 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002430 throw new IllegalStateException("HmacSHA256 is not available", e);
2431 } catch (InvalidKeyException e) {
2432 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002433 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002434
Mark Rathjenf42dd912017-06-05 19:04:34 -07002435 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002436 for (int i = 0; i < callingPkg.signatures.length; i++) {
2437 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002438 m.update(getLengthPrefix(sig), 0, 4);
2439 m.update(sig);
2440 }
Mark Rathjend891f012017-01-19 04:10:37 +00002441
2442 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002443 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2444 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002445
2446 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002447 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002448 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2449 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002450 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002451
2452 if (!success) {
2453 throw new IllegalStateException("Ssaid settings not accessible");
2454 }
2455
2456 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2457 }
2458
2459 public void syncSsaidTableOnStart() {
2460 synchronized (mLock) {
2461 // Verify that each user's packages and ssaid's are in sync.
2462 for (UserInfo user : mUserManager.getUsers(true)) {
2463 // Get all uids for the user's packages.
2464 final List<PackageInfo> packages;
2465 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002466 packages = mPackageManager.getInstalledPackages(
2467 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2468 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002469 } catch (RemoteException e) {
2470 throw new IllegalStateException("Package manager not available");
2471 }
2472 final Set<String> appUids = new HashSet<>();
2473 for (PackageInfo info : packages) {
2474 appUids.add(Integer.toString(info.applicationInfo.uid));
2475 }
2476
2477 // Get all uids currently stored in the user's ssaid table.
2478 final Set<String> ssaidUids = new HashSet<>(
2479 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2480 ssaidUids.remove(SSAID_USER_KEY);
2481
2482 // Perform a set difference for the appUids and ssaidUids.
2483 ssaidUids.removeAll(appUids);
2484
2485 // If there are ssaidUids left over they need to be removed from the table.
2486 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2487 user.id);
2488 for (String uid : ssaidUids) {
2489 ssaidSettings.deleteSettingLocked(uid);
2490 }
2491 }
2492 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002493 }
2494
Svetoslav683914b2015-01-15 14:22:26 -08002495 public List<String> getSettingsNamesLocked(int type, int userId) {
2496 final int key = makeKey(type, userId);
2497 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002498 if (settingsState == null) {
2499 return new ArrayList<String>();
2500 }
Svetoslav683914b2015-01-15 14:22:26 -08002501 return settingsState.getSettingNamesLocked();
2502 }
2503
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002504 public SparseBooleanArray getKnownUsersLocked() {
2505 SparseBooleanArray users = new SparseBooleanArray();
2506 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2507 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2508 }
2509 return users;
2510 }
2511
Kweku Adamsb0886f32017-10-31 15:32:09 -07002512 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002513 public SettingsState getSettingsLocked(int type, int userId) {
2514 final int key = makeKey(type, userId);
2515 return peekSettingsStateLocked(key);
2516 }
2517
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002518 public boolean ensureSettingsForUserLocked(int userId) {
2519 // First make sure this user actually exists.
2520 if (mUserManager.getUserInfo(userId) == null) {
2521 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2522 return false;
2523 }
2524
Svetoslav683914b2015-01-15 14:22:26 -08002525 // Migrate the setting for this user if needed.
2526 migrateLegacySettingsForUserIfNeededLocked(userId);
2527
Matt Pape1b31a332018-10-17 09:58:28 -07002528 // Ensure config settings loaded if owner.
2529 if (userId == UserHandle.USER_SYSTEM) {
2530 final int configKey
2531 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2532 ensureSettingsStateLocked(configKey);
2533 }
2534
Svetoslav683914b2015-01-15 14:22:26 -08002535 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002536 if (userId == UserHandle.USER_SYSTEM) {
2537 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002538 ensureSettingsStateLocked(globalKey);
2539 }
2540
2541 // Ensure secure settings loaded.
2542 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2543 ensureSettingsStateLocked(secureKey);
2544
2545 // Make sure the secure settings have an Android id set.
2546 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2547 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2548
2549 // Ensure system settings loaded.
2550 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2551 ensureSettingsStateLocked(systemKey);
2552
Mark Rathjend891f012017-01-19 04:10:37 +00002553 // Ensure secure settings loaded.
2554 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2555 ensureSettingsStateLocked(ssaidKey);
2556
Svetoslav683914b2015-01-15 14:22:26 -08002557 // Upgrade the settings to the latest version.
2558 UpgradeController upgrader = new UpgradeController(userId);
2559 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002560 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002561 }
2562
2563 private void ensureSettingsStateLocked(int key) {
2564 if (mSettingsStates.get(key) == null) {
2565 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002566 SettingsState settingsState = new SettingsState(getContext(), mLock,
2567 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002568 mSettingsStates.put(key, settingsState);
2569 }
2570 }
2571
2572 public void removeUserStateLocked(int userId, boolean permanently) {
2573 // We always keep the global settings in memory.
2574
2575 // Nuke system settings.
2576 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2577 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2578 if (systemSettingsState != null) {
2579 if (permanently) {
2580 mSettingsStates.remove(systemKey);
2581 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002582 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002583 systemSettingsState.destroyLocked(new Runnable() {
2584 @Override
2585 public void run() {
2586 mSettingsStates.remove(systemKey);
2587 }
2588 });
2589 }
2590 }
2591
2592 // Nuke secure settings.
2593 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2594 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2595 if (secureSettingsState != null) {
2596 if (permanently) {
2597 mSettingsStates.remove(secureKey);
2598 secureSettingsState.destroyLocked(null);
2599 } else {
2600 secureSettingsState.destroyLocked(new Runnable() {
2601 @Override
2602 public void run() {
2603 mSettingsStates.remove(secureKey);
2604 }
2605 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002606 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002607 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002608
Mark Rathjend891f012017-01-19 04:10:37 +00002609 // Nuke ssaid settings.
2610 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2611 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2612 if (ssaidSettingsState != null) {
2613 if (permanently) {
2614 mSettingsStates.remove(ssaidKey);
2615 ssaidSettingsState.destroyLocked(null);
2616 } else {
2617 ssaidSettingsState.destroyLocked(new Runnable() {
2618 @Override
2619 public void run() {
2620 mSettingsStates.remove(ssaidKey);
2621 }
2622 });
2623 }
2624 }
2625
Svet Ganov53a441c2016-04-19 19:38:00 -07002626 // Nuke generation tracking data
2627 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002628 }
2629
Svetoslav683914b2015-01-15 14:22:26 -08002630 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002631 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2632 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002633 final int key = makeKey(type, userId);
2634
Svetoslav Ganove080da92016-12-21 17:10:35 -08002635 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002636 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002637 if (settingsState != null) {
2638 success = settingsState.insertSettingLocked(name, value,
2639 tag, makeDefault, packageName);
2640 }
Svetoslav683914b2015-01-15 14:22:26 -08002641
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002642 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2643 settingsState.persistSyncLocked();
2644 }
2645
Svet Ganov53a441c2016-04-19 19:38:00 -07002646 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002647 notifyForSettingsChange(key, name);
2648 }
2649 return success;
2650 }
2651
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002652 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2653 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002654 final int key = makeKey(type, userId);
2655
Svetoslav Ganove080da92016-12-21 17:10:35 -08002656 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002657 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002658 if (settingsState != null) {
2659 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002660 }
Svetoslav683914b2015-01-15 14:22:26 -08002661
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002662 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2663 settingsState.persistSyncLocked();
2664 }
2665
Svet Ganov53a441c2016-04-19 19:38:00 -07002666 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002667 notifyForSettingsChange(key, name);
2668 }
2669 return success;
2670 }
2671
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002672 public boolean updateSettingLocked(int type, int userId, String name, String value,
2673 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2674 Set<String> criticalSettings) {
2675 final int key = makeKey(type, userId);
2676
2677 boolean success = false;
2678 SettingsState settingsState = peekSettingsStateLocked(key);
2679 if (settingsState != null) {
2680 success = settingsState.updateSettingLocked(name, value, tag,
2681 makeDefault, packageName);
2682 }
2683
2684 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2685 settingsState.persistSyncLocked();
2686 }
2687
2688 if (forceNotify || success) {
2689 notifyForSettingsChange(key, name);
2690 }
2691
2692 return success;
2693 }
2694
Svetoslav683914b2015-01-15 14:22:26 -08002695 public Setting getSettingLocked(int type, int userId, String name) {
2696 final int key = makeKey(type, userId);
2697
2698 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002699 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002700 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002701 }
Mark Rathjend891f012017-01-19 04:10:37 +00002702
2703 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002704 return settingsState.getSettingLocked(name);
2705 }
2706
Svetoslav Ganove080da92016-12-21 17:10:35 -08002707 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2708 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002709 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2710 }
2711
2712 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2713 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002714 final int key = makeKey(type, userId);
2715 SettingsState settingsState = peekSettingsStateLocked(key);
2716 if (settingsState == null) {
2717 return;
2718 }
2719
2720 switch (mode) {
2721 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2722 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002723 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002724 Setting setting = settingsState.getSettingLocked(name);
2725 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002726 if ((tag != null && !tag.equals(setting.getTag()))
2727 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002728 continue;
2729 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002730 if (settingsState.resetSettingLocked(name)) {
2731 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002732 notifyForSettingsChange(key, name);
2733 }
2734 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002735 if (someSettingChanged) {
2736 settingsState.persistSyncLocked();
2737 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002738 }
2739 } break;
2740
2741 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2742 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002743 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002744 Setting setting = settingsState.getSettingLocked(name);
2745 if (!SettingsState.isSystemPackage(getContext(),
2746 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002747 if (prefix != null && !setting.getName().startsWith(prefix)) {
2748 continue;
2749 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002750 if (settingsState.resetSettingLocked(name)) {
2751 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002752 notifyForSettingsChange(key, name);
2753 }
2754 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002755 if (someSettingChanged) {
2756 settingsState.persistSyncLocked();
2757 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002758 }
2759 } break;
2760
2761 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2762 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002763 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002764 Setting setting = settingsState.getSettingLocked(name);
2765 if (!SettingsState.isSystemPackage(getContext(),
2766 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002767 if (prefix != null && !setting.getName().startsWith(prefix)) {
2768 continue;
2769 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002770 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002771 if (settingsState.resetSettingLocked(name)) {
2772 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002773 notifyForSettingsChange(key, name);
2774 }
2775 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002776 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002777 notifyForSettingsChange(key, name);
2778 }
2779 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002780 if (someSettingChanged) {
2781 settingsState.persistSyncLocked();
2782 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002783 }
2784 } break;
2785
2786 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2787 for (String name : settingsState.getSettingNamesLocked()) {
2788 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002789 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002790 if (prefix != null && !setting.getName().startsWith(prefix)) {
2791 continue;
2792 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002793 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002794 if (settingsState.resetSettingLocked(name)) {
2795 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002796 notifyForSettingsChange(key, name);
2797 }
2798 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002799 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002800 notifyForSettingsChange(key, name);
2801 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002802 if (someSettingChanged) {
2803 settingsState.persistSyncLocked();
2804 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002805 }
2806 } break;
2807 }
2808 }
2809
Zimuzoc56192c2018-07-25 10:40:01 +01002810 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002811 // Global and secure settings are signature protected. Apps signed
2812 // by the platform certificate are generally not uninstalled and
2813 // the main exception is tests. We trust components signed
2814 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002815
2816 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2817 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002818 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002819 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002820 }
Svetoslav683914b2015-01-15 14:22:26 -08002821 }
2822
Mark Rathjend891f012017-01-19 04:10:37 +00002823 public void onUidRemovedLocked(int uid) {
2824 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2825 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002826 if (ssaidSettings != null) {
2827 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2828 }
Mark Rathjend891f012017-01-19 04:10:37 +00002829 }
2830
Kweku Adamsb0886f32017-10-31 15:32:09 -07002831 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002832 private SettingsState peekSettingsStateLocked(int key) {
2833 SettingsState settingsState = mSettingsStates.get(key);
2834 if (settingsState != null) {
2835 return settingsState;
2836 }
2837
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002838 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2839 return null;
2840 }
Svetoslav683914b2015-01-15 14:22:26 -08002841 return mSettingsStates.get(key);
2842 }
2843
2844 private void migrateAllLegacySettingsIfNeeded() {
2845 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002846 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002847 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002848 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002849 return;
2850 }
2851
Amith Yamasani39452022017-03-21 15:23:47 -07002852 mSettingsCreationBuildId = Build.ID;
2853
Svetoslav683914b2015-01-15 14:22:26 -08002854 final long identity = Binder.clearCallingIdentity();
2855 try {
2856 List<UserInfo> users = mUserManager.getUsers(true);
2857
2858 final int userCount = users.size();
2859 for (int i = 0; i < userCount; i++) {
2860 final int userId = users.get(i).id;
2861
2862 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2863 SQLiteDatabase database = dbHelper.getWritableDatabase();
2864 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2865
2866 // Upgrade to the latest version.
2867 UpgradeController upgrader = new UpgradeController(userId);
2868 upgrader.upgradeIfNeededLocked();
2869
2870 // Drop from memory if not a running user.
2871 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2872 removeUserStateLocked(userId, false);
2873 }
2874 }
2875 } finally {
2876 Binder.restoreCallingIdentity(identity);
2877 }
2878 }
2879 }
2880
2881 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2882 // Every user has secure settings and if no file we need to migrate.
2883 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2884 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002885 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002886 return;
2887 }
2888
2889 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2890 SQLiteDatabase database = dbHelper.getWritableDatabase();
2891
2892 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2893 }
2894
2895 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2896 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002897 // Move over the system settings.
2898 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2899 ensureSettingsStateLocked(systemKey);
2900 SettingsState systemSettings = mSettingsStates.get(systemKey);
2901 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2902 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002903
2904 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002905 // Do this after System settings, since this is the first thing we check when deciding
2906 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002907 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2908 ensureSettingsStateLocked(secureKey);
2909 SettingsState secureSettings = mSettingsStates.get(secureKey);
2910 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2911 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2912 secureSettings.persistSyncLocked();
2913
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002914 // Move over the global settings if owner.
2915 // Do this last, since this is the first thing we check when deciding
2916 // to skip over migration from db to xml for owner user.
2917 if (userId == UserHandle.USER_SYSTEM) {
2918 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2919 ensureSettingsStateLocked(globalKey);
2920 SettingsState globalSettings = mSettingsStates.get(globalKey);
2921 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002922 // If this was just created
2923 if (mSettingsCreationBuildId != null) {
2924 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2925 mSettingsCreationBuildId, null, true,
2926 SettingsState.SYSTEM_PACKAGE_NAME);
2927 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002928 globalSettings.persistSyncLocked();
2929 }
Svetoslav683914b2015-01-15 14:22:26 -08002930
2931 // Drop the database as now all is moved and persisted.
2932 if (DROP_DATABASE_ON_MIGRATION) {
2933 dbHelper.dropDatabase();
2934 } else {
2935 dbHelper.backupDatabase();
2936 }
2937 }
2938
2939 private void migrateLegacySettingsLocked(SettingsState settingsState,
2940 SQLiteDatabase database, String table) {
2941 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2942 queryBuilder.setTables(table);
2943
2944 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2945 null, null, null, null, null);
2946
2947 if (cursor == null) {
2948 return;
2949 }
2950
2951 try {
2952 if (!cursor.moveToFirst()) {
2953 return;
2954 }
2955
2956 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2957 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2958
2959 settingsState.setVersionLocked(database.getVersion());
2960
2961 while (!cursor.isAfterLast()) {
2962 String name = cursor.getString(nameColumnIdx);
2963 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002964 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002965 SettingsState.SYSTEM_PACKAGE_NAME);
2966 cursor.moveToNext();
2967 }
2968 } finally {
2969 cursor.close();
2970 }
2971 }
2972
Andreas Gampeb58893072018-09-05 16:52:31 -07002973 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002974 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2975 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2976
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002977 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002978 return;
2979 }
2980
2981 final int userId = getUserIdFromKey(secureSettings.mKey);
2982
2983 final UserInfo user;
2984 final long identity = Binder.clearCallingIdentity();
2985 try {
2986 user = mUserManager.getUserInfo(userId);
2987 } finally {
2988 Binder.restoreCallingIdentity(identity);
2989 }
2990 if (user == null) {
2991 // Can happen due to races when deleting users - treat as benign.
2992 return;
2993 }
2994
2995 String androidId = Long.toHexString(new SecureRandom().nextLong());
2996 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002997 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002998
2999 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3000 + "] for user " + userId);
3001
3002 // Write a drop box entry if it's a restricted profile
3003 if (user.isRestricted()) {
3004 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3005 Context.DROPBOX_SERVICE);
3006 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3007 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3008 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3009 }
3010 }
3011 }
3012
3013 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003014 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003015 mGenerationRegistry.incrementGeneration(key);
3016
Svet Ganov945864c2018-03-22 21:49:10 -07003017 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003018 final long token = Binder.clearCallingIdentity();
3019 try {
3020 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3021 // When the global kill switch is updated, send the
3022 // change notification for the location setting.
3023 notifyLocationChangeForRunningUsers();
3024 }
3025 notifyGlobalSettingChangeForRunningUsers(key, name);
3026 } finally {
3027 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003028 }
Svet Ganov945864c2018-03-22 21:49:10 -07003029 } else {
3030 final int userId = getUserIdFromKey(key);
3031 final Uri uri = getNotificationUriFor(key, name);
3032 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3033 userId, 0, uri).sendToTarget();
3034 if (isSecureSettingsKey(key)) {
3035 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3036 sSecureCloneToManagedSettings);
3037 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3038 sSystemCloneFromParentOnDependency.values());
3039 } else if (isSystemSettingsKey(key)) {
3040 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3041 sSystemCloneToManagedSettings);
3042 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003043 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003044
Svet Ganov945864c2018-03-22 21:49:10 -07003045 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003046 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003047 }
3048
Svet Ganov53a441c2016-04-19 19:38:00 -07003049 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003050 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003051 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003052 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003053 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003054 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003055 final int key = makeKey(type, profileId);
3056 // Increment the generation first, so observers always see the new value
3057 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003058 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003059 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003060 }
3061 }
3062 }
Svetoslav683914b2015-01-15 14:22:26 -08003063 }
3064
Svet Ganov945864c2018-03-22 21:49:10 -07003065 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3066 // Important: No need to update generation for each user as there
3067 // is a singleton generation entry for the global settings which
3068 // is already incremented be the caller.
3069 final Uri uri = getNotificationUriFor(key, name);
3070 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3071 for (int i = 0; i < users.size(); i++) {
3072 final int userId = users.get(i).id;
3073 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3074 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3075 userId, 0, uri).sendToTarget();
3076 }
3077 }
3078 }
3079
Makoto Onuki0000d322017-11-28 16:31:47 -08003080 private void notifyLocationChangeForRunningUsers() {
3081 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3082
3083 for (int i = 0; i < users.size(); i++) {
3084 final int userId = users.get(i).id;
3085
3086 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3087 continue;
3088 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003089
Svet Ganov945864c2018-03-22 21:49:10 -07003090 // Increment the generation first, so observers always see the new value
3091 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3092 mGenerationRegistry.incrementGeneration(key);
3093
3094 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003095 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3096 userId, 0, uri).sendToTarget();
3097 }
3098 }
3099
Matt Pape1b31a332018-10-17 09:58:28 -07003100 private boolean isConfigSettingsKey(int key) {
3101 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3102 }
3103
Svetoslav683914b2015-01-15 14:22:26 -08003104 private boolean isGlobalSettingsKey(int key) {
3105 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3106 }
3107
3108 private boolean isSystemSettingsKey(int key) {
3109 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3110 }
3111
3112 private boolean isSecureSettingsKey(int key) {
3113 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3114 }
3115
Mark Rathjend891f012017-01-19 04:10:37 +00003116 private boolean isSsaidSettingsKey(int key) {
3117 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3118 }
3119
Svetoslav683914b2015-01-15 14:22:26 -08003120 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003121 if (isConfigSettingsKey(key)) {
3122 final int userId = getUserIdFromKey(key);
3123 return new File(Environment.getUserSystemDirectory(userId),
3124 SETTINGS_FILE_CONFIG);
3125 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003126 final int userId = getUserIdFromKey(key);
3127 return new File(Environment.getUserSystemDirectory(userId),
3128 SETTINGS_FILE_GLOBAL);
3129 } else if (isSystemSettingsKey(key)) {
3130 final int userId = getUserIdFromKey(key);
3131 return new File(Environment.getUserSystemDirectory(userId),
3132 SETTINGS_FILE_SYSTEM);
3133 } else if (isSecureSettingsKey(key)) {
3134 final int userId = getUserIdFromKey(key);
3135 return new File(Environment.getUserSystemDirectory(userId),
3136 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003137 } else if (isSsaidSettingsKey(key)) {
3138 final int userId = getUserIdFromKey(key);
3139 return new File(Environment.getUserSystemDirectory(userId),
3140 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003141 } else {
3142 throw new IllegalArgumentException("Invalid settings key:" + key);
3143 }
3144 }
3145
3146 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003147 if (isConfigSettingsKey(key)) {
3148 return (name != null) ? Uri.withAppendedPath(CONFIG_CONTENT_URI, name)
3149 : CONFIG_CONTENT_URI;
3150 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003151 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3152 : Settings.Global.CONTENT_URI;
3153 } else if (isSecureSettingsKey(key)) {
3154 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3155 : Settings.Secure.CONTENT_URI;
3156 } else if (isSystemSettingsKey(key)) {
3157 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3158 : Settings.System.CONTENT_URI;
3159 } else {
3160 throw new IllegalArgumentException("Invalid settings key:" + key);
3161 }
3162 }
3163
3164 private int getMaxBytesPerPackageForType(int type) {
3165 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003166 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003167 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003168 case SETTINGS_TYPE_SECURE:
3169 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003170 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3171 }
3172
3173 default: {
3174 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3175 }
3176 }
3177 }
3178
Svetoslav7e0683b2015-08-03 16:02:52 -07003179 private final class MyHandler extends Handler {
3180 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3181 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3182
3183 public MyHandler(Looper looper) {
3184 super(looper);
3185 }
3186
3187 @Override
3188 public void handleMessage(Message msg) {
3189 switch (msg.what) {
3190 case MSG_NOTIFY_URI_CHANGED: {
3191 final int userId = msg.arg1;
3192 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003193 try {
3194 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3195 } catch (SecurityException e) {
3196 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3197 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003198 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003199 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3200 }
3201 } break;
3202
3203 case MSG_NOTIFY_DATA_CHANGED: {
3204 mBackupManager.dataChanged();
3205 } break;
3206 }
3207 }
3208 }
3209
Svetoslav683914b2015-01-15 14:22:26 -08003210 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003211 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003212
3213 private final int mUserId;
3214
3215 public UpgradeController(int userId) {
3216 mUserId = userId;
3217 }
3218
3219 public void upgradeIfNeededLocked() {
3220 // The version of all settings for a user is the same (all users have secure).
3221 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003222 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003223
3224 // Try an update from the current state.
3225 final int oldVersion = secureSettings.getVersionLocked();
3226 final int newVersion = SETTINGS_VERSION;
3227
Svet Ganovc9755bc2015-03-28 13:21:22 -07003228 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003229 if (oldVersion == newVersion) {
3230 return;
3231 }
3232
3233 // Try to upgrade.
3234 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3235
3236 // If upgrade failed start from scratch and upgrade.
3237 if (curVersion != newVersion) {
3238 // Drop state we have for this user.
3239 removeUserStateLocked(mUserId, true);
3240
3241 // Recreate the database.
3242 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3243 SQLiteDatabase database = dbHelper.getWritableDatabase();
3244 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3245
3246 // Migrate the settings for this user.
3247 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3248
3249 // Now upgrade should work fine.
3250 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003251
3252 // Make a note what happened, so we don't wonder why data was lost
3253 String reason = "Settings rebuilt! Current version: "
3254 + curVersion + " while expected: " + newVersion;
3255 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003256 Settings.Global.DATABASE_DOWNGRADE_REASON,
3257 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003258 }
3259
3260 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003261 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003262 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003263 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003264 globalSettings.setVersionLocked(newVersion);
3265 }
3266
3267 // Set the secure settings version.
3268 secureSettings.setVersionLocked(newVersion);
3269
3270 // Set the system settings version.
3271 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003272 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003273 systemSettings.setVersionLocked(newVersion);
3274 }
3275
3276 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003277 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003278 }
3279
3280 private SettingsState getSecureSettingsLocked(int userId) {
3281 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3282 }
3283
Mark Rathjend891f012017-01-19 04:10:37 +00003284 private SettingsState getSsaidSettingsLocked(int userId) {
3285 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3286 }
3287
Svetoslav683914b2015-01-15 14:22:26 -08003288 private SettingsState getSystemSettingsLocked(int userId) {
3289 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3290 }
3291
Jeff Brown503cffc2015-03-26 18:08:51 -07003292 /**
3293 * You must perform all necessary mutations to bring the settings
3294 * for this user from the old to the new version. When you add a new
3295 * upgrade step you *must* update SETTINGS_VERSION.
3296 *
3297 * This is an example of moving a setting from secure to global.
3298 *
3299 * // v119: Example settings changes.
3300 * if (currentVersion == 118) {
3301 * if (userId == UserHandle.USER_OWNER) {
3302 * // Remove from the secure settings.
3303 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3304 * String name = "example_setting_to_move";
3305 * String value = secureSettings.getSetting(name);
3306 * secureSettings.deleteSetting(name);
3307 *
3308 * // Add to the global settings.
3309 * SettingsState globalSettings = getGlobalSettingsLocked();
3310 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3311 * }
3312 *
3313 * // Update the current version.
3314 * currentVersion = 119;
3315 * }
3316 */
Svetoslav683914b2015-01-15 14:22:26 -08003317 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3318 if (DEBUG) {
3319 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3320 + oldVersion + " to version: " + newVersion);
3321 }
3322
Jeff Brown503cffc2015-03-26 18:08:51 -07003323 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003324
John Spurlocke11ae112015-05-11 16:09:03 -04003325 // v119: Reset zen + ringer mode.
3326 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003327 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003328 final SettingsState globalSettings = getGlobalSettingsLocked();
3329 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003330 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3331 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003332 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003333 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3334 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003335 }
3336 currentVersion = 119;
3337 }
3338
Jason Monk27bbb2d2015-03-31 16:46:39 -04003339 // v120: Add double tap to wake setting.
3340 if (currentVersion == 119) {
3341 SettingsState secureSettings = getSecureSettingsLocked(userId);
3342 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3343 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003344 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003345 SettingsState.SYSTEM_PACKAGE_NAME);
3346
3347 currentVersion = 120;
3348 }
3349
Svetoslav7e0683b2015-08-03 16:02:52 -07003350 if (currentVersion == 120) {
3351 // Before 121, we used a different string encoding logic. We just bump the
3352 // version here; SettingsState knows how to handle pre-version 120 files.
3353 currentVersion = 121;
3354 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003355
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003356 if (currentVersion == 121) {
3357 // Version 122: allow OEMs to set a default payment component in resources.
3358 // Note that we only write the default if no default has been set;
3359 // if there is, we just leave the default at whatever it currently is.
3360 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3361 String defaultComponent = (getContext().getResources().getString(
3362 R.string.def_nfc_payment_component));
3363 Setting currentSetting = secureSettings.getSettingLocked(
3364 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3365 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003366 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003367 secureSettings.insertSettingLocked(
3368 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003369 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003370 }
3371 currentVersion = 122;
3372 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003373
3374 if (currentVersion == 122) {
3375 // Version 123: Adding a default value for the ability to add a user from
3376 // the lock screen.
3377 if (userId == UserHandle.USER_SYSTEM) {
3378 final SettingsState globalSettings = getGlobalSettingsLocked();
3379 Setting currentSetting = globalSettings.getSettingLocked(
3380 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003381 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003382 globalSettings.insertSettingLocked(
3383 Settings.Global.ADD_USERS_WHEN_LOCKED,
3384 getContext().getResources().getBoolean(
3385 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003386 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003387 }
3388 }
3389 currentVersion = 123;
3390 }
Bryce Leebd179282015-12-17 19:01:37 -08003391
3392 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003393 final SettingsState globalSettings = getGlobalSettingsLocked();
3394 String defaultDisabledProfiles = (getContext().getResources().getString(
3395 R.string.def_bluetooth_disabled_profiles));
3396 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003397 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003398 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003399 }
3400
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003401 if (currentVersion == 124) {
3402 // Version 124: allow OEMs to set a default value for whether IME should be
3403 // shown when a physical keyboard is connected.
3404 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3405 Setting currentSetting = secureSettings.getSettingLocked(
3406 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003407 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003408 secureSettings.insertSettingLocked(
3409 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3410 getContext().getResources().getBoolean(
3411 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003412 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003413 }
3414 currentVersion = 125;
3415 }
3416
Ruben Brunk98576cf2016-03-07 18:54:28 -08003417 if (currentVersion == 125) {
3418 // Version 125: Allow OEMs to set the default VR service.
3419 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3420
3421 Setting currentSetting = secureSettings.getSettingLocked(
3422 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003423 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003424 ArraySet<ComponentName> l =
3425 SystemConfig.getInstance().getDefaultVrComponents();
3426
3427 if (l != null && !l.isEmpty()) {
3428 StringBuilder b = new StringBuilder();
3429 boolean start = true;
3430 for (ComponentName c : l) {
3431 if (!start) {
3432 b.append(':');
3433 }
3434 b.append(c.flattenToString());
3435 start = false;
3436 }
3437 secureSettings.insertSettingLocked(
3438 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003439 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003440 }
3441
3442 }
3443 currentVersion = 126;
3444 }
3445
Daniel U02ba6122016-04-01 18:41:42 +01003446 if (currentVersion == 126) {
3447 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3448 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3449 if (mUserManager.isManagedProfile(userId)) {
3450 final SettingsState systemSecureSettings =
3451 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3452
3453 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3454 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003455 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003456 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3457 secureSettings.insertSettingLocked(
3458 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003459 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003460 SettingsState.SYSTEM_PACKAGE_NAME);
3461 }
3462
3463 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3464 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003465 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003466 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3467 secureSettings.insertSettingLocked(
3468 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003469 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003470 SettingsState.SYSTEM_PACKAGE_NAME);
3471 }
3472 }
3473 currentVersion = 127;
3474 }
3475
Steven Ngdc20ba62016-04-26 18:19:04 +01003476 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003477 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003478 currentVersion = 128;
3479 }
3480
Julia Reynolds1f721e12016-07-11 08:50:58 -04003481 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003482 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003483 currentVersion = 129;
3484 }
3485
Dan Sandler71f85e92016-07-20 13:46:05 -04003486 if (currentVersion == 129) {
3487 // default longpress timeout changed from 500 to 400. If unchanged from the old
3488 // default, update to the new default.
3489 final SettingsState systemSecureSettings =
3490 getSecureSettingsLocked(userId);
3491 final String oldValue = systemSecureSettings.getSettingLocked(
3492 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3493 if (TextUtils.equals("500", oldValue)) {
3494 systemSecureSettings.insertSettingLocked(
3495 Settings.Secure.LONG_PRESS_TIMEOUT,
3496 String.valueOf(getContext().getResources().getInteger(
3497 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003498 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003499 }
3500 currentVersion = 130;
3501 }
3502
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003503 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003504 // Split Ambient settings
3505 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3506 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3507 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3508
3509 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003510 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003511 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003512 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003513 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003514 }
3515 currentVersion = 131;
3516 }
3517
3518 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003519 // Initialize new multi-press timeout to default value
3520 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3521 final String oldValue = systemSecureSettings.getSettingLocked(
3522 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3523 if (TextUtils.equals(null, oldValue)) {
3524 systemSecureSettings.insertSettingLocked(
3525 Settings.Secure.MULTI_PRESS_TIMEOUT,
3526 String.valueOf(getContext().getResources().getInteger(
3527 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003528 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003529 }
3530
Adrian Roos69741a22016-10-21 14:49:17 -07003531 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003532 }
3533
Adrian Roos69741a22016-10-21 14:49:17 -07003534 if (currentVersion == 132) {
3535 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003536 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3537 String defaultSyncParentSounds = (getContext().getResources()
3538 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3539 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003540 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3541 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003542 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003543 }
3544
Adrian Roos69741a22016-10-21 14:49:17 -07003545 if (currentVersion == 133) {
3546 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003547 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003548 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3549 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003550 String defaultEndButtonBehavior = Integer.toString(getContext()
3551 .getResources().getInteger(R.integer.def_end_button_behavior));
3552 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003553 defaultEndButtonBehavior, null, true,
3554 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003555 }
Adrian Roos69741a22016-10-21 14:49:17 -07003556 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003557 }
3558
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003559 if (currentVersion == 134) {
3560 // Remove setting that specifies if magnification values should be preserved.
3561 // This setting defaulted to true and never has a UI.
3562 getSecureSettingsLocked(userId).deleteSettingLocked(
3563 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3564 currentVersion = 135;
3565 }
3566
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003567 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003568 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003569 currentVersion = 136;
3570 }
3571
Mark Rathjend891f012017-01-19 04:10:37 +00003572 if (currentVersion == 136) {
3573 // Version 136: Store legacy SSAID for all apps currently installed on the
3574 // device as first step in migrating SSAID to be unique per application.
3575
3576 final boolean isUpgrade;
3577 try {
3578 isUpgrade = mPackageManager.isUpgrade();
3579 } catch (RemoteException e) {
3580 throw new IllegalStateException("Package manager not available");
3581 }
3582 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3583 // user data or first boot on a new device should use new ssaid generation.
3584 if (isUpgrade) {
3585 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003586 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3587 userId, Settings.Secure.ANDROID_ID);
3588 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3589 || legacySsaidSetting.getValue() == null) {
3590 throw new IllegalStateException("Legacy ssaid not accessible");
3591 }
3592 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003593
3594 // Fill each uid with the legacy ssaid to be backwards compatible.
3595 final List<PackageInfo> packages;
3596 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003597 packages = mPackageManager.getInstalledPackages(
3598 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3599 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003600 } catch (RemoteException e) {
3601 throw new IllegalStateException("Package manager not available");
3602 }
3603
3604 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3605 for (PackageInfo info : packages) {
3606 // Check if the UID already has an entry in the table.
3607 final String uid = Integer.toString(info.applicationInfo.uid);
3608 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3609
3610 if (ssaid.isNull() || ssaid.getValue() == null) {
3611 // Android Id doesn't exist for this package so create it.
3612 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3613 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003614 if (DEBUG) {
3615 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3616 }
Mark Rathjend891f012017-01-19 04:10:37 +00003617 }
3618 }
3619 }
3620
3621 currentVersion = 137;
3622 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003623 if (currentVersion == 137) {
3624 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3625 // default value set to 1. The user can no longer change the value of this
3626 // setting through the UI.
3627 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3628 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003629 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3630 && secureSetting.getSettingLocked(
3631 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3632
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003633 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3634 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003635 // For managed profiles with profile owners, DevicePolicyManagerService
3636 // may want to set the user restriction in this case
3637 secureSetting.insertSettingLocked(
3638 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3639 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003640 }
3641 currentVersion = 138;
3642 }
Mark Rathjend891f012017-01-19 04:10:37 +00003643
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003644 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003645 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003646 currentVersion = 139;
3647 }
3648
Phil Weaver385912e2017-02-10 10:06:56 -08003649 if (currentVersion == 139) {
3650 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3651 // the user can no longer change the value of this setting through the UI.
3652 // Force to true.
3653 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3654 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3655 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3656 currentVersion = 140;
3657 }
3658
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003659 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003660 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003661 currentVersion = 141;
3662 }
3663
Svet Ganov13701552017-02-23 12:45:17 -08003664 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003665 // This implementation was incorrectly setting the current value of
3666 // settings changed by non-system packages as the default which default
3667 // is set by the system. We add a new upgrade step at the end to properly
3668 // handle this case which would also fix incorrect changes made by the
3669 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003670 currentVersion = 142;
3671 }
3672
Stephen Chen5d0922f2017-03-27 10:28:04 -07003673 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003674 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003675 if (userId == UserHandle.USER_SYSTEM) {
3676 final SettingsState globalSettings = getGlobalSettingsLocked();
3677 Setting currentSetting = globalSettings.getSettingLocked(
3678 Settings.Global.WIFI_WAKEUP_ENABLED);
3679 if (currentSetting.isNull()) {
3680 globalSettings.insertSettingLocked(
3681 Settings.Global.WIFI_WAKEUP_ENABLED,
3682 getContext().getResources().getBoolean(
3683 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3684 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3685 }
3686 }
3687
3688 currentVersion = 143;
3689 }
3690
Felipe Lemeff355092017-04-03 12:55:02 -07003691 if (currentVersion == 143) {
3692 // Version 144: Set a default value for Autofill service.
3693 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3694 final Setting currentSetting = secureSettings
3695 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3696 if (currentSetting.isNull()) {
3697 final String defaultValue = getContext().getResources().getString(
3698 com.android.internal.R.string.config_defaultAutofillService);
3699 if (defaultValue != null) {
3700 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3701 + "for user " + userId);
3702 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3703 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3704 }
3705 }
3706
3707 currentVersion = 144;
3708 }
3709
Jeremy Joslin45caa252017-05-04 11:22:46 -07003710 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003711 // Version 145: Removed
3712 currentVersion = 145;
3713 }
3714
3715 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003716 // Version 146: In step 142 we had a bug where incorrectly
3717 // some settings were considered system set and as a result
3718 // made the default and marked as the default being set by
3719 // the system. Here reevaluate the default and default system
3720 // set flags. This would both fix corruption by the old impl
3721 // of step 142 and also properly handle devices which never
3722 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003723 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003724 SettingsState globalSettings = getGlobalSettingsLocked();
3725 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3726 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003727 }
3728
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003729 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3730 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3731 secureSettings.persistSyncLocked();
3732
3733 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3734 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3735 systemSettings.persistSyncLocked();
3736
Amin Shaikh86367962017-06-07 08:58:22 -07003737 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003738 }
3739
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003740 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003741 // Version 147: Removed. (This version previously allowed showing the
3742 // "wifi_wakeup_available" setting).
3743 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003744 currentVersion = 147;
3745 }
3746
3747 if (currentVersion == 147) {
3748 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003749 if (userId == UserHandle.USER_SYSTEM) {
3750 final SettingsState globalSettings = getGlobalSettingsLocked();
3751 final Setting currentSetting = globalSettings.getSettingLocked(
3752 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3753 if (currentSetting.isNull()) {
3754 globalSettings.insertSettingLocked(
3755 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3756 getContext().getResources().getBoolean(
3757 R.bool.def_restrict_background_data) ? "1" : "0",
3758 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3759 }
3760 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003761 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003762 }
3763
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003764 if (currentVersion == 148) {
3765 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3766 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3767 final String oldValue = systemSecureSettings.getSettingLocked(
3768 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3769 if (TextUtils.equals(null, oldValue)) {
3770 final String defaultValue = getContext().getResources().getString(
3771 R.string.def_backup_manager_constants);
3772 if (!TextUtils.isEmpty(defaultValue)) {
3773 systemSecureSettings.insertSettingLocked(
3774 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3775 true, SettingsState.SYSTEM_PACKAGE_NAME);
3776 }
3777 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003778 currentVersion = 149;
3779 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003780
3781 if (currentVersion == 149) {
3782 // Version 150: Set a default value for mobile data always on
3783 final SettingsState globalSettings = getGlobalSettingsLocked();
3784 final Setting currentSetting = globalSettings.getSettingLocked(
3785 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3786 if (currentSetting.isNull()) {
3787 globalSettings.insertSettingLocked(
3788 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3789 getContext().getResources().getBoolean(
3790 R.bool.def_mobile_data_always_on) ? "1" : "0",
3791 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3792 }
3793
3794 currentVersion = 150;
3795 }
3796
Mike Digman4af4a6f2018-01-16 14:49:38 -08003797 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003798 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003799 currentVersion = 151;
3800 }
3801
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003802 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003803 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3804 // by default but it is now no longer configurable).
3805 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003806 currentVersion = 152;
3807 }
3808
Joe LaPenna250d7842018-01-25 10:19:42 -08003809 if (currentVersion == 152) {
3810 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3811 currentVersion = 153;
3812 }
3813
Ben Linb4df8bc2018-01-29 11:48:20 -08003814 if (currentVersion == 153) {
3815 // Version 154: Read notification badge configuration from config.
3816 // If user has already set the value, don't do anything.
3817 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3818 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3819 Settings.Secure.NOTIFICATION_BADGING);
3820 if (showNotificationBadges.isNull()) {
3821 final boolean defaultValue = getContext().getResources().getBoolean(
3822 com.android.internal.R.bool.config_notificationBadging);
3823 systemSecureSettings.insertSettingLocked(
3824 Secure.NOTIFICATION_BADGING,
3825 defaultValue ? "1" : "0",
3826 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3827 }
3828 currentVersion = 154;
3829 }
3830
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003831 if (currentVersion == 154) {
3832 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3833 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3834 final String oldValue = systemSecureSettings.getSettingLocked(
3835 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3836 if (TextUtils.equals(null, oldValue)) {
3837 final String defaultValue = getContext().getResources().getString(
3838 R.string.def_backup_local_transport_parameters);
3839 if (!TextUtils.isEmpty(defaultValue)) {
3840 systemSecureSettings.insertSettingLocked(
3841 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3842 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3843 }
3844
3845 }
3846 currentVersion = 155;
3847 }
3848
Beverlyda904812018-03-02 09:55:30 -05003849 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003850 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003851 final SettingsState globalSettings = getGlobalSettingsLocked();
3852 final String oldValue = globalSettings.getSettingLocked(
3853 Global.CHARGING_STARTED_SOUND).getValue();
3854 final String oldDefault = getContext().getResources().getString(
3855 R.string.def_wireless_charging_started_sound);
3856 if (TextUtils.equals(null, oldValue)
3857 || TextUtils.equals(oldValue, oldDefault)) {
3858 final String defaultValue = getContext().getResources().getString(
3859 R.string.def_charging_started_sound);
3860 if (!TextUtils.isEmpty(defaultValue)) {
3861 globalSettings.insertSettingLocked(
3862 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3863 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3864 }
3865
3866 }
3867 currentVersion = 156;
3868 }
3869
Beverly09da25f2018-02-26 09:17:07 -05003870 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003871 // Version 157: Set a default value for zen duration,
3872 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003873 final SettingsState globalSettings = getGlobalSettingsLocked();
3874 final Setting currentSetting = globalSettings.getSettingLocked(
3875 Global.ZEN_DURATION);
3876 if (currentSetting.isNull()) {
3877 String defaultZenDuration = Integer.toString(getContext()
3878 .getResources().getInteger(R.integer.def_zen_duration));
3879 globalSettings.insertSettingLocked(
3880 Global.ZEN_DURATION, defaultZenDuration,
3881 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3882 }
Beverly09da25f2018-02-26 09:17:07 -05003883 currentVersion = 157;
3884 }
Annie Mengd069a882018-03-13 15:31:40 +00003885
3886 if (currentVersion == 157) {
3887 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3888 final SettingsState globalSettings = getGlobalSettingsLocked();
3889 final String oldValue = globalSettings.getSettingLocked(
3890 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3891 if (TextUtils.equals(null, oldValue)) {
3892 final String defaultValue = getContext().getResources().getString(
3893 R.string.def_backup_agent_timeout_parameters);
3894 if (!TextUtils.isEmpty(defaultValue)) {
3895 globalSettings.insertSettingLocked(
3896 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3897 null, true,
3898 SettingsState.SYSTEM_PACKAGE_NAME);
3899 }
3900 }
3901 currentVersion = 158;
3902 }
Roshan Pius9c396672018-03-02 14:54:13 -08003903
3904 if (currentVersion == 158) {
3905 // Remove setting that specifies wifi bgscan throttling params
3906 getGlobalSettingsLocked().deleteSettingLocked(
3907 "wifi_scan_background_throttle_interval_ms");
3908 getGlobalSettingsLocked().deleteSettingLocked(
3909 "wifi_scan_background_throttle_package_whitelist");
3910 currentVersion = 159;
3911 }
3912
Pavel Grafovc5c97302018-03-19 13:37:15 +00003913 if (currentVersion == 159) {
3914 // Version 160: Hiding notifications from the lockscreen is only available as
3915 // primary user option, profiles can only make them redacted. If a profile was
3916 // configured to not show lockscreen notifications, ensure that at the very
3917 // least these will be come hidden.
3918 if (mUserManager.isManagedProfile(userId)) {
3919 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3920 Setting showNotifications = secureSettings.getSettingLocked(
3921 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3922 // The default value is "1", check if user has turned it off.
3923 if ("0".equals(showNotifications.getValue())) {
3924 secureSettings.insertSettingLocked(
3925 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3926 null /* tag */, false /* makeDefault */,
3927 SettingsState.SYSTEM_PACKAGE_NAME);
3928 }
3929 // The setting is no longer valid for managed profiles, it should be
3930 // treated as if it was set to "1".
3931 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3932 }
3933 currentVersion = 160;
3934 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003935
3936 if (currentVersion == 160) {
3937 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003938 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003939 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3940 final SettingsState globalSettings = getGlobalSettingsLocked();
3941
3942 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003943 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3944 if (TextUtils.equals(null, oldValue)) {
3945 globalSettings.insertSettingLocked(
3946 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3947 Integer.toString(getContext().getResources().getInteger(
3948 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3949 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3950 }
3951
3952 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003953 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3954 if (TextUtils.equals(null, oldValue)) {
3955 globalSettings.insertSettingLocked(
3956 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3957 Integer.toString(getContext().getResources().getInteger(
3958 R.integer.def_sound_trigger_detection_service_op_timeout)),
3959 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3960 }
3961 currentVersion = 161;
3962 }
3963
Mike Digman55272862018-02-20 14:35:17 -08003964 if (currentVersion == 161) {
3965 // Version 161: Add a gesture for silencing phones
3966 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3967 final Setting currentSetting = secureSettings.getSettingLocked(
3968 Secure.VOLUME_HUSH_GESTURE);
3969 if (currentSetting.isNull()) {
3970 secureSettings.insertSettingLocked(
3971 Secure.VOLUME_HUSH_GESTURE,
3972 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3973 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3974 }
3975
3976 currentVersion = 162;
3977 }
3978
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003979 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003980 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003981 currentVersion = 163;
3982 }
3983
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003984 if (currentVersion == 163) {
3985 // Version 163: Update default value of
3986 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3987 final SettingsState settings = getGlobalSettingsLocked();
3988 final Setting currentSetting = settings.getSettingLocked(
3989 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3990 if (currentSetting.isDefaultFromSystem()) {
3991 settings.insertSettingLocked(
3992 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3993 Integer.toString(getContext().getResources().getInteger(
3994 R.integer
3995 .def_max_sound_trigger_detection_service_ops_per_day)),
3996 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3997 }
3998
3999 currentVersion = 164;
4000 }
4001
Julia Reynolds76bfa602018-04-23 09:38:47 -04004002 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004003 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004004 currentVersion = 165;
4005 }
4006
Beverly301e92a2018-04-27 09:43:05 -04004007 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004008 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4009 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004010 currentVersion = 166;
4011 }
4012
Beverly38fcfd02018-05-18 17:33:40 -04004013 if (currentVersion == 166) {
4014 // Version 166: add default values for hush gesture used and manual ringer
4015 // toggle
4016 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4017 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4018 Secure.HUSH_GESTURE_USED);
4019 if (currentHushUsedSetting.isNull()) {
4020 secureSettings.insertSettingLocked(
4021 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4022 SettingsState.SYSTEM_PACKAGE_NAME);
4023 }
4024
4025 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4026 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4027 if (currentRingerToggleCountSetting.isNull()) {
4028 secureSettings.insertSettingLocked(
4029 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4030 SettingsState.SYSTEM_PACKAGE_NAME);
4031 }
4032 currentVersion = 167;
4033 }
4034
Beverly155c9d22018-05-23 18:03:23 -04004035 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004036 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4037 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004038 currentVersion = 168;
4039 }
4040
Michael Wright0e9eeee2018-05-26 00:31:20 +01004041 if (currentVersion == 168) {
4042 // Version 168: by default, vibrate for phone calls
4043 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4044 final Setting currentSetting = systemSettings.getSettingLocked(
4045 Settings.System.VIBRATE_WHEN_RINGING);
4046 if (currentSetting.isNull()) {
4047 systemSettings.insertSettingLocked(
4048 Settings.System.VIBRATE_WHEN_RINGING,
4049 getContext().getResources().getBoolean(
4050 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4051 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4052 }
4053 currentVersion = 169;
4054 }
4055
Nadav Barf9f115d2018-06-24 10:06:50 +03004056 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004057 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4058 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4059 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004060
Beverly91d0a632018-07-02 16:45:00 -04004061 final SettingsState globalSettings = getGlobalSettingsLocked();
4062 final Setting globalZenDuration = globalSettings.getSettingLocked(
4063 Global.ZEN_DURATION);
4064
4065 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4066 final Setting secureZenDuration = secureSettings.getSettingLocked(
4067 Secure.ZEN_DURATION);
4068
4069 // ZEN_DURATION
4070 if (!globalZenDuration.isNull()) {
4071 secureSettings.insertSettingLocked(
4072 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4073 SettingsState.SYSTEM_PACKAGE_NAME);
4074
4075 // set global zen duration setting to null since it's deprecated
4076 globalSettings.insertSettingLocked(
4077 Global.ZEN_DURATION, null, null, true,
4078 SettingsState.SYSTEM_PACKAGE_NAME);
4079 } else if (secureZenDuration.isNull()) {
4080 String defaultZenDuration = Integer.toString(getContext()
4081 .getResources().getInteger(R.integer.def_zen_duration));
4082 secureSettings.insertSettingLocked(
4083 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4084 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004085 }
Beverly91d0a632018-07-02 16:45:00 -04004086
4087 // SHOW_ZEN_SETTINGS_SUGGESTION
4088 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4089 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4090 if (currentShowZenSettingSuggestion.isNull()) {
4091 secureSettings.insertSettingLocked(
4092 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4093 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4094 }
4095
4096 // ZEN_SETTINGS_UPDATED
4097 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4098 Secure.ZEN_SETTINGS_UPDATED);
4099 if (currentUpdatedSetting.isNull()) {
4100 secureSettings.insertSettingLocked(
4101 Secure.ZEN_SETTINGS_UPDATED, "0",
4102 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4103 }
4104
4105 // ZEN_SETTINGS_SUGGESTION_VIEWED
4106 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4107 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4108 if (currentSettingSuggestionViewed.isNull()) {
4109 secureSettings.insertSettingLocked(
4110 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4111 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4112 }
4113
Nadav Barf9f115d2018-06-24 10:06:50 +03004114 currentVersion = 170;
4115 }
4116
Beverly91d0a632018-07-02 16:45:00 -04004117 if (currentVersion == 170) {
4118 // Version 170: Set the default value for Secure Settings:
4119 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4120
4121 final SettingsState globalSettings = getGlobalSettingsLocked();
4122 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4123
4124 // CHARGING_SOUNDS_ENABLED
4125 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4126 Global.CHARGING_SOUNDS_ENABLED);
4127 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4128 Secure.CHARGING_SOUNDS_ENABLED);
4129
4130 if (!globalChargingSoundEnabled.isNull()) {
4131 secureSettings.insertSettingLocked(
4132 Secure.CHARGING_SOUNDS_ENABLED,
4133 globalChargingSoundEnabled.getValue(), null, false,
4134 SettingsState.SYSTEM_PACKAGE_NAME);
4135
4136 // set global charging_sounds_enabled setting to null since it's deprecated
4137 globalSettings.insertSettingLocked(
4138 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4139 SettingsState.SYSTEM_PACKAGE_NAME);
4140 } else if (secureChargingSoundsEnabled.isNull()) {
4141 String defChargingSoundsEnabled = getContext().getResources()
4142 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4143 secureSettings.insertSettingLocked(
4144 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4145 true, SettingsState.SYSTEM_PACKAGE_NAME);
4146 }
4147
4148 // CHARGING_VIBRATION_ENABLED
4149 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4150 Secure.CHARGING_VIBRATION_ENABLED);
4151
4152 if (secureChargingVibrationEnabled.isNull()) {
4153 String defChargingVibrationEnabled = getContext().getResources()
4154 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4155 secureSettings.insertSettingLocked(
4156 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4157 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4158 }
4159
4160 currentVersion = 171;
4161 }
4162
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004163 if (currentVersion == 171) {
4164 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4165 // be muted.
4166 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4167 final Setting currentSetting = systemSettings.getSettingLocked(
4168 Settings.System.MUTE_STREAMS_AFFECTED);
4169 if (!currentSetting.isNull()) {
4170 try {
4171 int currentSettingIntegerValue = Integer.parseInt(
4172 currentSetting.getValue());
4173 if ((currentSettingIntegerValue
4174 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4175 systemSettings.insertSettingLocked(
4176 Settings.System.MUTE_STREAMS_AFFECTED,
4177 Integer.toString(
4178 currentSettingIntegerValue
4179 | (1 << AudioManager.STREAM_VOICE_CALL)),
4180 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4181 }
4182 } catch (NumberFormatException e) {
4183 // remove the setting in case it is not a valid integer
4184 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4185 + "setting, removing setting", e);
4186 systemSettings.deleteSettingLocked(
4187 Settings.System.MUTE_STREAMS_AFFECTED);
4188 }
4189
4190 }
4191 currentVersion = 172;
4192 }
4193
Felipe Lemeff355092017-04-03 12:55:02 -07004194 // vXXX: Add new settings above this point.
4195
Dan Sandler71f85e92016-07-20 13:46:05 -04004196 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004197 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004198 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004199 + currentVersion +
4200 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4201 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004202 if (DEBUG) {
4203 throw new RuntimeException("db upgrade error");
4204 }
4205 }
4206
Jeff Brown503cffc2015-03-26 18:08:51 -07004207 // Return the current version.
4208 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004209 }
4210 }
Svet Ganov13701552017-02-23 12:45:17 -08004211
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004212 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4213 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004214 List<String> names = settings.getSettingNamesLocked();
4215 final int nameCount = names.size();
4216 for (int i = 0; i < nameCount; i++) {
4217 String name = names.get(i);
4218 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004219
4220 // In the upgrade case we pretend the call is made from the app
4221 // that made the last change to the setting to properly determine
4222 // whether the call has been made by a system component.
4223 int callingUid = -1;
4224 try {
4225 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4226 } catch (RemoteException e) {
4227 /* ignore - handled below */
4228 }
4229 if (callingUid < 0) {
4230 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4231 continue;
4232 }
4233 try {
4234 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4235 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004236 if (systemSet) {
4237 settings.insertSettingLocked(name, setting.getValue(),
4238 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004239 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4240 // We had a bug where changes by non-system packages were marked
4241 // as system made and as a result set as the default. Therefore, if
4242 // the package changed the setting last is not a system one but the
4243 // setting is marked as its default coming from the system we clear
4244 // the default and clear the system set flag.
4245 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004246 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004247 } catch (IllegalStateException e) {
4248 // If the package goes over its quota during the upgrade, don't
4249 // crash but just log the error as the system does the upgrade.
4250 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4251
Svet Ganov13701552017-02-23 12:45:17 -08004252 }
4253 }
4254 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004255 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004256}