blob: b071355986f5205928ec3bca54c678191552eb99 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010067import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080068import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000069import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010071import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080072import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000073import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070076import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080077import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import com.android.internal.annotations.GuardedBy;
80import com.android.internal.content.PackageMonitor;
81import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080082import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070083import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080084import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040085
Svetoslav683914b2015-01-15 14:22:26 -080086import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080087import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080089import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080090import java.nio.ByteBuffer;
91import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070094import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000096import java.util.Collection;
Matt Pape6bfc62e2018-11-28 13:16:03 -080097import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +000098import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080099import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -0800100import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100101import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800102import java.util.Set;
103import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000104
Mark Rathjen7599f132017-01-23 14:15:54 -0800105import javax.crypto.Mac;
106import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700107
Svetoslav Ganove080da92016-12-21 17:10:35 -0800108
Svetoslav683914b2015-01-15 14:22:26 -0800109/**
110 * <p>
111 * This class is a content provider that publishes the system settings.
112 * It can be accessed via the content provider APIs or via custom call
113 * commands. The latter is a bit faster and is the preferred way to access
114 * the platform settings.
115 * </p>
116 * <p>
117 * There are three settings types, global (with signature level protection
118 * and shared across users), secure (with signature permission level
119 * protection and per user), and system (with dangerous permission level
120 * protection and per user). Global settings are stored under the device owner.
121 * Each of these settings is represented by a {@link
122 * com.android.providers.settings.SettingsState} object mapped to an integer
123 * key derived from the setting type in the most significant bits and user
124 * id in the least significant bits. Settings are synchronously loaded on
125 * instantiation of a SettingsState and asynchronously persisted on mutation.
126 * Settings are stored in the user specific system directory.
127 * </p>
128 * <p>
129 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
130 * and get a warning. Targeting higher API version prohibits this as the
131 * system settings are not a place for apps to save their state. When a package
132 * is removed the settings it added are deleted. Apps cannot delete system
133 * settings added by the platform. System settings values are validated to
134 * ensure the clients do not put bad values. Global and secure settings are
135 * changed only by trusted parties, therefore no validation is performed. Also
136 * there is a limit on the amount of app specific settings that can be added
137 * to prevent unlimited growth of the system process memory footprint.
138 * </p>
139 */
140@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700142 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700144 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800145
146 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700147
Christopher Tate06efb532012-08-24 15:29:27 -0700148 private static final String TABLE_SYSTEM = "system";
149 private static final String TABLE_SECURE = "secure";
150 private static final String TABLE_GLOBAL = "global";
Matt Pape6bfc62e2018-11-28 13:16:03 -0800151 private static final String TABLE_CONFIG = "config";
Svetoslav683914b2015-01-15 14:22:26 -0800152
153 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 private static final String TABLE_FAVORITES = "favorites";
155 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800156 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
157 private static final String TABLE_BOOKMARKS = "bookmarks";
158 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Svetoslav683914b2015-01-15 14:22:26 -0800160 // The set of removed legacy tables.
161 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700162 static {
Svetoslav683914b2015-01-15 14:22:26 -0800163 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
164 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
165 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
166 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
167 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
168 }
Christopher Tate06efb532012-08-24 15:29:27 -0700169
Svetoslav683914b2015-01-15 14:22:26 -0800170 private static final int MUTATION_OPERATION_INSERT = 1;
171 private static final int MUTATION_OPERATION_DELETE = 2;
172 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800173 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400174
Svetoslav683914b2015-01-15 14:22:26 -0800175 private static final String[] ALL_COLUMNS = new String[] {
176 Settings.NameValueTable._ID,
177 Settings.NameValueTable.NAME,
178 Settings.NameValueTable.VALUE
179 };
180
Makoto Onuki53f0e022017-11-29 13:51:01 -0800181 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
182 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
183 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
184 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700185 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700186
187 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
188 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700189
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800190 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800191 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800192
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700193 // Overlay specified settings whitelisted for Instant Apps
194 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
195 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
196 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
197
Matt Pape1b31a332018-10-17 09:58:28 -0700198 /**
199 * TODO(b/113100523): Move this to DeviceConfig.java when it is added, and expose it as a System
200 * API.
201 */
202 private static final Uri CONFIG_CONTENT_URI =
203 Uri.parse("content://" + Settings.AUTHORITY + "/config");
204
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700205 static {
206 for (String name : Resources.getSystem().getStringArray(
207 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
208 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
209 }
210 for (String name : Resources.getSystem().getStringArray(
211 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
212 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
213 }
214 for (String name : Resources.getSystem().getStringArray(
215 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
216 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
217 }
218 }
219
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800220 // Changes to these global settings are synchronously persisted
221 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
222 static {
223 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
224 }
225
226 // Changes to these secure settings are synchronously persisted
227 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
228 static {
229 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
230 }
231
Svetoslav683914b2015-01-15 14:22:26 -0800232 // Per user secure settings that moved to the for all users global settings.
233 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
234 static {
235 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700236 }
237
Svetoslav683914b2015-01-15 14:22:26 -0800238 // Per user system settings that moved to the for all users global settings.
239 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
240 static {
241 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 }
243
Svetoslav683914b2015-01-15 14:22:26 -0800244 // Per user system settings that moved to the per user secure settings.
245 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
246 static {
247 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 }
249
Svetoslav683914b2015-01-15 14:22:26 -0800250 // Per all users global settings that moved to the per user secure settings.
251 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
252 static {
253 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700254 }
255
Svetoslav683914b2015-01-15 14:22:26 -0800256 // Per user secure settings that are cloned for the managed profiles of the user.
257 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
258 static {
259 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 }
261
Svetoslav683914b2015-01-15 14:22:26 -0800262 // Per user system settings that are cloned for the managed profiles of the user.
263 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
264 static {
265 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400266 }
267
Andre Lago3fa139c2016-08-04 13:53:44 +0100268 // Per user system settings that are cloned from the profile's parent when a dependency
269 // in {@link Settings.Secure} is set to "1".
270 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
271 static {
272 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
273 }
274
Svetoslav683914b2015-01-15 14:22:26 -0800275 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700276
Svetoslav683914b2015-01-15 14:22:26 -0800277 @GuardedBy("mLock")
278 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700279
Svet Ganova8f90262016-05-10 08:44:48 -0700280 @GuardedBy("mLock")
281 private HandlerThread mHandlerThread;
282
Makoto Onuki73360ab2017-03-17 11:50:13 -0700283 @GuardedBy("mLock")
284 private Handler mHandler;
285
Svetoslav7ec28e82015-05-20 17:01:10 -0700286 // We have to call in the user manager with no lock held,
287 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800288
yuemingw1d13eae2018-01-30 17:27:54 +0000289 private UserManagerInternal mUserManagerInternal;
290
Svetoslav7ec28e82015-05-20 17:01:10 -0700291 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700292 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700293
Svet Ganov53a441c2016-04-19 19:38:00 -0700294 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800295 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700296 }
297
298 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800299 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700300 }
301
302 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800303 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 }
305
306 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800307 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700308 }
309
310 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800311 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700312 }
313
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 @Override
315 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800316 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000317
318 // fail to boot if there're any backed up settings that don't have a non-null validator
319 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000320 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000321 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000322
Svetoslav683914b2015-01-15 14:22:26 -0800323 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700324 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000325 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700326 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700327 mHandlerThread = new HandlerThread(LOG_TAG,
328 Process.THREAD_PRIORITY_BACKGROUND);
329 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700330 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800331 mSettingsRegistry = new SettingsRegistry();
332 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700333 mHandler.post(() -> {
334 registerBroadcastReceivers();
335 startWatchingUserRestrictionChanges();
336 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700337 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800338 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700339 return true;
340 }
341
Michal Karpinski2c37b082018-01-18 16:14:27 +0000342 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000343 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
344 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000345
346 failToBootIfOffendersPresent(offenders, "Settings.System");
347 }
348
349 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000350 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
351 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000352
353 failToBootIfOffendersPresent(offenders, "Settings.Global");
354 }
355
Michal Karpinski964943a2018-01-19 16:28:26 +0000356 private void ensureAllBackedUpSecureSettingsHaveValidators() {
357 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
358 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
359
360 failToBootIfOffendersPresent(offenders, "Settings.Secure");
361 }
362
Michal Karpinski5db1e432018-01-18 20:10:24 +0000363 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
364 if (offenders.length() > 0) {
365 throw new RuntimeException("All " + settingsType + " settings that are backed up"
366 + " have to have a non-null validator, but those don't: " + offenders);
367 }
368 }
369
370 private String getOffenders(String[] settingsToBackup, Map<String,
371 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000372 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000373 for (String setting : settingsToBackup) {
374 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000375 offenders.append(setting).append(" ");
376 }
377 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000378 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000379 }
380
Michal Karpinski964943a2018-01-19 16:28:26 +0000381 private final String[] concat(String[] first, String[] second) {
382 if (second == null || second.length == 0) {
383 return first;
384 }
385 final int firstLen = first.length;
386 final int secondLen = second.length;
387 String[] both = new String[firstLen + secondLen];
388 System.arraycopy(first, 0, both, 0, firstLen);
389 System.arraycopy(second, 0, both, firstLen, secondLen);
390 return both;
391 }
392
Svetoslav683914b2015-01-15 14:22:26 -0800393 @Override
394 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700395 final int requestingUserId = getRequestingUserId(args);
396 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700397 case Settings.CALL_METHOD_GET_CONFIG: {
398 Setting setting = getConfigSetting(name);
399 return packageValueForCallResult(setting, isTrackingGeneration(args));
400 }
401
Svetoslav7ec28e82015-05-20 17:01:10 -0700402 case Settings.CALL_METHOD_GET_GLOBAL: {
403 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700404 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800405 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700406
407 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800408 Setting setting = getSecureSetting(name, requestingUserId,
409 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700410 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700411 }
412
413 case Settings.CALL_METHOD_GET_SYSTEM: {
414 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700415 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700416 }
417
Matt Pape1b31a332018-10-17 09:58:28 -0700418 case Settings.CALL_METHOD_PUT_CONFIG: {
419 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700420 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800421 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700422 break;
423 }
424
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 case Settings.CALL_METHOD_PUT_GLOBAL: {
426 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800427 String tag = getSettingTag(args);
428 final boolean makeDefault = getSettingMakeDefault(args);
429 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700430 break;
431 }
432
433 case Settings.CALL_METHOD_PUT_SECURE: {
434 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800435 String tag = getSettingTag(args);
436 final boolean makeDefault = getSettingMakeDefault(args);
437 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700438 break;
439 }
440
441 case Settings.CALL_METHOD_PUT_SYSTEM: {
442 String value = getSettingValue(args);
443 insertSystemSetting(name, value, requestingUserId);
444 break;
445 }
446
Matt Pape1b31a332018-10-17 09:58:28 -0700447 case Settings.CALL_METHOD_RESET_CONFIG: {
448 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800449 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800450 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700451 break;
452 }
453
Svetoslav Ganove080da92016-12-21 17:10:35 -0800454 case Settings.CALL_METHOD_RESET_GLOBAL: {
455 final int mode = getResetModeEnforcingPermission(args);
456 String tag = getSettingTag(args);
457 resetGlobalSetting(requestingUserId, mode, tag);
458 break;
459 }
460
461 case Settings.CALL_METHOD_RESET_SECURE: {
462 final int mode = getResetModeEnforcingPermission(args);
463 String tag = getSettingTag(args);
464 resetSecureSetting(requestingUserId, mode, tag);
465 break;
466 }
467
Matt Pape6bfc62e2018-11-28 13:16:03 -0800468 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800469 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800470 Bundle result = new Bundle();
471 result.putInt(RESULT_ROWS_DELETED, rows);
472 return result;
473 }
474
475 case Settings.CALL_METHOD_DELETE_GLOBAL: {
476 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
477 Bundle result = new Bundle();
478 result.putInt(RESULT_ROWS_DELETED, rows);
479 return result;
480 }
481
Matt Pape6bfc62e2018-11-28 13:16:03 -0800482 case Settings.CALL_METHOD_DELETE_SECURE: {
483 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
484 Bundle result = new Bundle();
485 result.putInt(RESULT_ROWS_DELETED, rows);
486 return result;
487 }
488
489 case Settings.CALL_METHOD_DELETE_SYSTEM: {
490 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
491 Bundle result = new Bundle();
492 result.putInt(RESULT_ROWS_DELETED, rows);
493 return result;
494 }
495
496 case Settings.CALL_METHOD_LIST_CONFIG: {
497 String prefix = getSettingPrefix(args);
498 Bundle result = new Bundle();
499 result.putSerializable(
500 Settings.NameValueTable.VALUE, (HashMap) getAllConfigFlags(prefix));
501 return result;
502 }
503
504 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800505 Bundle result = new Bundle();
506 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800507 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800508 return result;
509 }
510
511 case Settings.CALL_METHOD_LIST_SECURE: {
512 Bundle result = new Bundle();
513 result.putStringArrayList(RESULT_SETTINGS_LIST,
514 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
515 return result;
516 }
517
Matt Pape6bfc62e2018-11-28 13:16:03 -0800518 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800519 Bundle result = new Bundle();
520 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800521 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800522 return result;
523 }
524
Svetoslav7ec28e82015-05-20 17:01:10 -0700525 default: {
526 Slog.w(LOG_TAG, "call() with invalid method: " + method);
527 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700528 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700529
Christopher Tate06efb532012-08-24 15:29:27 -0700530 return null;
531 }
532
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800533 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800534 public String getType(Uri uri) {
535 Arguments args = new Arguments(uri, null, null, true);
536 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700537 return "vnd.android.cursor.dir/" + args.table;
538 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700539 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700540 }
541 }
542
543 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800544 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
545 String order) {
546 if (DEBUG) {
547 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700548 }
549
Svetoslav683914b2015-01-15 14:22:26 -0800550 Arguments args = new Arguments(uri, where, whereArgs, true);
551 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552
Svetoslav683914b2015-01-15 14:22:26 -0800553 // If a legacy table that is gone, done.
554 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
555 return new MatrixCursor(normalizedProjection, 0);
556 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700557
Svetoslav7ec28e82015-05-20 17:01:10 -0700558 switch (args.table) {
559 case TABLE_GLOBAL: {
560 if (args.name != null) {
561 Setting setting = getGlobalSetting(args.name);
562 return packageSettingForQuery(setting, normalizedProjection);
563 } else {
564 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700565 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700566 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700567
Svetoslav7ec28e82015-05-20 17:01:10 -0700568 case TABLE_SECURE: {
569 final int userId = UserHandle.getCallingUserId();
570 if (args.name != null) {
571 Setting setting = getSecureSetting(args.name, userId);
572 return packageSettingForQuery(setting, normalizedProjection);
573 } else {
574 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800575 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700576 }
Svetoslav683914b2015-01-15 14:22:26 -0800577
Svetoslav7ec28e82015-05-20 17:01:10 -0700578 case TABLE_SYSTEM: {
579 final int userId = UserHandle.getCallingUserId();
580 if (args.name != null) {
581 Setting setting = getSystemSetting(args.name, userId);
582 return packageSettingForQuery(setting, normalizedProjection);
583 } else {
584 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800585 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700586 }
Svetoslav683914b2015-01-15 14:22:26 -0800587
Svetoslav7ec28e82015-05-20 17:01:10 -0700588 default: {
589 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700590 }
591 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700592 }
593
Nicholas Sauer72500532018-11-21 10:30:58 -0800594 private ArrayList<String> buildSettingsList(Cursor cursor) {
595 final ArrayList<String> lines = new ArrayList<String>();
596 try {
597 while (cursor != null && cursor.moveToNext()) {
598 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
599 }
600 } finally {
601 if (cursor != null) {
602 cursor.close();
603 }
604 }
605 return lines;
606 }
607
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700608 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800609 public Uri insert(Uri uri, ContentValues values) {
610 if (DEBUG) {
611 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700612 }
613
Svetoslav683914b2015-01-15 14:22:26 -0800614 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700615
Svetoslav683914b2015-01-15 14:22:26 -0800616 // If a legacy table that is gone, done.
617 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 return null;
619 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700620
Svetoslav683914b2015-01-15 14:22:26 -0800621 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700622 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800623 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700624 }
625
Svetoslav683914b2015-01-15 14:22:26 -0800626 String value = values.getAsString(Settings.Secure.VALUE);
627
Svetoslav7ec28e82015-05-20 17:01:10 -0700628 switch (table) {
629 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800630 if (insertGlobalSetting(name, value, null, false,
631 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700632 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700633 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700634 } break;
635
636 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800637 if (insertSecureSetting(name, value, null, false,
638 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700639 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
640 }
641 } break;
642
643 case TABLE_SYSTEM: {
644 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
645 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
646 }
647 } break;
648
649 default: {
650 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700651 }
652 }
653
Svetoslav683914b2015-01-15 14:22:26 -0800654 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700655 }
656
657 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800658 public int bulkInsert(Uri uri, ContentValues[] allValues) {
659 if (DEBUG) {
660 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700662
Svetoslav683914b2015-01-15 14:22:26 -0800663 int insertionCount = 0;
664 final int valuesCount = allValues.length;
665 for (int i = 0; i < valuesCount; i++) {
666 ContentValues values = allValues[i];
667 if (insert(uri, values) != null) {
668 insertionCount++;
669 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700670 }
Svetoslav683914b2015-01-15 14:22:26 -0800671
672 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700673 }
674
675 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800676 public int delete(Uri uri, String where, String[] whereArgs) {
677 if (DEBUG) {
678 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700680
Svetoslav683914b2015-01-15 14:22:26 -0800681 Arguments args = new Arguments(uri, where, whereArgs, false);
682
683 // If a legacy table that is gone, done.
684 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
685 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700686 }
Svetoslav683914b2015-01-15 14:22:26 -0800687
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700688 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800689 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700690 }
Svetoslav683914b2015-01-15 14:22:26 -0800691
Svetoslav7ec28e82015-05-20 17:01:10 -0700692 switch (args.table) {
693 case TABLE_GLOBAL: {
694 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700695 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700696 }
Svetoslav683914b2015-01-15 14:22:26 -0800697
Svetoslav7ec28e82015-05-20 17:01:10 -0700698 case TABLE_SECURE: {
699 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700700 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700701 }
Svetoslav683914b2015-01-15 14:22:26 -0800702
Svetoslav7ec28e82015-05-20 17:01:10 -0700703 case TABLE_SYSTEM: {
704 final int userId = UserHandle.getCallingUserId();
705 return deleteSystemSetting(args.name, userId) ? 1 : 0;
706 }
707
708 default: {
709 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800710 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700711 }
Svetoslav683914b2015-01-15 14:22:26 -0800712 }
713
714 @Override
715 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
716 if (DEBUG) {
717 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700718 }
Svetoslav683914b2015-01-15 14:22:26 -0800719
720 Arguments args = new Arguments(uri, where, whereArgs, false);
721
722 // If a legacy table that is gone, done.
723 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
724 return 0;
725 }
726
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700727 String name = values.getAsString(Settings.Secure.NAME);
728 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800729 return 0;
730 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700731 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800732
Svetoslav7ec28e82015-05-20 17:01:10 -0700733 switch (args.table) {
734 case TABLE_GLOBAL: {
735 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800736 return updateGlobalSetting(args.name, value, null, false,
737 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700738 }
Svetoslav683914b2015-01-15 14:22:26 -0800739
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 case TABLE_SECURE: {
741 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800742 return updateSecureSetting(args.name, value, null, false,
743 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700744 }
Svetoslav683914b2015-01-15 14:22:26 -0800745
Svetoslav7ec28e82015-05-20 17:01:10 -0700746 case TABLE_SYSTEM: {
747 final int userId = UserHandle.getCallingUserId();
748 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
749 }
Svetoslav683914b2015-01-15 14:22:26 -0800750
Svetoslav7ec28e82015-05-20 17:01:10 -0700751 default: {
752 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800753 }
754 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700755 }
756
757 @Override
758 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100759 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
760 if (userId != UserHandle.getCallingUserId()) {
761 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
762 "Access files from the settings of another user");
763 }
764 uri = ContentProvider.getUriWithoutUserId(uri);
765
Andre Lago3fa139c2016-08-04 13:53:44 +0100766 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700767 final String cacheName;
768 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100769 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700770 cacheName = Settings.System.RINGTONE_CACHE;
771 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100772 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700773 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
774 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100775 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700776 cacheName = Settings.System.ALARM_ALERT_CACHE;
777 } else {
778 throw new FileNotFoundException("Direct file access no longer supported; "
779 + "ringtone playback is available through android.media.Ringtone");
780 }
781
Andre Lago3fa139c2016-08-04 13:53:44 +0100782 int actualCacheOwner;
783 // Redirect cache to parent if ringtone setting is owned by profile parent
784 synchronized (mLock) {
785 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
786 cacheRingtoneSetting);
787 }
788 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700789 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
790 }
791
792 private File getRingtoneCacheDir(int userId) {
793 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
794 cacheDir.mkdir();
795 SELinux.restorecon(cacheDir);
796 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700797 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800798
Eugene Suslad72c3972016-12-27 15:49:30 -0800799 /**
800 * Dump all settings as a proto buf.
801 *
802 * @param fd The file to dump to
803 */
804 void dumpProto(@NonNull FileDescriptor fd) {
805 ProtoOutputStream proto = new ProtoOutputStream(fd);
806
807 synchronized (mLock) {
808 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800809 }
810
811 proto.flush();
812 }
813
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700814 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800815 synchronized (mLock) {
816 final long identity = Binder.clearCallingIdentity();
817 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700818 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800819 final int userCount = users.size();
820 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700821 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800822 }
823 } finally {
824 Binder.restoreCallingIdentity(identity);
825 }
826 }
827 }
828
Andreas Gampeb58893072018-09-05 16:52:31 -0700829 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700830 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700831 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700832 pw.println("CONFIG SETTINGS (user " + userId + ")");
833 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
834 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
835 if (configSettings != null) {
836 dumpSettingsLocked(configSettings, pw);
837 pw.println();
838 configSettings.dumpHistoricalOperations(pw);
839 }
840
Svetoslavb505ccc2015-02-17 12:41:04 -0800841 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700842 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
843 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700844 if (globalSettings != null) {
845 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800846 pw.println();
847 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700848 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800849 }
850
851 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700852 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
853 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700854 if (secureSettings != null) {
855 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 pw.println();
857 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700858 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700859
Svetoslavb505ccc2015-02-17 12:41:04 -0800860 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700861 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
862 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700863 if (systemSettings != null) {
864 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800865 pw.println();
866 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700867 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800868 }
869
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700870 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
871 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800872
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700873 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800874
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700875 for (int i = 0; i < nameCount; i++) {
876 String name = names.get(i);
877 Setting setting = settingsState.getSettingLocked(name);
878 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
879 pw.print(" name:"); pw.print(toDumpString(name));
880 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800881 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700882 }
883 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800884 if (setting.getDefaultValue() != null) {
885 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800886 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800887 }
888 if (setting.getTag() != null) {
889 pw.print(" tag:"); pw.print(setting.getTag());
890 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800891 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700892 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800893 }
894
Svetoslav7e0683b2015-08-03 16:02:52 -0700895 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700896 if (s != null) {
897 return s;
898 }
899 return "{null}";
900 }
901
Svetoslav683914b2015-01-15 14:22:26 -0800902 private void registerBroadcastReceivers() {
903 IntentFilter userFilter = new IntentFilter();
904 userFilter.addAction(Intent.ACTION_USER_REMOVED);
905 userFilter.addAction(Intent.ACTION_USER_STOPPED);
906
907 getContext().registerReceiver(new BroadcastReceiver() {
908 @Override
909 public void onReceive(Context context, Intent intent) {
910 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700911 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800912
913 switch (intent.getAction()) {
914 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700915 synchronized (mLock) {
916 mSettingsRegistry.removeUserStateLocked(userId, true);
917 }
Svetoslav683914b2015-01-15 14:22:26 -0800918 } break;
919
920 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700921 synchronized (mLock) {
922 mSettingsRegistry.removeUserStateLocked(userId, false);
923 }
Svetoslav683914b2015-01-15 14:22:26 -0800924 } break;
925 }
926 }
927 }, userFilter);
928
929 PackageMonitor monitor = new PackageMonitor() {
930 @Override
931 public void onPackageRemoved(String packageName, int uid) {
932 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100933 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800934 UserHandle.getUserId(uid));
935 }
936 }
Mark Rathjend891f012017-01-19 04:10:37 +0000937
938 @Override
939 public void onUidRemoved(int uid) {
940 synchronized (mLock) {
941 mSettingsRegistry.onUidRemovedLocked(uid);
942 }
943 }
Zimuzoc56192c2018-07-25 10:40:01 +0100944
945 @Override
946 public void onPackageDataCleared(String packageName, int uid) {
947 synchronized (mLock) {
948 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
949 UserHandle.getUserId(uid));
950 }
951 }
Svetoslav683914b2015-01-15 14:22:26 -0800952 };
953
954 // package changes
955 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
956 UserHandle.ALL, true);
957 }
958
Svet Ganov53a441c2016-04-19 19:38:00 -0700959 private void startWatchingUserRestrictionChanges() {
960 // TODO: The current design of settings looking different based on user restrictions
961 // should be reworked to keep them separate and system code should check the setting
962 // first followed by checking the user restriction before performing an operation.
963 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
964 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
965 Bundle prevRestrictions) -> {
966 // We are changing the settings affected by restrictions to their current
967 // value with a forced update to ensure that all cross profile dependencies
968 // are taken into account. Also make sure the settings update to.. the same
969 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800970 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
971 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700972 final long identity = Binder.clearCallingIdentity();
973 try {
974 synchronized (mLock) {
975 Setting setting = getSecureSetting(
976 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
977 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800978 setting != null ? setting.getValue() : null, null,
979 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700980 }
981 } finally {
982 Binder.restoreCallingIdentity(identity);
983 }
984 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800985 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100986 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
987 newRestrictions.getBoolean(
988 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
989 != prevRestrictions.getBoolean(
990 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700991 final long identity = Binder.clearCallingIdentity();
992 try {
993 synchronized (mLock) {
994 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800995 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700996 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800997 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700998 }
999 } finally {
1000 Binder.restoreCallingIdentity(identity);
1001 }
1002 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001003 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
1004 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001005 final long identity = Binder.clearCallingIdentity();
1006 try {
1007 synchronized (mLock) {
1008 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001009 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001010 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001011 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001012 }
1013 } finally {
1014 Binder.restoreCallingIdentity(identity);
1015 }
1016 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001017 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
1018 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001019 final long identity = Binder.clearCallingIdentity();
1020 try {
1021 synchronized (mLock) {
1022 Setting enable = getGlobalSetting(
1023 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001024 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001025 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001026 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001027 Setting include = getGlobalSetting(
1028 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001029 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001030 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001031 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001032 }
1033 } finally {
1034 Binder.restoreCallingIdentity(identity);
1035 }
1036 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001037 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
1038 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001039 final long identity = Binder.clearCallingIdentity();
1040 try {
1041 synchronized (mLock) {
1042 Setting setting = getGlobalSetting(
1043 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001044 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001045 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001046 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001047 }
1048 } finally {
1049 Binder.restoreCallingIdentity(identity);
1050 }
1051 }
1052 });
1053 }
1054
Matt Pape1b31a332018-10-17 09:58:28 -07001055 private Setting getConfigSetting(String name) {
1056 if (DEBUG) {
1057 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1058 }
1059
1060 // TODO(b/117663715): Ensure the caller can access the setting.
1061 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1062
1063 // Get the value.
1064 synchronized (mLock) {
1065 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1066 UserHandle.USER_SYSTEM, name);
1067 }
1068 }
1069
Matt Papec1323dc2018-12-11 12:32:42 -08001070 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001071 if (DEBUG) {
1072 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001073 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001074 }
Matt Papec1323dc2018-12-11 12:32:42 -08001075 return mutateConfigSetting(name, value, null, makeDefault,
1076 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001077 }
1078
Matt Papec1323dc2018-12-11 12:32:42 -08001079 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001080 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001081 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001082 }
Matt Papec1323dc2018-12-11 12:32:42 -08001083 return mutateConfigSetting(name, null, null, false,
1084 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001085 }
1086
Matt Papec1323dc2018-12-11 12:32:42 -08001087 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001088 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001089 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001090 }
Matt Papec1323dc2018-12-11 12:32:42 -08001091 mutateConfigSetting(null, null, prefix, false,
1092 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001093 }
1094
Matt Pape6bfc62e2018-11-28 13:16:03 -08001095 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001096 boolean makeDefault, int operation, int mode) {
Matt Pape1b31a332018-10-17 09:58:28 -07001097 // TODO(b/117663715): check the new permission when it's added.
1098 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1099
Matt Pape1b31a332018-10-17 09:58:28 -07001100 // Perform the mutation.
1101 synchronized (mLock) {
1102 switch (operation) {
1103 case MUTATION_OPERATION_INSERT: {
1104 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001105 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
1106 getCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001107 }
1108
Matt Pape6bfc62e2018-11-28 13:16:03 -08001109 case MUTATION_OPERATION_DELETE: {
1110 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001111 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001112 }
1113
Matt Pape1b31a332018-10-17 09:58:28 -07001114 case MUTATION_OPERATION_RESET: {
1115 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape6bfc62e2018-11-28 13:16:03 -08001116 UserHandle.USER_SYSTEM, getCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001117 } return true;
1118 }
1119 }
1120
1121 return false;
1122 }
1123
Matt Pape6bfc62e2018-11-28 13:16:03 -08001124 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1125 if (DEBUG) {
1126 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1127 }
1128
1129 synchronized (mLock) {
1130 // Get the settings.
1131 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1132 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1133
1134 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1135 UserHandle.USER_SYSTEM);
1136
1137 final int nameCount = names.size();
1138 Map<String, String> flagsToValues = new HashMap<>(names.size());
1139
1140 for (int i = 0; i < nameCount; i++) {
1141 String name = names.get(i);
1142 Setting setting = settingsState.getSettingLocked(name);
1143 if (prefix == null || setting.getName().startsWith(prefix)) {
1144 flagsToValues.put(setting.getName(), setting.getValue());
1145 }
1146 }
1147
1148 return flagsToValues;
1149 }
1150 }
1151
Svetoslav7ec28e82015-05-20 17:01:10 -07001152 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001153 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001154 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001155 }
1156
Svetoslav7ec28e82015-05-20 17:01:10 -07001157 synchronized (mLock) {
1158 // Get the settings.
1159 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001160 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001161
Chad Brubaker97bccee2017-01-05 15:51:41 -08001162 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1163 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001164
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001166
Svetoslav7ec28e82015-05-20 17:01:10 -07001167 String[] normalizedProjection = normalizeProjection(projection);
1168 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001169
Svetoslav7ec28e82015-05-20 17:01:10 -07001170 // Anyone can get the global settings, so no security checks.
1171 for (int i = 0; i < nameCount; i++) {
1172 String name = names.get(i);
1173 Setting setting = settingsState.getSettingLocked(name);
1174 appendSettingToCursor(result, setting);
1175 }
1176
1177 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001178 }
Svetoslav683914b2015-01-15 14:22:26 -08001179 }
1180
Svetoslav7ec28e82015-05-20 17:01:10 -07001181 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001182 if (DEBUG) {
1183 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1184 }
1185
Chad Brubakera6830e72017-04-28 17:34:36 -07001186 // Ensure the caller can access the setting.
1187 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1188
Svetoslav683914b2015-01-15 14:22:26 -08001189 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001190 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001191 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001192 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001193 }
Svetoslav683914b2015-01-15 14:22:26 -08001194 }
1195
Svetoslav Ganove080da92016-12-21 17:10:35 -08001196 private boolean updateGlobalSetting(String name, String value, String tag,
1197 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001198 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001199 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1200 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1201 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001202 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001203 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1204 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001205 }
1206
Svetoslav Ganove080da92016-12-21 17:10:35 -08001207 private boolean insertGlobalSetting(String name, String value, String tag,
1208 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001209 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001210 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1211 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1212 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1215 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001216 }
1217
Svet Ganov53a441c2016-04-19 19:38:00 -07001218 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001219 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001220 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1221 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001222 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001223 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1224 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001225 }
1226
Svetoslav Ganove080da92016-12-21 17:10:35 -08001227 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1228 if (DEBUG) {
1229 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1230 + mode + ", " + tag + ")");
1231 }
1232 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1233 MUTATION_OPERATION_RESET, false, mode);
1234 }
1235
1236 private boolean mutateGlobalSetting(String name, String value, String tag,
1237 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1238 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001239 // Make sure the caller can change the settings - treated as secure.
1240 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1241
Svetoslav683914b2015-01-15 14:22:26 -08001242 // Resolve the userId on whose behalf the call is made.
1243 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1244
Makoto Onuki28da2e32015-11-20 11:30:44 -08001245 // If this is a setting that is currently restricted for this user, do not allow
1246 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001247 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1248 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001249 return false;
1250 }
1251
1252 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001253 synchronized (mLock) {
1254 switch (operation) {
1255 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001256 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1257 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001258 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001259 }
Svetoslav683914b2015-01-15 14:22:26 -08001260
Svetoslav7ec28e82015-05-20 17:01:10 -07001261 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001262 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001263 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001264 }
Svetoslav683914b2015-01-15 14:22:26 -08001265
Svetoslav7ec28e82015-05-20 17:01:10 -07001266 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001267 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1268 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001269 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001270 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001271
1272 case MUTATION_OPERATION_RESET: {
1273 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1274 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1275 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001276 }
1277 }
1278
1279 return false;
1280 }
1281
Christopher Tateb218e762017-04-05 16:34:07 -07001282 private PackageInfo getCallingPackageInfo(int userId) {
1283 try {
1284 return mPackageManager.getPackageInfo(getCallingPackage(),
1285 PackageManager.GET_SIGNATURES, userId);
1286 } catch (RemoteException e) {
1287 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1288 }
1289 }
1290
Svetoslav7ec28e82015-05-20 17:01:10 -07001291 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001292 if (DEBUG) {
1293 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1294 }
1295
1296 // Resolve the userId on whose behalf the call is made.
1297 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1298
Christopher Tateb218e762017-04-05 16:34:07 -07001299 // The relevant "calling package" userId will be the owning userId for some
1300 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1301 // up front who the effective "new SSAID" user ID for that settings name will be.
1302 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1303 Settings.Secure.ANDROID_ID);
1304 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1305
Svetoslav7ec28e82015-05-20 17:01:10 -07001306 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001307 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001308
Svetoslav7ec28e82015-05-20 17:01:10 -07001309 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001310
Svetoslav7ec28e82015-05-20 17:01:10 -07001311 String[] normalizedProjection = normalizeProjection(projection);
1312 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001313
Svetoslav7ec28e82015-05-20 17:01:10 -07001314 for (int i = 0; i < nameCount; i++) {
1315 String name = names.get(i);
1316 // Determine the owning user as some profile settings are cloned from the parent.
1317 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1318 name);
Svetoslav683914b2015-01-15 14:22:26 -08001319
Alex Klyubin1991f572017-03-03 14:08:36 -08001320 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1321 // This caller is not permitted to access this setting. Pretend the setting
1322 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001323 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001324 }
Svetoslav683914b2015-01-15 14:22:26 -08001325
Mark Rathjen7599f132017-01-23 14:15:54 -08001326 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001327 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1328 final Setting setting;
1329 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001330 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001331 } else {
1332 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1333 name);
1334 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001335 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001336 }
1337
Svetoslav7ec28e82015-05-20 17:01:10 -07001338 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001339 }
Svetoslav683914b2015-01-15 14:22:26 -08001340 }
1341
Svetoslav7ec28e82015-05-20 17:01:10 -07001342 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001343 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1344 }
1345
1346 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001347 if (DEBUG) {
1348 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1349 }
1350
1351 // Resolve the userId on whose behalf the call is made.
1352 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1353
Chad Brubakera6830e72017-04-28 17:34:36 -07001354 // Ensure the caller can access the setting.
1355 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1356
Svetoslav683914b2015-01-15 14:22:26 -08001357 // Determine the owning user as some profile settings are cloned from the parent.
1358 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1359
Alex Klyubin1991f572017-03-03 14:08:36 -08001360 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1361 // This caller is not permitted to access this setting. Pretend the setting doesn't
1362 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001363 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1364 owningUserId);
1365 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001366 }
1367
Christopher Tateb218e762017-04-05 16:34:07 -07001368 // As of Android O, the SSAID is read from an app-specific entry in table
1369 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1370 if (isNewSsaidSetting(name)) {
1371 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1372 synchronized (mLock) {
1373 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001374 }
Christopher Tateb218e762017-04-05 16:34:07 -07001375 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001376 if (enableOverride) {
1377 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1378 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1379 if (overridden != null) {
1380 return overridden;
1381 }
1382 }
1383 }
Mark Rathjend891f012017-01-19 04:10:37 +00001384
Christopher Tateb218e762017-04-05 16:34:07 -07001385 // Not the SSAID; do a straight lookup
1386 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001387 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001388 owningUserId, name);
1389 }
Svetoslav683914b2015-01-15 14:22:26 -08001390 }
1391
Mark Rathjend891f012017-01-19 04:10:37 +00001392 private boolean isNewSsaidSetting(String name) {
1393 return Settings.Secure.ANDROID_ID.equals(name)
1394 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1395 }
1396
Andreas Gampeb58893072018-09-05 16:52:31 -07001397 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001398 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001399 // Get uid of caller (key) used to store ssaid value
1400 String name = Integer.toString(
1401 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1402
1403 if (DEBUG) {
1404 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1405 }
1406
1407 // Retrieve the ssaid from the table if present.
1408 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1409 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001410 // If the app is an Instant App use its stored SSAID instead of our own.
1411 final String instantSsaid;
1412 final long token = Binder.clearCallingIdentity();
1413 try {
1414 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1415 owningUserId);
1416 } catch (RemoteException e) {
1417 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1418 return null;
1419 } finally {
1420 Binder.restoreCallingIdentity(token);
1421 }
Svet Ganov96c99462017-05-05 14:27:13 -07001422
1423 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1424 SETTINGS_TYPE_SSAID, owningUserId);
1425
Chad Brubaker0d277a72017-04-12 16:56:53 -07001426 if (instantSsaid != null) {
1427 // Use the stored value if it is still valid.
1428 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001429 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001430 }
1431 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001432 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1433 true, callingPkg.packageName);
1434 if (!success) {
1435 throw new IllegalStateException("Failed to update instant app android id");
1436 }
Svet Ganov96c99462017-05-05 14:27:13 -07001437 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1438 owningUserId, name);
1439 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001440 }
Mark Rathjend891f012017-01-19 04:10:37 +00001441
1442 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001443 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001444 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1445 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001446 }
1447
Svet Ganov96c99462017-05-05 14:27:13 -07001448 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1449 }
1450
1451 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1452 // SSAID settings are located in a dedicated table for internal bookkeeping
1453 // but for the world they reside in the secure table, so adjust the key here.
1454 // We have a special name when looking it up but want the world to see it as
1455 // "android_id".
1456 if (ssaidSetting != null) {
1457 return settingsState.new Setting(ssaidSetting) {
1458 @Override
1459 public int getKey() {
1460 final int userId = getUserIdFromKey(super.getKey());
1461 return makeKey(SETTINGS_TYPE_SECURE, userId);
1462 }
1463
1464 @Override
1465 public String getName() {
1466 return Settings.Secure.ANDROID_ID;
1467 }
1468 };
1469 }
1470 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001471 }
1472
Makoto Onuki0000d322017-11-28 16:31:47 -08001473 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1474 synchronized (mLock) {
1475 final Setting setting = getGlobalSetting(
1476 Global.LOCATION_GLOBAL_KILL_SWITCH);
1477 if (!"1".equals(setting.getValue())) {
1478 return null;
1479 }
1480 // Global kill-switch is enabled. Return an empty value.
1481 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1482 SETTINGS_TYPE_SECURE, owningUserId);
1483 return settingsState.new Setting(
1484 Secure.LOCATION_PROVIDERS_ALLOWED,
1485 "", // value
1486 "", // tag
1487 "", // default value
1488 "", // package name
1489 false, // from system
1490 "0" // id
1491 ) {
1492 @Override
1493 public boolean update(String value, boolean setDefault, String packageName,
1494 String tag, boolean forceNonSystemPackage) {
1495 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1496 return false;
1497 }
1498 };
1499 }
1500 }
1501
Svetoslav Ganove080da92016-12-21 17:10:35 -08001502 private boolean insertSecureSetting(String name, String value, String tag,
1503 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001504 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001505 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001506 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1507 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001508 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001509 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1510 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001511 }
1512
Svet Ganov53a441c2016-04-19 19:38:00 -07001513 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001514 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001515 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1516 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001517 }
1518
Svetoslav Ganove080da92016-12-21 17:10:35 -08001519 return mutateSecureSetting(name, null, null, false, requestingUserId,
1520 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001521 }
1522
Svetoslav Ganove080da92016-12-21 17:10:35 -08001523 private boolean updateSecureSetting(String name, String value, String tag,
1524 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001525 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001526 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001527 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1528 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001529 }
1530
Svetoslav Ganove080da92016-12-21 17:10:35 -08001531 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1532 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001533 }
1534
Svetoslav Ganove080da92016-12-21 17:10:35 -08001535 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1536 if (DEBUG) {
1537 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1538 + mode + ", " + tag + ")");
1539 }
1540
1541 mutateSecureSetting(null, null, tag, false, requestingUserId,
1542 MUTATION_OPERATION_RESET, false, mode);
1543 }
1544
1545 private boolean mutateSecureSetting(String name, String value, String tag,
1546 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1547 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001548 // Make sure the caller can change the settings.
1549 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1550
Svetoslav683914b2015-01-15 14:22:26 -08001551 // Resolve the userId on whose behalf the call is made.
1552 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1553
Makoto Onuki28da2e32015-11-20 11:30:44 -08001554 // If this is a setting that is currently restricted for this user, do not allow
1555 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001556 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1557 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001558 return false;
1559 }
1560
1561 // Determine the owning user as some profile settings are cloned from the parent.
1562 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1563
1564 // Only the owning user can change the setting.
1565 if (owningUserId != callingUserId) {
1566 return false;
1567 }
1568
1569 // Special cases for location providers (sigh).
1570 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001571 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1572 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001573 }
1574
1575 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001576 synchronized (mLock) {
1577 switch (operation) {
1578 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001579 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001580 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001581 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001582 }
Svetoslav683914b2015-01-15 14:22:26 -08001583
Svetoslav7ec28e82015-05-20 17:01:10 -07001584 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001585 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001586 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001587 }
Svetoslav683914b2015-01-15 14:22:26 -08001588
Svetoslav7ec28e82015-05-20 17:01:10 -07001589 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001590 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001591 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001592 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001593 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001594
1595 case MUTATION_OPERATION_RESET: {
1596 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1597 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1598 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001599 }
1600 }
1601
1602 return false;
1603 }
1604
Svetoslav7ec28e82015-05-20 17:01:10 -07001605 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001606 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001607 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001608 }
1609
1610 // Resolve the userId on whose behalf the call is made.
1611 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1612
Svetoslav7ec28e82015-05-20 17:01:10 -07001613 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001614 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001615
Svetoslav7ec28e82015-05-20 17:01:10 -07001616 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001617
Svetoslav7ec28e82015-05-20 17:01:10 -07001618 String[] normalizedProjection = normalizeProjection(projection);
1619 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001620
Svetoslav7ec28e82015-05-20 17:01:10 -07001621 for (int i = 0; i < nameCount; i++) {
1622 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001623
Svetoslav7ec28e82015-05-20 17:01:10 -07001624 // Determine the owning user as some profile settings are cloned from the parent.
1625 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1626 name);
Svetoslav683914b2015-01-15 14:22:26 -08001627
Svetoslav7ec28e82015-05-20 17:01:10 -07001628 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001629 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001630 appendSettingToCursor(result, setting);
1631 }
1632
1633 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001634 }
Svetoslav683914b2015-01-15 14:22:26 -08001635 }
1636
Svetoslav7ec28e82015-05-20 17:01:10 -07001637 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001638 if (DEBUG) {
1639 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1640 }
1641
1642 // Resolve the userId on whose behalf the call is made.
1643 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1644
Chad Brubakera6830e72017-04-28 17:34:36 -07001645 // Ensure the caller can access the setting.
1646 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001647
Svetoslav683914b2015-01-15 14:22:26 -08001648 // Determine the owning user as some profile settings are cloned from the parent.
1649 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1650
1651 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001652 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001653 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001654 }
Svetoslav683914b2015-01-15 14:22:26 -08001655 }
1656
Svetoslav7ec28e82015-05-20 17:01:10 -07001657 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001658 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001659 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001660 + requestingUserId + ")");
1661 }
1662
Svetoslav7ec28e82015-05-20 17:01:10 -07001663 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001664 }
1665
Svetoslav7ec28e82015-05-20 17:01:10 -07001666 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001667 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001668 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001669 }
1670
Svetoslav7ec28e82015-05-20 17:01:10 -07001671 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001672 }
1673
Svetoslav7ec28e82015-05-20 17:01:10 -07001674 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001675 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001676 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001677 + requestingUserId + ")");
1678 }
1679
Svetoslav7ec28e82015-05-20 17:01:10 -07001680 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001681 }
1682
Svetoslav7ec28e82015-05-20 17:01:10 -07001683 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001684 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001685 if (!hasWriteSecureSettingsPermission()) {
1686 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1687 // operation is allowed for the calling package through appops.
1688 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1689 Binder.getCallingUid(), getCallingPackage(), true)) {
1690 return false;
1691 }
Svetoslav683914b2015-01-15 14:22:26 -08001692 }
1693
Svetoslav683914b2015-01-15 14:22:26 -08001694 // Resolve the userId on whose behalf the call is made.
1695 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1696
yuemingw1d13eae2018-01-30 17:27:54 +00001697 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1698 name, callingUserId, value, Binder.getCallingUid())) {
1699 return false;
1700 }
1701
Svetoslavd8d25e02015-11-20 13:09:26 -08001702 // Enforce what the calling package can mutate the system settings.
1703 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1704
Svetoslav683914b2015-01-15 14:22:26 -08001705 // Determine the owning user as some profile settings are cloned from the parent.
1706 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1707
1708 // Only the owning user id can change the setting.
1709 if (owningUserId != callingUserId) {
1710 return false;
1711 }
1712
Jeff Sharkey413573a2016-02-22 17:52:45 -07001713 // Invalidate any relevant cache files
1714 String cacheName = null;
1715 if (Settings.System.RINGTONE.equals(name)) {
1716 cacheName = Settings.System.RINGTONE_CACHE;
1717 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1718 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1719 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1720 cacheName = Settings.System.ALARM_ALERT_CACHE;
1721 }
1722 if (cacheName != null) {
1723 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001724 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001725 cacheFile.delete();
1726 }
1727
Svetoslav683914b2015-01-15 14:22:26 -08001728 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001729 synchronized (mLock) {
1730 switch (operation) {
1731 case MUTATION_OPERATION_INSERT: {
1732 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001733 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001734 owningUserId, name, value, null, false, getCallingPackage(),
1735 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001736 }
1737
1738 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001739 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001740 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001741 }
1742
1743 case MUTATION_OPERATION_UPDATE: {
1744 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001745 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001746 owningUserId, name, value, null, false, getCallingPackage(),
1747 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001748 }
Svetoslav683914b2015-01-15 14:22:26 -08001749 }
1750
Svetoslav7ec28e82015-05-20 17:01:10 -07001751 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001752 }
Svetoslav683914b2015-01-15 14:22:26 -08001753 }
1754
Billy Lau6ad2d662015-07-18 00:26:58 +01001755 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001756 // Write secure settings is a more protected permission. If caller has it we are good.
1757 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1758 == PackageManager.PERMISSION_GRANTED) {
1759 return true;
1760 }
1761
Svetoslavf41334b2015-06-23 12:06:03 -07001762 return false;
1763 }
1764
Svetoslav683914b2015-01-15 14:22:26 -08001765 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001766 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001767 if (validator != null && !validator.validate(value)) {
1768 throw new IllegalArgumentException("Invalid value: " + value
1769 + " for setting: " + name);
1770 }
1771 }
1772
Alex Klyubin1991f572017-03-03 14:08:36 -08001773 /**
1774 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1775 */
1776 private boolean isSecureSettingAccessible(String name, int callingUserId,
1777 int owningUserId) {
1778 // Special case for location (sigh).
1779 // This check is not inside the name-based checks below because this method performs checks
1780 // only if the calling user ID is not the same as the owning user ID.
1781 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1782 return false;
1783 }
1784
1785 switch (name) {
1786 case "bluetooth_address":
1787 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1788 // address in this secure setting. Secure settings can normally be read by any app,
1789 // which thus enables them to bypass the recently introduced restrictions on access
1790 // to device identifiers.
1791 // To mitigate this we make this setting available only to callers privileged to see
1792 // this device's MAC addresses, same as through public API
1793 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1794 return getContext().checkCallingOrSelfPermission(
1795 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1796 default:
1797 return true;
1798 }
1799 }
1800
Svetoslav683914b2015-01-15 14:22:26 -08001801 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1802 int owningUserId) {
1803 // Optimization - location providers are restricted only for managed profiles.
1804 if (callingUserId == owningUserId) {
1805 return false;
1806 }
1807 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1808 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1809 new UserHandle(callingUserId))) {
1810 return true;
1811 }
1812 return false;
1813 }
1814
Svetoslav683914b2015-01-15 14:22:26 -08001815 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1816 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1817 }
1818
1819 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001820 final int parentId;
1821 // Resolves dependency if setting has a dependency and the calling user has a parent
1822 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1823 && (parentId = getGroupParentLocked(userId)) != userId) {
1824 // The setting has a dependency and the profile has a parent
1825 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001826 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1827 final long token = Binder.clearCallingIdentity();
1828 try {
1829 Setting settingObj = getSecureSetting(dependency, userId);
1830 if (settingObj != null && settingObj.getValue().equals("1")) {
1831 return parentId;
1832 }
1833 } finally {
1834 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001835 }
1836 }
Svetoslav683914b2015-01-15 14:22:26 -08001837 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1838 }
1839
1840 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1841 final int parentId = getGroupParentLocked(userId);
1842 if (parentId != userId && keys.contains(name)) {
1843 return parentId;
1844 }
1845 return userId;
1846 }
1847
Svetoslavf41334b2015-06-23 12:06:03 -07001848 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001849 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001850 // System/root/shell can mutate whatever secure settings they want.
1851 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001852 final int appId = UserHandle.getAppId(callingUid);
1853 if (appId == android.os.Process.SYSTEM_UID
1854 || appId == Process.SHELL_UID
1855 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001856 return;
1857 }
1858
1859 switch (operation) {
1860 case MUTATION_OPERATION_INSERT:
1861 // Insert updates.
1862 case MUTATION_OPERATION_UPDATE: {
1863 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1864 return;
1865 }
1866
1867 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001868 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001869
1870 // Privileged apps can do whatever they want.
1871 if ((packageInfo.applicationInfo.privateFlags
1872 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1873 return;
1874 }
1875
1876 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1877 packageInfo.applicationInfo.targetSdkVersion, name);
1878 } break;
1879
1880 case MUTATION_OPERATION_DELETE: {
1881 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1882 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1883 throw new IllegalArgumentException("You cannot delete system defined"
1884 + " secure settings.");
1885 }
1886
1887 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001888 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001889
1890 // Privileged apps can do whatever they want.
1891 if ((packageInfo.applicationInfo.privateFlags &
1892 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1893 return;
1894 }
1895
1896 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1897 packageInfo.applicationInfo.targetSdkVersion, name);
1898 } break;
1899 }
1900 }
1901
Todd Kennedybe0b8892017-02-15 14:13:52 -08001902 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001903 switch (settingsType) {
1904 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001905 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001906 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001907 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001908 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001909 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001910 default:
1911 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1912 }
1913 }
1914
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001915 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1916 switch (settingsType) {
1917 case SETTINGS_TYPE_GLOBAL:
1918 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1919 case SETTINGS_TYPE_SYSTEM:
1920 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1921 case SETTINGS_TYPE_SECURE:
1922 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1923 default:
1924 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1925 }
1926 }
1927
Andreas Gampeb58893072018-09-05 16:52:31 -07001928 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001929 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001930 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1931 // in the current form.
1932 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001933 }
1934
Chad Brubakera6830e72017-04-28 17:34:36 -07001935 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001936 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1937 return;
1938 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001939 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001940 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001941 return;
1942 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001943 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1944 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001945 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1946 // breakage in the current form.
1947 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1948 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001949 }
1950 }
1951
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001952 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1953 // We always use the callingUid for this lookup. This means that if hypothetically an
1954 // app was installed in user A with cross user and in user B as an Instant App
1955 // the app in A would be able to see all the settings in user B. However since cross
1956 // user is a system permission and the app must be uninstalled in B and then installed as
1957 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001958 ApplicationInfo ai = null;
1959 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001960 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1961 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001962 } catch (RemoteException ignored) {
1963 }
1964 if (ai == null) {
1965 throw new IllegalStateException("Failed to lookup info for package "
1966 + getCallingPackage());
1967 }
1968 return ai;
1969 }
1970
Xiaohui Chen43765b72015-08-31 10:57:33 -07001971 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001972 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001973 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1974 getCallingPackage(), 0, userId);
1975 if (packageInfo != null) {
1976 return packageInfo;
1977 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001978 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001979 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001980 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001981 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001982 }
1983
1984 private int getGroupParentLocked(int userId) {
1985 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001986 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001987 return userId;
1988 }
1989 // We are in the same process with the user manager and the returned
1990 // user info is a cached instance, so just look up instead of cache.
1991 final long identity = Binder.clearCallingIdentity();
1992 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001993 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001994 UserInfo userInfo = mUserManager.getProfileParent(userId);
1995 return (userInfo != null) ? userInfo.id : userId;
1996 } finally {
1997 Binder.restoreCallingIdentity(identity);
1998 }
1999 }
2000
Svetoslav683914b2015-01-15 14:22:26 -08002001 private void enforceWritePermission(String permission) {
2002 if (getContext().checkCallingOrSelfPermission(permission)
2003 != PackageManager.PERMISSION_GRANTED) {
2004 throw new SecurityException("Permission denial: writing to settings requires:"
2005 + permission);
2006 }
2007 }
2008
2009 /*
2010 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2011 * This setting contains a list of the currently enabled location providers.
2012 * But helper functions in android.providers.Settings can enable or disable
2013 * a single provider by using a "+" or "-" prefix before the provider name.
2014 *
yuemingw1d13eae2018-01-30 17:27:54 +00002015 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2016 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2017 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002018 *
Svetoslav683914b2015-01-15 14:22:26 -08002019 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002020 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002021 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002022 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2023 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002024 if (TextUtils.isEmpty(value)) {
2025 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002026 }
Maggie83e03f52018-03-16 12:22:20 -07002027 Setting oldSetting = getSecureSetting(
2028 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2029 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002030 return false;
2031 }
Maggie83e03f52018-03-16 12:22:20 -07002032 String oldProviders = oldSetting.getValue();
2033 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2034 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2035 Set<String> newProvidersSet = new ArraySet<>();
2036 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002037
Maggie83e03f52018-03-16 12:22:20 -07002038 String[] providerUpdates = value.split(",");
2039 boolean inputError = false;
2040 for (String provider : providerUpdates) {
2041 // do not update location_providers_allowed when input is invalid
2042 if (TextUtils.isEmpty(provider)) {
2043 inputError = true;
2044 break;
Svetoslav683914b2015-01-15 14:22:26 -08002045 }
Maggie83e03f52018-03-16 12:22:20 -07002046 final char prefix = provider.charAt(0);
2047 // do not update location_providers_allowed when input is invalid
2048 if (prefix != '+' && prefix != '-') {
2049 inputError = true;
2050 break;
Svetoslav683914b2015-01-15 14:22:26 -08002051 }
Maggie83e03f52018-03-16 12:22:20 -07002052 // skip prefix
2053 provider = provider.substring(1);
2054 if (prefix == '+') {
2055 newProvidersSet.add(provider);
2056 } else if (prefix == '-') {
2057 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002058 }
Maggie83e03f52018-03-16 12:22:20 -07002059 }
2060 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2061 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002062 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002063 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002064 mSettingsRegistry.notifyForSettingsChange(
2065 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002066 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2067 }
Svetoslav683914b2015-01-15 14:22:26 -08002068 return false;
2069 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002070 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002071 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2072 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002073 }
2074
Svetoslav683914b2015-01-15 14:22:26 -08002075 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2076 int targetSdkVersion, String name) {
2077 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2078 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2079 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2080 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2081 + " This will soon become an error.");
2082 } else {
2083 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2084 + " This will soon become an error.");
2085 }
2086 } else {
2087 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2088 throw new IllegalArgumentException("You cannot change private secure settings.");
2089 } else {
2090 throw new IllegalArgumentException("You cannot keep your settings in"
2091 + " the secure settings.");
2092 }
2093 }
2094 }
2095
2096 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2097 if (requestingUserId == UserHandle.getCallingUserId()) {
2098 return requestingUserId;
2099 }
2100 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2101 Binder.getCallingUid(), requestingUserId, false, true,
2102 "get/set setting for user", null);
2103 }
2104
Svet Ganov53a441c2016-04-19 19:38:00 -07002105 private Bundle packageValueForCallResult(Setting setting,
2106 boolean trackingGeneration) {
2107 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002108 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002109 return NULL_SETTING_BUNDLE;
2110 }
2111 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002112 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002113 Bundle result = new Bundle();
2114 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002115 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002116
Svetoslav Ganove080da92016-12-21 17:10:35 -08002117 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002118 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002119 }
2120
2121 private static int getRequestingUserId(Bundle args) {
2122 final int callingUserId = UserHandle.getCallingUserId();
2123 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2124 : callingUserId;
2125 }
2126
Svet Ganov53a441c2016-04-19 19:38:00 -07002127 private boolean isTrackingGeneration(Bundle args) {
2128 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2129 }
2130
Svetoslav683914b2015-01-15 14:22:26 -08002131 private static String getSettingValue(Bundle args) {
2132 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2133 }
2134
Svetoslav Ganove080da92016-12-21 17:10:35 -08002135 private static String getSettingTag(Bundle args) {
2136 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2137 }
2138
Matt Pape6bfc62e2018-11-28 13:16:03 -08002139 private static String getSettingPrefix(Bundle args) {
2140 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2141 // Append '/' to ensure we only match properties with this exact prefix.
2142 // i.e. "foo" should match "foo/property" but not "foobar/property"
2143 return prefix != null ? prefix + "/" : null;
2144 }
2145
Svetoslav Ganove080da92016-12-21 17:10:35 -08002146 private static boolean getSettingMakeDefault(Bundle args) {
2147 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2148 }
2149
2150 private static int getResetModeEnforcingPermission(Bundle args) {
2151 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2152 switch (mode) {
2153 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2154 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2155 throw new SecurityException("Only system, shell/root on a "
2156 + "debuggable build can reset to untrusted defaults");
2157 }
2158 return mode;
2159 }
2160 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2161 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2162 throw new SecurityException("Only system, shell/root on a "
2163 + "debuggable build can reset untrusted changes");
2164 }
2165 return mode;
2166 }
2167 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2168 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2169 throw new SecurityException("Only system, shell/root on a "
2170 + "debuggable build can reset to trusted defaults");
2171 }
2172 return mode;
2173 }
2174 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2175 return mode;
2176 }
2177 }
2178 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2179 }
2180
2181 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2182 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2183 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2184 && (appId == SHELL_UID || appId == ROOT_UID));
2185 }
2186
Svetoslav683914b2015-01-15 14:22:26 -08002187 private static String getValidTableOrThrow(Uri uri) {
2188 if (uri.getPathSegments().size() > 0) {
2189 String table = uri.getPathSegments().get(0);
2190 if (DatabaseHelper.isValidTable(table)) {
2191 return table;
2192 }
2193 throw new IllegalArgumentException("Bad root path: " + table);
2194 }
2195 throw new IllegalArgumentException("Invalid URI:" + uri);
2196 }
2197
2198 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002199 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002200 return new MatrixCursor(projection, 0);
2201 }
2202 MatrixCursor cursor = new MatrixCursor(projection, 1);
2203 appendSettingToCursor(cursor, setting);
2204 return cursor;
2205 }
2206
2207 private static String[] normalizeProjection(String[] projection) {
2208 if (projection == null) {
2209 return ALL_COLUMNS;
2210 }
2211
2212 final int columnCount = projection.length;
2213 for (int i = 0; i < columnCount; i++) {
2214 String column = projection[i];
2215 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2216 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002217 }
2218 }
2219
Svetoslav683914b2015-01-15 14:22:26 -08002220 return projection;
2221 }
2222
2223 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002224 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002225 return;
2226 }
Svetoslav683914b2015-01-15 14:22:26 -08002227 final int columnCount = cursor.getColumnCount();
2228
2229 String[] values = new String[columnCount];
2230
2231 for (int i = 0; i < columnCount; i++) {
2232 String column = cursor.getColumnName(i);
2233
2234 switch (column) {
2235 case Settings.NameValueTable._ID: {
2236 values[i] = setting.getId();
2237 } break;
2238
2239 case Settings.NameValueTable.NAME: {
2240 values[i] = setting.getName();
2241 } break;
2242
2243 case Settings.NameValueTable.VALUE: {
2244 values[i] = setting.getValue();
2245 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002246 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002247 }
2248
Svetoslav683914b2015-01-15 14:22:26 -08002249 cursor.addRow(values);
2250 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002251
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002252 private static boolean isKeyValid(String key) {
2253 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2254 }
2255
Svetoslav683914b2015-01-15 14:22:26 -08002256 private static final class Arguments {
2257 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2258 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2259
2260 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2261 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2262
2263 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2264 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2265
2266 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2267 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2268
2269 public final String table;
2270 public final String name;
2271
2272 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2273 final int segmentSize = uri.getPathSegments().size();
2274 switch (segmentSize) {
2275 case 1: {
2276 if (where != null
2277 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2278 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2279 && whereArgs.length == 1) {
2280 name = whereArgs[0];
2281 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002282 return;
Svetoslav683914b2015-01-15 14:22:26 -08002283 } else if (where != null
2284 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2285 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2286 final int startIndex = Math.max(where.indexOf("'"),
2287 where.indexOf("\"")) + 1;
2288 final int endIndex = Math.max(where.lastIndexOf("'"),
2289 where.lastIndexOf("\""));
2290 name = where.substring(startIndex, endIndex);
2291 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002292 return;
Svetoslav683914b2015-01-15 14:22:26 -08002293 } else if (supportAll && where == null && whereArgs == null) {
2294 name = null;
2295 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002296 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002297 }
Svetoslav683914b2015-01-15 14:22:26 -08002298 } break;
2299
Svetoslav28494652015-02-12 14:11:42 -08002300 case 2: {
2301 if (where == null && whereArgs == null) {
2302 name = uri.getPathSegments().get(1);
2303 table = computeTableForSetting(uri, name);
2304 return;
2305 }
2306 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002307 }
Svetoslav28494652015-02-12 14:11:42 -08002308
2309 EventLogTags.writeUnsupportedSettingsQuery(
2310 uri.toSafeString(), where, Arrays.toString(whereArgs));
2311 String message = String.format( "Supported SQL:\n"
2312 + " uri content://some_table/some_property with null where and where args\n"
2313 + " uri content://some_table with query name=? and single name as arg\n"
2314 + " uri content://some_table with query name=some_name and null args\n"
2315 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2316 Arrays.toString(whereArgs));
2317 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002318 }
2319
Svetoslav28494652015-02-12 14:11:42 -08002320 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002321 String table = getValidTableOrThrow(uri);
2322
2323 if (name != null) {
2324 if (sSystemMovedToSecureSettings.contains(name)) {
2325 table = TABLE_SECURE;
2326 }
2327
2328 if (sSystemMovedToGlobalSettings.contains(name)) {
2329 table = TABLE_GLOBAL;
2330 }
2331
2332 if (sSecureMovedToGlobalSettings.contains(name)) {
2333 table = TABLE_GLOBAL;
2334 }
2335
2336 if (sGlobalMovedToSecureSettings.contains(name)) {
2337 table = TABLE_SECURE;
2338 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002339 }
Svetoslav683914b2015-01-15 14:22:26 -08002340
2341 return table;
2342 }
2343 }
2344
2345 final class SettingsRegistry {
2346 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2347
Svetoslav683914b2015-01-15 14:22:26 -08002348 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2349 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2350 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002351 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002352 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002353
2354 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002355
2356 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2357
Svet Ganov53a441c2016-04-19 19:38:00 -07002358 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002359
Svetoslav7e0683b2015-08-03 16:02:52 -07002360 private final Handler mHandler;
2361
Svet Ganov53a441c2016-04-19 19:38:00 -07002362 private final BackupManager mBackupManager;
2363
Amith Yamasani39452022017-03-21 15:23:47 -07002364 private String mSettingsCreationBuildId;
2365
Svetoslav683914b2015-01-15 14:22:26 -08002366 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002367 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002368 mGenerationRegistry = new GenerationRegistry(mLock);
2369 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002370 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002371 syncSsaidTableOnStart();
2372 }
2373
2374 private void generateUserKeyLocked(int userId) {
2375 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002376 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002377 final SecureRandom rand = new SecureRandom();
2378 rand.nextBytes(keyBytes);
2379
2380 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002381 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002382
2383 // Store the key in the ssaid table.
2384 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2385 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2386 true, SettingsState.SYSTEM_PACKAGE_NAME);
2387
2388 if (!success) {
2389 throw new IllegalStateException("Ssaid settings not accessible");
2390 }
2391 }
2392
Mark Rathjen7599f132017-01-23 14:15:54 -08002393 private byte[] getLengthPrefix(byte[] data) {
2394 return ByteBuffer.allocate(4).putInt(data.length).array();
2395 }
2396
Christopher Tateb218e762017-04-05 16:34:07 -07002397 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002398 // Read the user's key from the ssaid table.
2399 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002400 if (userKeySetting == null || userKeySetting.isNull()
2401 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002402 // Lazy initialize and store the user key.
2403 generateUserKeyLocked(userId);
2404 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002405 if (userKeySetting == null || userKeySetting.isNull()
2406 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002407 throw new IllegalStateException("User key not accessible");
2408 }
2409 }
2410 final String userKey = userKeySetting.getValue();
2411
2412 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002413 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2414
2415 // Validate that the key is of expected length.
2416 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2417 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002418 throw new IllegalStateException("User key invalid");
2419 }
2420
Mark Rathjen7599f132017-01-23 14:15:54 -08002421 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002422 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002423 m = Mac.getInstance("HmacSHA256");
2424 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002425 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002426 throw new IllegalStateException("HmacSHA256 is not available", e);
2427 } catch (InvalidKeyException e) {
2428 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002429 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002430
Mark Rathjenf42dd912017-06-05 19:04:34 -07002431 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002432 for (int i = 0; i < callingPkg.signatures.length; i++) {
2433 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002434 m.update(getLengthPrefix(sig), 0, 4);
2435 m.update(sig);
2436 }
Mark Rathjend891f012017-01-19 04:10:37 +00002437
2438 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002439 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2440 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002441
2442 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002443 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002444 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2445 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002446 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002447
2448 if (!success) {
2449 throw new IllegalStateException("Ssaid settings not accessible");
2450 }
2451
2452 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2453 }
2454
2455 public void syncSsaidTableOnStart() {
2456 synchronized (mLock) {
2457 // Verify that each user's packages and ssaid's are in sync.
2458 for (UserInfo user : mUserManager.getUsers(true)) {
2459 // Get all uids for the user's packages.
2460 final List<PackageInfo> packages;
2461 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002462 packages = mPackageManager.getInstalledPackages(
2463 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2464 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002465 } catch (RemoteException e) {
2466 throw new IllegalStateException("Package manager not available");
2467 }
2468 final Set<String> appUids = new HashSet<>();
2469 for (PackageInfo info : packages) {
2470 appUids.add(Integer.toString(info.applicationInfo.uid));
2471 }
2472
2473 // Get all uids currently stored in the user's ssaid table.
2474 final Set<String> ssaidUids = new HashSet<>(
2475 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2476 ssaidUids.remove(SSAID_USER_KEY);
2477
2478 // Perform a set difference for the appUids and ssaidUids.
2479 ssaidUids.removeAll(appUids);
2480
2481 // If there are ssaidUids left over they need to be removed from the table.
2482 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2483 user.id);
2484 for (String uid : ssaidUids) {
2485 ssaidSettings.deleteSettingLocked(uid);
2486 }
2487 }
2488 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002489 }
2490
Svetoslav683914b2015-01-15 14:22:26 -08002491 public List<String> getSettingsNamesLocked(int type, int userId) {
2492 final int key = makeKey(type, userId);
2493 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002494 if (settingsState == null) {
2495 return new ArrayList<String>();
2496 }
Svetoslav683914b2015-01-15 14:22:26 -08002497 return settingsState.getSettingNamesLocked();
2498 }
2499
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002500 public SparseBooleanArray getKnownUsersLocked() {
2501 SparseBooleanArray users = new SparseBooleanArray();
2502 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2503 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2504 }
2505 return users;
2506 }
2507
Kweku Adamsb0886f32017-10-31 15:32:09 -07002508 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002509 public SettingsState getSettingsLocked(int type, int userId) {
2510 final int key = makeKey(type, userId);
2511 return peekSettingsStateLocked(key);
2512 }
2513
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002514 public boolean ensureSettingsForUserLocked(int userId) {
2515 // First make sure this user actually exists.
2516 if (mUserManager.getUserInfo(userId) == null) {
2517 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2518 return false;
2519 }
2520
Svetoslav683914b2015-01-15 14:22:26 -08002521 // Migrate the setting for this user if needed.
2522 migrateLegacySettingsForUserIfNeededLocked(userId);
2523
Matt Pape1b31a332018-10-17 09:58:28 -07002524 // Ensure config settings loaded if owner.
2525 if (userId == UserHandle.USER_SYSTEM) {
2526 final int configKey
2527 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2528 ensureSettingsStateLocked(configKey);
2529 }
2530
Svetoslav683914b2015-01-15 14:22:26 -08002531 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002532 if (userId == UserHandle.USER_SYSTEM) {
2533 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002534 ensureSettingsStateLocked(globalKey);
2535 }
2536
2537 // Ensure secure settings loaded.
2538 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2539 ensureSettingsStateLocked(secureKey);
2540
2541 // Make sure the secure settings have an Android id set.
2542 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2543 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2544
2545 // Ensure system settings loaded.
2546 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2547 ensureSettingsStateLocked(systemKey);
2548
Mark Rathjend891f012017-01-19 04:10:37 +00002549 // Ensure secure settings loaded.
2550 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2551 ensureSettingsStateLocked(ssaidKey);
2552
Svetoslav683914b2015-01-15 14:22:26 -08002553 // Upgrade the settings to the latest version.
2554 UpgradeController upgrader = new UpgradeController(userId);
2555 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002556 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002557 }
2558
2559 private void ensureSettingsStateLocked(int key) {
2560 if (mSettingsStates.get(key) == null) {
2561 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002562 SettingsState settingsState = new SettingsState(getContext(), mLock,
2563 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002564 mSettingsStates.put(key, settingsState);
2565 }
2566 }
2567
2568 public void removeUserStateLocked(int userId, boolean permanently) {
2569 // We always keep the global settings in memory.
2570
2571 // Nuke system settings.
2572 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2573 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2574 if (systemSettingsState != null) {
2575 if (permanently) {
2576 mSettingsStates.remove(systemKey);
2577 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002578 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002579 systemSettingsState.destroyLocked(new Runnable() {
2580 @Override
2581 public void run() {
2582 mSettingsStates.remove(systemKey);
2583 }
2584 });
2585 }
2586 }
2587
2588 // Nuke secure settings.
2589 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2590 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2591 if (secureSettingsState != null) {
2592 if (permanently) {
2593 mSettingsStates.remove(secureKey);
2594 secureSettingsState.destroyLocked(null);
2595 } else {
2596 secureSettingsState.destroyLocked(new Runnable() {
2597 @Override
2598 public void run() {
2599 mSettingsStates.remove(secureKey);
2600 }
2601 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002602 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002603 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002604
Mark Rathjend891f012017-01-19 04:10:37 +00002605 // Nuke ssaid settings.
2606 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2607 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2608 if (ssaidSettingsState != null) {
2609 if (permanently) {
2610 mSettingsStates.remove(ssaidKey);
2611 ssaidSettingsState.destroyLocked(null);
2612 } else {
2613 ssaidSettingsState.destroyLocked(new Runnable() {
2614 @Override
2615 public void run() {
2616 mSettingsStates.remove(ssaidKey);
2617 }
2618 });
2619 }
2620 }
2621
Svet Ganov53a441c2016-04-19 19:38:00 -07002622 // Nuke generation tracking data
2623 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002624 }
2625
Svetoslav683914b2015-01-15 14:22:26 -08002626 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002627 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2628 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002629 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2630 packageName, forceNotify, criticalSettings);
2631 }
2632
2633 public boolean insertSettingLocked(int type, int userId, String name, String value,
2634 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2635 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002636 final int key = makeKey(type, userId);
2637
Svetoslav Ganove080da92016-12-21 17:10:35 -08002638 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002639 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002640 if (settingsState != null) {
2641 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002642 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002643 }
Svetoslav683914b2015-01-15 14:22:26 -08002644
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002645 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2646 settingsState.persistSyncLocked();
2647 }
2648
Svet Ganov53a441c2016-04-19 19:38:00 -07002649 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002650 notifyForSettingsChange(key, name);
2651 }
2652 return success;
2653 }
2654
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002655 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2656 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002657 final int key = makeKey(type, userId);
2658
Svetoslav Ganove080da92016-12-21 17:10:35 -08002659 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002660 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002661 if (settingsState != null) {
2662 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002663 }
Svetoslav683914b2015-01-15 14:22:26 -08002664
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002665 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2666 settingsState.persistSyncLocked();
2667 }
2668
Svet Ganov53a441c2016-04-19 19:38:00 -07002669 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002670 notifyForSettingsChange(key, name);
2671 }
2672 return success;
2673 }
2674
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002675 public boolean updateSettingLocked(int type, int userId, String name, String value,
2676 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2677 Set<String> criticalSettings) {
2678 final int key = makeKey(type, userId);
2679
2680 boolean success = false;
2681 SettingsState settingsState = peekSettingsStateLocked(key);
2682 if (settingsState != null) {
2683 success = settingsState.updateSettingLocked(name, value, tag,
2684 makeDefault, packageName);
2685 }
2686
2687 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2688 settingsState.persistSyncLocked();
2689 }
2690
2691 if (forceNotify || success) {
2692 notifyForSettingsChange(key, name);
2693 }
2694
2695 return success;
2696 }
2697
Svetoslav683914b2015-01-15 14:22:26 -08002698 public Setting getSettingLocked(int type, int userId, String name) {
2699 final int key = makeKey(type, userId);
2700
2701 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002702 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002703 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002704 }
Mark Rathjend891f012017-01-19 04:10:37 +00002705
2706 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002707 return settingsState.getSettingLocked(name);
2708 }
2709
Svetoslav Ganove080da92016-12-21 17:10:35 -08002710 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2711 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002712 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2713 }
2714
2715 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2716 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002717 final int key = makeKey(type, userId);
2718 SettingsState settingsState = peekSettingsStateLocked(key);
2719 if (settingsState == null) {
2720 return;
2721 }
2722
2723 switch (mode) {
2724 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2725 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002726 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002727 Setting setting = settingsState.getSettingLocked(name);
2728 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002729 if ((tag != null && !tag.equals(setting.getTag()))
2730 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002731 continue;
2732 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002733 if (settingsState.resetSettingLocked(name)) {
2734 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002735 notifyForSettingsChange(key, name);
2736 }
2737 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002738 if (someSettingChanged) {
2739 settingsState.persistSyncLocked();
2740 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002741 }
2742 } break;
2743
2744 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2745 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002746 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002747 Setting setting = settingsState.getSettingLocked(name);
2748 if (!SettingsState.isSystemPackage(getContext(),
2749 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002750 if (prefix != null && !setting.getName().startsWith(prefix)) {
2751 continue;
2752 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002753 if (settingsState.resetSettingLocked(name)) {
2754 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002755 notifyForSettingsChange(key, name);
2756 }
2757 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002758 if (someSettingChanged) {
2759 settingsState.persistSyncLocked();
2760 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002761 }
2762 } break;
2763
2764 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2765 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002766 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002767 Setting setting = settingsState.getSettingLocked(name);
2768 if (!SettingsState.isSystemPackage(getContext(),
2769 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002770 if (prefix != null && !setting.getName().startsWith(prefix)) {
2771 continue;
2772 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002773 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002774 if (settingsState.resetSettingLocked(name)) {
2775 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002776 notifyForSettingsChange(key, name);
2777 }
2778 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002779 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002780 notifyForSettingsChange(key, name);
2781 }
2782 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002783 if (someSettingChanged) {
2784 settingsState.persistSyncLocked();
2785 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002786 }
2787 } break;
2788
2789 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2790 for (String name : settingsState.getSettingNamesLocked()) {
2791 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002792 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002793 if (prefix != null && !setting.getName().startsWith(prefix)) {
2794 continue;
2795 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002796 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002797 if (settingsState.resetSettingLocked(name)) {
2798 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002799 notifyForSettingsChange(key, name);
2800 }
2801 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002802 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002803 notifyForSettingsChange(key, name);
2804 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002805 if (someSettingChanged) {
2806 settingsState.persistSyncLocked();
2807 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002808 }
2809 } break;
2810 }
2811 }
2812
Zimuzoc56192c2018-07-25 10:40:01 +01002813 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002814 // Global and secure settings are signature protected. Apps signed
2815 // by the platform certificate are generally not uninstalled and
2816 // the main exception is tests. We trust components signed
2817 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002818
2819 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2820 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002821 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002822 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002823 }
Svetoslav683914b2015-01-15 14:22:26 -08002824 }
2825
Mark Rathjend891f012017-01-19 04:10:37 +00002826 public void onUidRemovedLocked(int uid) {
2827 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2828 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002829 if (ssaidSettings != null) {
2830 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2831 }
Mark Rathjend891f012017-01-19 04:10:37 +00002832 }
2833
Kweku Adamsb0886f32017-10-31 15:32:09 -07002834 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002835 private SettingsState peekSettingsStateLocked(int key) {
2836 SettingsState settingsState = mSettingsStates.get(key);
2837 if (settingsState != null) {
2838 return settingsState;
2839 }
2840
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002841 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2842 return null;
2843 }
Svetoslav683914b2015-01-15 14:22:26 -08002844 return mSettingsStates.get(key);
2845 }
2846
2847 private void migrateAllLegacySettingsIfNeeded() {
2848 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002849 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002850 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002851 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002852 return;
2853 }
2854
Amith Yamasani39452022017-03-21 15:23:47 -07002855 mSettingsCreationBuildId = Build.ID;
2856
Svetoslav683914b2015-01-15 14:22:26 -08002857 final long identity = Binder.clearCallingIdentity();
2858 try {
2859 List<UserInfo> users = mUserManager.getUsers(true);
2860
2861 final int userCount = users.size();
2862 for (int i = 0; i < userCount; i++) {
2863 final int userId = users.get(i).id;
2864
2865 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2866 SQLiteDatabase database = dbHelper.getWritableDatabase();
2867 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2868
2869 // Upgrade to the latest version.
2870 UpgradeController upgrader = new UpgradeController(userId);
2871 upgrader.upgradeIfNeededLocked();
2872
2873 // Drop from memory if not a running user.
2874 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2875 removeUserStateLocked(userId, false);
2876 }
2877 }
2878 } finally {
2879 Binder.restoreCallingIdentity(identity);
2880 }
2881 }
2882 }
2883
2884 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2885 // Every user has secure settings and if no file we need to migrate.
2886 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2887 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002888 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002889 return;
2890 }
2891
2892 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2893 SQLiteDatabase database = dbHelper.getWritableDatabase();
2894
2895 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2896 }
2897
2898 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2899 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002900 // Move over the system settings.
2901 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2902 ensureSettingsStateLocked(systemKey);
2903 SettingsState systemSettings = mSettingsStates.get(systemKey);
2904 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2905 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002906
2907 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002908 // Do this after System settings, since this is the first thing we check when deciding
2909 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002910 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2911 ensureSettingsStateLocked(secureKey);
2912 SettingsState secureSettings = mSettingsStates.get(secureKey);
2913 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2914 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2915 secureSettings.persistSyncLocked();
2916
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002917 // Move over the global settings if owner.
2918 // Do this last, since this is the first thing we check when deciding
2919 // to skip over migration from db to xml for owner user.
2920 if (userId == UserHandle.USER_SYSTEM) {
2921 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2922 ensureSettingsStateLocked(globalKey);
2923 SettingsState globalSettings = mSettingsStates.get(globalKey);
2924 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002925 // If this was just created
2926 if (mSettingsCreationBuildId != null) {
2927 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2928 mSettingsCreationBuildId, null, true,
2929 SettingsState.SYSTEM_PACKAGE_NAME);
2930 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002931 globalSettings.persistSyncLocked();
2932 }
Svetoslav683914b2015-01-15 14:22:26 -08002933
2934 // Drop the database as now all is moved and persisted.
2935 if (DROP_DATABASE_ON_MIGRATION) {
2936 dbHelper.dropDatabase();
2937 } else {
2938 dbHelper.backupDatabase();
2939 }
2940 }
2941
2942 private void migrateLegacySettingsLocked(SettingsState settingsState,
2943 SQLiteDatabase database, String table) {
2944 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2945 queryBuilder.setTables(table);
2946
2947 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2948 null, null, null, null, null);
2949
2950 if (cursor == null) {
2951 return;
2952 }
2953
2954 try {
2955 if (!cursor.moveToFirst()) {
2956 return;
2957 }
2958
2959 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2960 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2961
2962 settingsState.setVersionLocked(database.getVersion());
2963
2964 while (!cursor.isAfterLast()) {
2965 String name = cursor.getString(nameColumnIdx);
2966 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002967 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002968 SettingsState.SYSTEM_PACKAGE_NAME);
2969 cursor.moveToNext();
2970 }
2971 } finally {
2972 cursor.close();
2973 }
2974 }
2975
Andreas Gampeb58893072018-09-05 16:52:31 -07002976 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002977 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2978 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2979
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002980 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002981 return;
2982 }
2983
2984 final int userId = getUserIdFromKey(secureSettings.mKey);
2985
2986 final UserInfo user;
2987 final long identity = Binder.clearCallingIdentity();
2988 try {
2989 user = mUserManager.getUserInfo(userId);
2990 } finally {
2991 Binder.restoreCallingIdentity(identity);
2992 }
2993 if (user == null) {
2994 // Can happen due to races when deleting users - treat as benign.
2995 return;
2996 }
2997
2998 String androidId = Long.toHexString(new SecureRandom().nextLong());
2999 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003000 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003001
3002 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3003 + "] for user " + userId);
3004
3005 // Write a drop box entry if it's a restricted profile
3006 if (user.isRestricted()) {
3007 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3008 Context.DROPBOX_SERVICE);
3009 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3010 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3011 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3012 }
3013 }
3014 }
3015
3016 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003017 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003018 mGenerationRegistry.incrementGeneration(key);
3019
Svet Ganov945864c2018-03-22 21:49:10 -07003020 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003021 final long token = Binder.clearCallingIdentity();
3022 try {
3023 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3024 // When the global kill switch is updated, send the
3025 // change notification for the location setting.
3026 notifyLocationChangeForRunningUsers();
3027 }
3028 notifyGlobalSettingChangeForRunningUsers(key, name);
3029 } finally {
3030 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003031 }
Svet Ganov945864c2018-03-22 21:49:10 -07003032 } else {
3033 final int userId = getUserIdFromKey(key);
3034 final Uri uri = getNotificationUriFor(key, name);
3035 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3036 userId, 0, uri).sendToTarget();
3037 if (isSecureSettingsKey(key)) {
3038 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3039 sSecureCloneToManagedSettings);
3040 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3041 sSystemCloneFromParentOnDependency.values());
3042 } else if (isSystemSettingsKey(key)) {
3043 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3044 sSystemCloneToManagedSettings);
3045 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003046 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003047
Svet Ganov945864c2018-03-22 21:49:10 -07003048 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003049 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003050 }
3051
Svet Ganov53a441c2016-04-19 19:38:00 -07003052 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003053 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003054 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003055 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003056 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003057 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003058 final int key = makeKey(type, profileId);
3059 // Increment the generation first, so observers always see the new value
3060 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003061 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003062 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003063 }
3064 }
3065 }
Svetoslav683914b2015-01-15 14:22:26 -08003066 }
3067
Svet Ganov945864c2018-03-22 21:49:10 -07003068 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3069 // Important: No need to update generation for each user as there
3070 // is a singleton generation entry for the global settings which
3071 // is already incremented be the caller.
3072 final Uri uri = getNotificationUriFor(key, name);
3073 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3074 for (int i = 0; i < users.size(); i++) {
3075 final int userId = users.get(i).id;
3076 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3077 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3078 userId, 0, uri).sendToTarget();
3079 }
3080 }
3081 }
3082
Makoto Onuki0000d322017-11-28 16:31:47 -08003083 private void notifyLocationChangeForRunningUsers() {
3084 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3085
3086 for (int i = 0; i < users.size(); i++) {
3087 final int userId = users.get(i).id;
3088
3089 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3090 continue;
3091 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003092
Svet Ganov945864c2018-03-22 21:49:10 -07003093 // Increment the generation first, so observers always see the new value
3094 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3095 mGenerationRegistry.incrementGeneration(key);
3096
3097 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003098 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3099 userId, 0, uri).sendToTarget();
3100 }
3101 }
3102
Matt Pape1b31a332018-10-17 09:58:28 -07003103 private boolean isConfigSettingsKey(int key) {
3104 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3105 }
3106
Svetoslav683914b2015-01-15 14:22:26 -08003107 private boolean isGlobalSettingsKey(int key) {
3108 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3109 }
3110
3111 private boolean isSystemSettingsKey(int key) {
3112 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3113 }
3114
3115 private boolean isSecureSettingsKey(int key) {
3116 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3117 }
3118
Mark Rathjend891f012017-01-19 04:10:37 +00003119 private boolean isSsaidSettingsKey(int key) {
3120 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3121 }
3122
Svetoslav683914b2015-01-15 14:22:26 -08003123 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003124 if (isConfigSettingsKey(key)) {
3125 final int userId = getUserIdFromKey(key);
3126 return new File(Environment.getUserSystemDirectory(userId),
3127 SETTINGS_FILE_CONFIG);
3128 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003129 final int userId = getUserIdFromKey(key);
3130 return new File(Environment.getUserSystemDirectory(userId),
3131 SETTINGS_FILE_GLOBAL);
3132 } else if (isSystemSettingsKey(key)) {
3133 final int userId = getUserIdFromKey(key);
3134 return new File(Environment.getUserSystemDirectory(userId),
3135 SETTINGS_FILE_SYSTEM);
3136 } else if (isSecureSettingsKey(key)) {
3137 final int userId = getUserIdFromKey(key);
3138 return new File(Environment.getUserSystemDirectory(userId),
3139 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003140 } else if (isSsaidSettingsKey(key)) {
3141 final int userId = getUserIdFromKey(key);
3142 return new File(Environment.getUserSystemDirectory(userId),
3143 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003144 } else {
3145 throw new IllegalArgumentException("Invalid settings key:" + key);
3146 }
3147 }
3148
3149 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003150 if (isConfigSettingsKey(key)) {
3151 return (name != null) ? Uri.withAppendedPath(CONFIG_CONTENT_URI, name)
3152 : CONFIG_CONTENT_URI;
3153 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003154 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3155 : Settings.Global.CONTENT_URI;
3156 } else if (isSecureSettingsKey(key)) {
3157 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3158 : Settings.Secure.CONTENT_URI;
3159 } else if (isSystemSettingsKey(key)) {
3160 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3161 : Settings.System.CONTENT_URI;
3162 } else {
3163 throw new IllegalArgumentException("Invalid settings key:" + key);
3164 }
3165 }
3166
3167 private int getMaxBytesPerPackageForType(int type) {
3168 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003169 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003170 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003171 case SETTINGS_TYPE_SECURE:
3172 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003173 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3174 }
3175
3176 default: {
3177 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3178 }
3179 }
3180 }
3181
Svetoslav7e0683b2015-08-03 16:02:52 -07003182 private final class MyHandler extends Handler {
3183 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3184 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3185
3186 public MyHandler(Looper looper) {
3187 super(looper);
3188 }
3189
3190 @Override
3191 public void handleMessage(Message msg) {
3192 switch (msg.what) {
3193 case MSG_NOTIFY_URI_CHANGED: {
3194 final int userId = msg.arg1;
3195 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003196 try {
3197 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3198 } catch (SecurityException e) {
3199 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3200 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003201 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003202 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3203 }
3204 } break;
3205
3206 case MSG_NOTIFY_DATA_CHANGED: {
3207 mBackupManager.dataChanged();
3208 } break;
3209 }
3210 }
3211 }
3212
Svetoslav683914b2015-01-15 14:22:26 -08003213 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003214 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003215
3216 private final int mUserId;
3217
3218 public UpgradeController(int userId) {
3219 mUserId = userId;
3220 }
3221
3222 public void upgradeIfNeededLocked() {
3223 // The version of all settings for a user is the same (all users have secure).
3224 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003225 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003226
3227 // Try an update from the current state.
3228 final int oldVersion = secureSettings.getVersionLocked();
3229 final int newVersion = SETTINGS_VERSION;
3230
Svet Ganovc9755bc2015-03-28 13:21:22 -07003231 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003232 if (oldVersion == newVersion) {
3233 return;
3234 }
3235
3236 // Try to upgrade.
3237 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3238
3239 // If upgrade failed start from scratch and upgrade.
3240 if (curVersion != newVersion) {
3241 // Drop state we have for this user.
3242 removeUserStateLocked(mUserId, true);
3243
3244 // Recreate the database.
3245 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3246 SQLiteDatabase database = dbHelper.getWritableDatabase();
3247 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3248
3249 // Migrate the settings for this user.
3250 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3251
3252 // Now upgrade should work fine.
3253 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003254
3255 // Make a note what happened, so we don't wonder why data was lost
3256 String reason = "Settings rebuilt! Current version: "
3257 + curVersion + " while expected: " + newVersion;
3258 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003259 Settings.Global.DATABASE_DOWNGRADE_REASON,
3260 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003261 }
3262
3263 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003264 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003265 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003266 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003267 globalSettings.setVersionLocked(newVersion);
3268 }
3269
3270 // Set the secure settings version.
3271 secureSettings.setVersionLocked(newVersion);
3272
3273 // Set the system settings version.
3274 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003275 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003276 systemSettings.setVersionLocked(newVersion);
3277 }
3278
3279 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003280 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003281 }
3282
3283 private SettingsState getSecureSettingsLocked(int userId) {
3284 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3285 }
3286
Mark Rathjend891f012017-01-19 04:10:37 +00003287 private SettingsState getSsaidSettingsLocked(int userId) {
3288 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3289 }
3290
Svetoslav683914b2015-01-15 14:22:26 -08003291 private SettingsState getSystemSettingsLocked(int userId) {
3292 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3293 }
3294
Jeff Brown503cffc2015-03-26 18:08:51 -07003295 /**
3296 * You must perform all necessary mutations to bring the settings
3297 * for this user from the old to the new version. When you add a new
3298 * upgrade step you *must* update SETTINGS_VERSION.
3299 *
3300 * This is an example of moving a setting from secure to global.
3301 *
3302 * // v119: Example settings changes.
3303 * if (currentVersion == 118) {
3304 * if (userId == UserHandle.USER_OWNER) {
3305 * // Remove from the secure settings.
3306 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3307 * String name = "example_setting_to_move";
3308 * String value = secureSettings.getSetting(name);
3309 * secureSettings.deleteSetting(name);
3310 *
3311 * // Add to the global settings.
3312 * SettingsState globalSettings = getGlobalSettingsLocked();
3313 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3314 * }
3315 *
3316 * // Update the current version.
3317 * currentVersion = 119;
3318 * }
3319 */
Svetoslav683914b2015-01-15 14:22:26 -08003320 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3321 if (DEBUG) {
3322 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3323 + oldVersion + " to version: " + newVersion);
3324 }
3325
Jeff Brown503cffc2015-03-26 18:08:51 -07003326 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003327
John Spurlocke11ae112015-05-11 16:09:03 -04003328 // v119: Reset zen + ringer mode.
3329 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003330 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003331 final SettingsState globalSettings = getGlobalSettingsLocked();
3332 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003333 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3334 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003335 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003336 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3337 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003338 }
3339 currentVersion = 119;
3340 }
3341
Jason Monk27bbb2d2015-03-31 16:46:39 -04003342 // v120: Add double tap to wake setting.
3343 if (currentVersion == 119) {
3344 SettingsState secureSettings = getSecureSettingsLocked(userId);
3345 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3346 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003347 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003348 SettingsState.SYSTEM_PACKAGE_NAME);
3349
3350 currentVersion = 120;
3351 }
3352
Svetoslav7e0683b2015-08-03 16:02:52 -07003353 if (currentVersion == 120) {
3354 // Before 121, we used a different string encoding logic. We just bump the
3355 // version here; SettingsState knows how to handle pre-version 120 files.
3356 currentVersion = 121;
3357 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003358
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003359 if (currentVersion == 121) {
3360 // Version 122: allow OEMs to set a default payment component in resources.
3361 // Note that we only write the default if no default has been set;
3362 // if there is, we just leave the default at whatever it currently is.
3363 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3364 String defaultComponent = (getContext().getResources().getString(
3365 R.string.def_nfc_payment_component));
3366 Setting currentSetting = secureSettings.getSettingLocked(
3367 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3368 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003369 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003370 secureSettings.insertSettingLocked(
3371 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003372 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003373 }
3374 currentVersion = 122;
3375 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003376
3377 if (currentVersion == 122) {
3378 // Version 123: Adding a default value for the ability to add a user from
3379 // the lock screen.
3380 if (userId == UserHandle.USER_SYSTEM) {
3381 final SettingsState globalSettings = getGlobalSettingsLocked();
3382 Setting currentSetting = globalSettings.getSettingLocked(
3383 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003384 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003385 globalSettings.insertSettingLocked(
3386 Settings.Global.ADD_USERS_WHEN_LOCKED,
3387 getContext().getResources().getBoolean(
3388 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003389 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003390 }
3391 }
3392 currentVersion = 123;
3393 }
Bryce Leebd179282015-12-17 19:01:37 -08003394
3395 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003396 final SettingsState globalSettings = getGlobalSettingsLocked();
3397 String defaultDisabledProfiles = (getContext().getResources().getString(
3398 R.string.def_bluetooth_disabled_profiles));
3399 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003400 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003401 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003402 }
3403
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003404 if (currentVersion == 124) {
3405 // Version 124: allow OEMs to set a default value for whether IME should be
3406 // shown when a physical keyboard is connected.
3407 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3408 Setting currentSetting = secureSettings.getSettingLocked(
3409 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003410 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003411 secureSettings.insertSettingLocked(
3412 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3413 getContext().getResources().getBoolean(
3414 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003415 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003416 }
3417 currentVersion = 125;
3418 }
3419
Ruben Brunk98576cf2016-03-07 18:54:28 -08003420 if (currentVersion == 125) {
3421 // Version 125: Allow OEMs to set the default VR service.
3422 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3423
3424 Setting currentSetting = secureSettings.getSettingLocked(
3425 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003426 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003427 ArraySet<ComponentName> l =
3428 SystemConfig.getInstance().getDefaultVrComponents();
3429
3430 if (l != null && !l.isEmpty()) {
3431 StringBuilder b = new StringBuilder();
3432 boolean start = true;
3433 for (ComponentName c : l) {
3434 if (!start) {
3435 b.append(':');
3436 }
3437 b.append(c.flattenToString());
3438 start = false;
3439 }
3440 secureSettings.insertSettingLocked(
3441 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003442 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003443 }
3444
3445 }
3446 currentVersion = 126;
3447 }
3448
Daniel U02ba6122016-04-01 18:41:42 +01003449 if (currentVersion == 126) {
3450 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3451 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3452 if (mUserManager.isManagedProfile(userId)) {
3453 final SettingsState systemSecureSettings =
3454 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3455
3456 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3457 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003458 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003459 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3460 secureSettings.insertSettingLocked(
3461 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003462 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003463 SettingsState.SYSTEM_PACKAGE_NAME);
3464 }
3465
3466 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3467 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003468 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003469 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3470 secureSettings.insertSettingLocked(
3471 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003472 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003473 SettingsState.SYSTEM_PACKAGE_NAME);
3474 }
3475 }
3476 currentVersion = 127;
3477 }
3478
Steven Ngdc20ba62016-04-26 18:19:04 +01003479 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003480 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003481 currentVersion = 128;
3482 }
3483
Julia Reynolds1f721e12016-07-11 08:50:58 -04003484 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003485 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003486 currentVersion = 129;
3487 }
3488
Dan Sandler71f85e92016-07-20 13:46:05 -04003489 if (currentVersion == 129) {
3490 // default longpress timeout changed from 500 to 400. If unchanged from the old
3491 // default, update to the new default.
3492 final SettingsState systemSecureSettings =
3493 getSecureSettingsLocked(userId);
3494 final String oldValue = systemSecureSettings.getSettingLocked(
3495 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3496 if (TextUtils.equals("500", oldValue)) {
3497 systemSecureSettings.insertSettingLocked(
3498 Settings.Secure.LONG_PRESS_TIMEOUT,
3499 String.valueOf(getContext().getResources().getInteger(
3500 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003501 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003502 }
3503 currentVersion = 130;
3504 }
3505
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003506 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003507 // Split Ambient settings
3508 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3509 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3510 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3511
3512 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003513 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003514 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003515 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003516 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003517 }
3518 currentVersion = 131;
3519 }
3520
3521 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003522 // Initialize new multi-press timeout to default value
3523 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3524 final String oldValue = systemSecureSettings.getSettingLocked(
3525 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3526 if (TextUtils.equals(null, oldValue)) {
3527 systemSecureSettings.insertSettingLocked(
3528 Settings.Secure.MULTI_PRESS_TIMEOUT,
3529 String.valueOf(getContext().getResources().getInteger(
3530 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003531 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003532 }
3533
Adrian Roos69741a22016-10-21 14:49:17 -07003534 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003535 }
3536
Adrian Roos69741a22016-10-21 14:49:17 -07003537 if (currentVersion == 132) {
3538 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003539 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3540 String defaultSyncParentSounds = (getContext().getResources()
3541 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3542 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003543 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3544 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003545 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003546 }
3547
Adrian Roos69741a22016-10-21 14:49:17 -07003548 if (currentVersion == 133) {
3549 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003550 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003551 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3552 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003553 String defaultEndButtonBehavior = Integer.toString(getContext()
3554 .getResources().getInteger(R.integer.def_end_button_behavior));
3555 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003556 defaultEndButtonBehavior, null, true,
3557 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003558 }
Adrian Roos69741a22016-10-21 14:49:17 -07003559 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003560 }
3561
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003562 if (currentVersion == 134) {
3563 // Remove setting that specifies if magnification values should be preserved.
3564 // This setting defaulted to true and never has a UI.
3565 getSecureSettingsLocked(userId).deleteSettingLocked(
3566 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3567 currentVersion = 135;
3568 }
3569
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003570 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003571 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003572 currentVersion = 136;
3573 }
3574
Mark Rathjend891f012017-01-19 04:10:37 +00003575 if (currentVersion == 136) {
3576 // Version 136: Store legacy SSAID for all apps currently installed on the
3577 // device as first step in migrating SSAID to be unique per application.
3578
3579 final boolean isUpgrade;
3580 try {
3581 isUpgrade = mPackageManager.isUpgrade();
3582 } catch (RemoteException e) {
3583 throw new IllegalStateException("Package manager not available");
3584 }
3585 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3586 // user data or first boot on a new device should use new ssaid generation.
3587 if (isUpgrade) {
3588 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003589 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3590 userId, Settings.Secure.ANDROID_ID);
3591 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3592 || legacySsaidSetting.getValue() == null) {
3593 throw new IllegalStateException("Legacy ssaid not accessible");
3594 }
3595 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003596
3597 // Fill each uid with the legacy ssaid to be backwards compatible.
3598 final List<PackageInfo> packages;
3599 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003600 packages = mPackageManager.getInstalledPackages(
3601 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3602 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003603 } catch (RemoteException e) {
3604 throw new IllegalStateException("Package manager not available");
3605 }
3606
3607 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3608 for (PackageInfo info : packages) {
3609 // Check if the UID already has an entry in the table.
3610 final String uid = Integer.toString(info.applicationInfo.uid);
3611 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3612
3613 if (ssaid.isNull() || ssaid.getValue() == null) {
3614 // Android Id doesn't exist for this package so create it.
3615 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3616 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003617 if (DEBUG) {
3618 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3619 }
Mark Rathjend891f012017-01-19 04:10:37 +00003620 }
3621 }
3622 }
3623
3624 currentVersion = 137;
3625 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003626 if (currentVersion == 137) {
3627 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3628 // default value set to 1. The user can no longer change the value of this
3629 // setting through the UI.
3630 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3631 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003632 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3633 && secureSetting.getSettingLocked(
3634 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3635
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003636 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3637 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003638 // For managed profiles with profile owners, DevicePolicyManagerService
3639 // may want to set the user restriction in this case
3640 secureSetting.insertSettingLocked(
3641 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3642 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003643 }
3644 currentVersion = 138;
3645 }
Mark Rathjend891f012017-01-19 04:10:37 +00003646
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003647 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003648 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003649 currentVersion = 139;
3650 }
3651
Phil Weaver385912e2017-02-10 10:06:56 -08003652 if (currentVersion == 139) {
3653 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3654 // the user can no longer change the value of this setting through the UI.
3655 // Force to true.
3656 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3657 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3658 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3659 currentVersion = 140;
3660 }
3661
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003662 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003663 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003664 currentVersion = 141;
3665 }
3666
Svet Ganov13701552017-02-23 12:45:17 -08003667 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003668 // This implementation was incorrectly setting the current value of
3669 // settings changed by non-system packages as the default which default
3670 // is set by the system. We add a new upgrade step at the end to properly
3671 // handle this case which would also fix incorrect changes made by the
3672 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003673 currentVersion = 142;
3674 }
3675
Stephen Chen5d0922f2017-03-27 10:28:04 -07003676 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003677 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003678 if (userId == UserHandle.USER_SYSTEM) {
3679 final SettingsState globalSettings = getGlobalSettingsLocked();
3680 Setting currentSetting = globalSettings.getSettingLocked(
3681 Settings.Global.WIFI_WAKEUP_ENABLED);
3682 if (currentSetting.isNull()) {
3683 globalSettings.insertSettingLocked(
3684 Settings.Global.WIFI_WAKEUP_ENABLED,
3685 getContext().getResources().getBoolean(
3686 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3687 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3688 }
3689 }
3690
3691 currentVersion = 143;
3692 }
3693
Felipe Lemeff355092017-04-03 12:55:02 -07003694 if (currentVersion == 143) {
3695 // Version 144: Set a default value for Autofill service.
3696 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3697 final Setting currentSetting = secureSettings
3698 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3699 if (currentSetting.isNull()) {
3700 final String defaultValue = getContext().getResources().getString(
3701 com.android.internal.R.string.config_defaultAutofillService);
3702 if (defaultValue != null) {
3703 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3704 + "for user " + userId);
3705 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3706 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3707 }
3708 }
3709
3710 currentVersion = 144;
3711 }
3712
Jeremy Joslin45caa252017-05-04 11:22:46 -07003713 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003714 // Version 145: Removed
3715 currentVersion = 145;
3716 }
3717
3718 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003719 // Version 146: In step 142 we had a bug where incorrectly
3720 // some settings were considered system set and as a result
3721 // made the default and marked as the default being set by
3722 // the system. Here reevaluate the default and default system
3723 // set flags. This would both fix corruption by the old impl
3724 // of step 142 and also properly handle devices which never
3725 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003726 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003727 SettingsState globalSettings = getGlobalSettingsLocked();
3728 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3729 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003730 }
3731
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003732 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3733 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3734 secureSettings.persistSyncLocked();
3735
3736 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3737 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3738 systemSettings.persistSyncLocked();
3739
Amin Shaikh86367962017-06-07 08:58:22 -07003740 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003741 }
3742
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003743 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003744 // Version 147: Removed. (This version previously allowed showing the
3745 // "wifi_wakeup_available" setting).
3746 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003747 currentVersion = 147;
3748 }
3749
3750 if (currentVersion == 147) {
3751 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003752 if (userId == UserHandle.USER_SYSTEM) {
3753 final SettingsState globalSettings = getGlobalSettingsLocked();
3754 final Setting currentSetting = globalSettings.getSettingLocked(
3755 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3756 if (currentSetting.isNull()) {
3757 globalSettings.insertSettingLocked(
3758 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3759 getContext().getResources().getBoolean(
3760 R.bool.def_restrict_background_data) ? "1" : "0",
3761 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3762 }
3763 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003764 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003765 }
3766
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003767 if (currentVersion == 148) {
3768 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3769 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3770 final String oldValue = systemSecureSettings.getSettingLocked(
3771 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3772 if (TextUtils.equals(null, oldValue)) {
3773 final String defaultValue = getContext().getResources().getString(
3774 R.string.def_backup_manager_constants);
3775 if (!TextUtils.isEmpty(defaultValue)) {
3776 systemSecureSettings.insertSettingLocked(
3777 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3778 true, SettingsState.SYSTEM_PACKAGE_NAME);
3779 }
3780 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003781 currentVersion = 149;
3782 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003783
3784 if (currentVersion == 149) {
3785 // Version 150: Set a default value for mobile data always on
3786 final SettingsState globalSettings = getGlobalSettingsLocked();
3787 final Setting currentSetting = globalSettings.getSettingLocked(
3788 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3789 if (currentSetting.isNull()) {
3790 globalSettings.insertSettingLocked(
3791 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3792 getContext().getResources().getBoolean(
3793 R.bool.def_mobile_data_always_on) ? "1" : "0",
3794 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3795 }
3796
3797 currentVersion = 150;
3798 }
3799
Mike Digman4af4a6f2018-01-16 14:49:38 -08003800 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003801 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003802 currentVersion = 151;
3803 }
3804
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003805 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003806 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3807 // by default but it is now no longer configurable).
3808 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003809 currentVersion = 152;
3810 }
3811
Joe LaPenna250d7842018-01-25 10:19:42 -08003812 if (currentVersion == 152) {
3813 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3814 currentVersion = 153;
3815 }
3816
Ben Linb4df8bc2018-01-29 11:48:20 -08003817 if (currentVersion == 153) {
3818 // Version 154: Read notification badge configuration from config.
3819 // If user has already set the value, don't do anything.
3820 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3821 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3822 Settings.Secure.NOTIFICATION_BADGING);
3823 if (showNotificationBadges.isNull()) {
3824 final boolean defaultValue = getContext().getResources().getBoolean(
3825 com.android.internal.R.bool.config_notificationBadging);
3826 systemSecureSettings.insertSettingLocked(
3827 Secure.NOTIFICATION_BADGING,
3828 defaultValue ? "1" : "0",
3829 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3830 }
3831 currentVersion = 154;
3832 }
3833
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003834 if (currentVersion == 154) {
3835 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3836 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3837 final String oldValue = systemSecureSettings.getSettingLocked(
3838 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3839 if (TextUtils.equals(null, oldValue)) {
3840 final String defaultValue = getContext().getResources().getString(
3841 R.string.def_backup_local_transport_parameters);
3842 if (!TextUtils.isEmpty(defaultValue)) {
3843 systemSecureSettings.insertSettingLocked(
3844 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3845 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3846 }
3847
3848 }
3849 currentVersion = 155;
3850 }
3851
Beverlyda904812018-03-02 09:55:30 -05003852 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003853 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003854 final SettingsState globalSettings = getGlobalSettingsLocked();
3855 final String oldValue = globalSettings.getSettingLocked(
3856 Global.CHARGING_STARTED_SOUND).getValue();
3857 final String oldDefault = getContext().getResources().getString(
3858 R.string.def_wireless_charging_started_sound);
3859 if (TextUtils.equals(null, oldValue)
3860 || TextUtils.equals(oldValue, oldDefault)) {
3861 final String defaultValue = getContext().getResources().getString(
3862 R.string.def_charging_started_sound);
3863 if (!TextUtils.isEmpty(defaultValue)) {
3864 globalSettings.insertSettingLocked(
3865 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3866 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3867 }
3868
3869 }
3870 currentVersion = 156;
3871 }
3872
Beverly09da25f2018-02-26 09:17:07 -05003873 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003874 // Version 157: Set a default value for zen duration,
3875 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003876 final SettingsState globalSettings = getGlobalSettingsLocked();
3877 final Setting currentSetting = globalSettings.getSettingLocked(
3878 Global.ZEN_DURATION);
3879 if (currentSetting.isNull()) {
3880 String defaultZenDuration = Integer.toString(getContext()
3881 .getResources().getInteger(R.integer.def_zen_duration));
3882 globalSettings.insertSettingLocked(
3883 Global.ZEN_DURATION, defaultZenDuration,
3884 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3885 }
Beverly09da25f2018-02-26 09:17:07 -05003886 currentVersion = 157;
3887 }
Annie Mengd069a882018-03-13 15:31:40 +00003888
3889 if (currentVersion == 157) {
3890 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3891 final SettingsState globalSettings = getGlobalSettingsLocked();
3892 final String oldValue = globalSettings.getSettingLocked(
3893 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3894 if (TextUtils.equals(null, oldValue)) {
3895 final String defaultValue = getContext().getResources().getString(
3896 R.string.def_backup_agent_timeout_parameters);
3897 if (!TextUtils.isEmpty(defaultValue)) {
3898 globalSettings.insertSettingLocked(
3899 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3900 null, true,
3901 SettingsState.SYSTEM_PACKAGE_NAME);
3902 }
3903 }
3904 currentVersion = 158;
3905 }
Roshan Pius9c396672018-03-02 14:54:13 -08003906
3907 if (currentVersion == 158) {
3908 // Remove setting that specifies wifi bgscan throttling params
3909 getGlobalSettingsLocked().deleteSettingLocked(
3910 "wifi_scan_background_throttle_interval_ms");
3911 getGlobalSettingsLocked().deleteSettingLocked(
3912 "wifi_scan_background_throttle_package_whitelist");
3913 currentVersion = 159;
3914 }
3915
Pavel Grafovc5c97302018-03-19 13:37:15 +00003916 if (currentVersion == 159) {
3917 // Version 160: Hiding notifications from the lockscreen is only available as
3918 // primary user option, profiles can only make them redacted. If a profile was
3919 // configured to not show lockscreen notifications, ensure that at the very
3920 // least these will be come hidden.
3921 if (mUserManager.isManagedProfile(userId)) {
3922 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3923 Setting showNotifications = secureSettings.getSettingLocked(
3924 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3925 // The default value is "1", check if user has turned it off.
3926 if ("0".equals(showNotifications.getValue())) {
3927 secureSettings.insertSettingLocked(
3928 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3929 null /* tag */, false /* makeDefault */,
3930 SettingsState.SYSTEM_PACKAGE_NAME);
3931 }
3932 // The setting is no longer valid for managed profiles, it should be
3933 // treated as if it was set to "1".
3934 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3935 }
3936 currentVersion = 160;
3937 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003938
3939 if (currentVersion == 160) {
3940 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003941 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003942 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3943 final SettingsState globalSettings = getGlobalSettingsLocked();
3944
3945 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003946 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3947 if (TextUtils.equals(null, oldValue)) {
3948 globalSettings.insertSettingLocked(
3949 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3950 Integer.toString(getContext().getResources().getInteger(
3951 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3952 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3953 }
3954
3955 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003956 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3957 if (TextUtils.equals(null, oldValue)) {
3958 globalSettings.insertSettingLocked(
3959 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3960 Integer.toString(getContext().getResources().getInteger(
3961 R.integer.def_sound_trigger_detection_service_op_timeout)),
3962 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3963 }
3964 currentVersion = 161;
3965 }
3966
Mike Digman55272862018-02-20 14:35:17 -08003967 if (currentVersion == 161) {
3968 // Version 161: Add a gesture for silencing phones
3969 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3970 final Setting currentSetting = secureSettings.getSettingLocked(
3971 Secure.VOLUME_HUSH_GESTURE);
3972 if (currentSetting.isNull()) {
3973 secureSettings.insertSettingLocked(
3974 Secure.VOLUME_HUSH_GESTURE,
3975 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3976 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3977 }
3978
3979 currentVersion = 162;
3980 }
3981
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003982 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003983 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003984 currentVersion = 163;
3985 }
3986
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003987 if (currentVersion == 163) {
3988 // Version 163: Update default value of
3989 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3990 final SettingsState settings = getGlobalSettingsLocked();
3991 final Setting currentSetting = settings.getSettingLocked(
3992 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3993 if (currentSetting.isDefaultFromSystem()) {
3994 settings.insertSettingLocked(
3995 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3996 Integer.toString(getContext().getResources().getInteger(
3997 R.integer
3998 .def_max_sound_trigger_detection_service_ops_per_day)),
3999 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4000 }
4001
4002 currentVersion = 164;
4003 }
4004
Julia Reynolds76bfa602018-04-23 09:38:47 -04004005 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004006 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004007 currentVersion = 165;
4008 }
4009
Beverly301e92a2018-04-27 09:43:05 -04004010 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004011 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4012 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004013 currentVersion = 166;
4014 }
4015
Beverly38fcfd02018-05-18 17:33:40 -04004016 if (currentVersion == 166) {
4017 // Version 166: add default values for hush gesture used and manual ringer
4018 // toggle
4019 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4020 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4021 Secure.HUSH_GESTURE_USED);
4022 if (currentHushUsedSetting.isNull()) {
4023 secureSettings.insertSettingLocked(
4024 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4025 SettingsState.SYSTEM_PACKAGE_NAME);
4026 }
4027
4028 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4029 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4030 if (currentRingerToggleCountSetting.isNull()) {
4031 secureSettings.insertSettingLocked(
4032 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4033 SettingsState.SYSTEM_PACKAGE_NAME);
4034 }
4035 currentVersion = 167;
4036 }
4037
Beverly155c9d22018-05-23 18:03:23 -04004038 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004039 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4040 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004041 currentVersion = 168;
4042 }
4043
Michael Wright0e9eeee2018-05-26 00:31:20 +01004044 if (currentVersion == 168) {
4045 // Version 168: by default, vibrate for phone calls
4046 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4047 final Setting currentSetting = systemSettings.getSettingLocked(
4048 Settings.System.VIBRATE_WHEN_RINGING);
4049 if (currentSetting.isNull()) {
4050 systemSettings.insertSettingLocked(
4051 Settings.System.VIBRATE_WHEN_RINGING,
4052 getContext().getResources().getBoolean(
4053 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4054 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4055 }
4056 currentVersion = 169;
4057 }
4058
Nadav Barf9f115d2018-06-24 10:06:50 +03004059 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004060 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4061 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4062 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004063
Beverly91d0a632018-07-02 16:45:00 -04004064 final SettingsState globalSettings = getGlobalSettingsLocked();
4065 final Setting globalZenDuration = globalSettings.getSettingLocked(
4066 Global.ZEN_DURATION);
4067
4068 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4069 final Setting secureZenDuration = secureSettings.getSettingLocked(
4070 Secure.ZEN_DURATION);
4071
4072 // ZEN_DURATION
4073 if (!globalZenDuration.isNull()) {
4074 secureSettings.insertSettingLocked(
4075 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4076 SettingsState.SYSTEM_PACKAGE_NAME);
4077
4078 // set global zen duration setting to null since it's deprecated
4079 globalSettings.insertSettingLocked(
4080 Global.ZEN_DURATION, null, null, true,
4081 SettingsState.SYSTEM_PACKAGE_NAME);
4082 } else if (secureZenDuration.isNull()) {
4083 String defaultZenDuration = Integer.toString(getContext()
4084 .getResources().getInteger(R.integer.def_zen_duration));
4085 secureSettings.insertSettingLocked(
4086 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4087 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004088 }
Beverly91d0a632018-07-02 16:45:00 -04004089
4090 // SHOW_ZEN_SETTINGS_SUGGESTION
4091 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4092 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4093 if (currentShowZenSettingSuggestion.isNull()) {
4094 secureSettings.insertSettingLocked(
4095 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4096 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4097 }
4098
4099 // ZEN_SETTINGS_UPDATED
4100 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4101 Secure.ZEN_SETTINGS_UPDATED);
4102 if (currentUpdatedSetting.isNull()) {
4103 secureSettings.insertSettingLocked(
4104 Secure.ZEN_SETTINGS_UPDATED, "0",
4105 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4106 }
4107
4108 // ZEN_SETTINGS_SUGGESTION_VIEWED
4109 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4110 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4111 if (currentSettingSuggestionViewed.isNull()) {
4112 secureSettings.insertSettingLocked(
4113 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4114 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4115 }
4116
Nadav Barf9f115d2018-06-24 10:06:50 +03004117 currentVersion = 170;
4118 }
4119
Beverly91d0a632018-07-02 16:45:00 -04004120 if (currentVersion == 170) {
4121 // Version 170: Set the default value for Secure Settings:
4122 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4123
4124 final SettingsState globalSettings = getGlobalSettingsLocked();
4125 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4126
4127 // CHARGING_SOUNDS_ENABLED
4128 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4129 Global.CHARGING_SOUNDS_ENABLED);
4130 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4131 Secure.CHARGING_SOUNDS_ENABLED);
4132
4133 if (!globalChargingSoundEnabled.isNull()) {
4134 secureSettings.insertSettingLocked(
4135 Secure.CHARGING_SOUNDS_ENABLED,
4136 globalChargingSoundEnabled.getValue(), null, false,
4137 SettingsState.SYSTEM_PACKAGE_NAME);
4138
4139 // set global charging_sounds_enabled setting to null since it's deprecated
4140 globalSettings.insertSettingLocked(
4141 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4142 SettingsState.SYSTEM_PACKAGE_NAME);
4143 } else if (secureChargingSoundsEnabled.isNull()) {
4144 String defChargingSoundsEnabled = getContext().getResources()
4145 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4146 secureSettings.insertSettingLocked(
4147 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4148 true, SettingsState.SYSTEM_PACKAGE_NAME);
4149 }
4150
4151 // CHARGING_VIBRATION_ENABLED
4152 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4153 Secure.CHARGING_VIBRATION_ENABLED);
4154
4155 if (secureChargingVibrationEnabled.isNull()) {
4156 String defChargingVibrationEnabled = getContext().getResources()
4157 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4158 secureSettings.insertSettingLocked(
4159 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4160 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4161 }
4162
4163 currentVersion = 171;
4164 }
4165
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004166 if (currentVersion == 171) {
4167 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4168 // be muted.
4169 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4170 final Setting currentSetting = systemSettings.getSettingLocked(
4171 Settings.System.MUTE_STREAMS_AFFECTED);
4172 if (!currentSetting.isNull()) {
4173 try {
4174 int currentSettingIntegerValue = Integer.parseInt(
4175 currentSetting.getValue());
4176 if ((currentSettingIntegerValue
4177 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4178 systemSettings.insertSettingLocked(
4179 Settings.System.MUTE_STREAMS_AFFECTED,
4180 Integer.toString(
4181 currentSettingIntegerValue
4182 | (1 << AudioManager.STREAM_VOICE_CALL)),
4183 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4184 }
4185 } catch (NumberFormatException e) {
4186 // remove the setting in case it is not a valid integer
4187 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4188 + "setting, removing setting", e);
4189 systemSettings.deleteSettingLocked(
4190 Settings.System.MUTE_STREAMS_AFFECTED);
4191 }
4192
4193 }
4194 currentVersion = 172;
4195 }
4196
Felipe Lemeff355092017-04-03 12:55:02 -07004197 // vXXX: Add new settings above this point.
4198
Dan Sandler71f85e92016-07-20 13:46:05 -04004199 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004200 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004201 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004202 + currentVersion +
4203 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4204 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004205 if (DEBUG) {
4206 throw new RuntimeException("db upgrade error");
4207 }
4208 }
4209
Jeff Brown503cffc2015-03-26 18:08:51 -07004210 // Return the current version.
4211 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004212 }
4213 }
Svet Ganov13701552017-02-23 12:45:17 -08004214
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004215 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4216 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004217 List<String> names = settings.getSettingNamesLocked();
4218 final int nameCount = names.size();
4219 for (int i = 0; i < nameCount; i++) {
4220 String name = names.get(i);
4221 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004222
4223 // In the upgrade case we pretend the call is made from the app
4224 // that made the last change to the setting to properly determine
4225 // whether the call has been made by a system component.
4226 int callingUid = -1;
4227 try {
4228 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4229 } catch (RemoteException e) {
4230 /* ignore - handled below */
4231 }
4232 if (callingUid < 0) {
4233 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4234 continue;
4235 }
4236 try {
4237 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4238 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004239 if (systemSet) {
4240 settings.insertSettingLocked(name, setting.getValue(),
4241 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004242 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4243 // We had a bug where changes by non-system packages were marked
4244 // as system made and as a result set as the default. Therefore, if
4245 // the package changed the setting last is not a system one but the
4246 // setting is marked as its default coming from the system we clear
4247 // the default and clear the system set flag.
4248 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004249 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004250 } catch (IllegalStateException e) {
4251 // If the package goes over its quota during the upgrade, don't
4252 // crash but just log the error as the system does the upgrade.
4253 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4254
Svet Ganov13701552017-02-23 12:45:17 -08004255 }
4256 }
4257 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004258 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004259}