blob: 19ce2803fd6025f56db5dcb25cdd6301fe35cfcf [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
Matt Pape1278d1c2018-12-11 13:03:49 -080066import android.provider.DeviceConfig;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070067import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010068import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080069import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000070import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070071import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010072import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080073import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000074import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070075import android.util.Slog;
76import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070077import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080078import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040079
Svetoslav683914b2015-01-15 14:22:26 -080080import com.android.internal.annotations.GuardedBy;
81import com.android.internal.content.PackageMonitor;
82import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080083import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070084import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080085import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040086
Svetoslav683914b2015-01-15 14:22:26 -080087import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080088import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080090import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080091import java.nio.ByteBuffer;
92import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000093import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080094import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070095import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080096import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000097import java.util.Collection;
Matt Pape6bfc62e2018-11-28 13:16:03 -080098import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +000099import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -0800100import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -0800101import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100102import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800103import java.util.Set;
104import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000105
Mark Rathjen7599f132017-01-23 14:15:54 -0800106import javax.crypto.Mac;
107import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700108
Svetoslav Ganove080da92016-12-21 17:10:35 -0800109
Svetoslav683914b2015-01-15 14:22:26 -0800110/**
111 * <p>
112 * This class is a content provider that publishes the system settings.
113 * It can be accessed via the content provider APIs or via custom call
114 * commands. The latter is a bit faster and is the preferred way to access
115 * the platform settings.
116 * </p>
117 * <p>
118 * There are three settings types, global (with signature level protection
119 * and shared across users), secure (with signature permission level
120 * protection and per user), and system (with dangerous permission level
121 * protection and per user). Global settings are stored under the device owner.
122 * Each of these settings is represented by a {@link
123 * com.android.providers.settings.SettingsState} object mapped to an integer
124 * key derived from the setting type in the most significant bits and user
125 * id in the least significant bits. Settings are synchronously loaded on
126 * instantiation of a SettingsState and asynchronously persisted on mutation.
127 * Settings are stored in the user specific system directory.
128 * </p>
129 * <p>
130 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
131 * and get a warning. Targeting higher API version prohibits this as the
132 * system settings are not a place for apps to save their state. When a package
133 * is removed the settings it added are deleted. Apps cannot delete system
134 * settings added by the platform. System settings values are validated to
135 * ensure the clients do not put bad values. Global and secure settings are
136 * changed only by trusted parties, therefore no validation is performed. Also
137 * there is a limit on the amount of app specific settings that can be added
138 * to prevent unlimited growth of the system process memory footprint.
139 * </p>
140 */
141@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700143 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700145 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800146
147 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700148
Christopher Tate06efb532012-08-24 15:29:27 -0700149 private static final String TABLE_SYSTEM = "system";
150 private static final String TABLE_SECURE = "secure";
151 private static final String TABLE_GLOBAL = "global";
Matt Pape6bfc62e2018-11-28 13:16:03 -0800152 private static final String TABLE_CONFIG = "config";
Svetoslav683914b2015-01-15 14:22:26 -0800153
154 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private static final String TABLE_FAVORITES = "favorites";
156 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800157 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
158 private static final String TABLE_BOOKMARKS = "bookmarks";
159 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Svetoslav683914b2015-01-15 14:22:26 -0800161 // The set of removed legacy tables.
162 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700163 static {
Svetoslav683914b2015-01-15 14:22:26 -0800164 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
165 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
166 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
167 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
168 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
169 }
Christopher Tate06efb532012-08-24 15:29:27 -0700170
Svetoslav683914b2015-01-15 14:22:26 -0800171 private static final int MUTATION_OPERATION_INSERT = 1;
172 private static final int MUTATION_OPERATION_DELETE = 2;
173 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800174 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400175
Svetoslav683914b2015-01-15 14:22:26 -0800176 private static final String[] ALL_COLUMNS = new String[] {
177 Settings.NameValueTable._ID,
178 Settings.NameValueTable.NAME,
179 Settings.NameValueTable.VALUE
180 };
181
Makoto Onuki53f0e022017-11-29 13:51:01 -0800182 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
183 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
184 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
185 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700186 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700187
188 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
189 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700190
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800191 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800192 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800193
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700194 // Overlay specified settings whitelisted for Instant Apps
195 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
196 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
197 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
198
199 static {
200 for (String name : Resources.getSystem().getStringArray(
201 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
202 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
203 }
204 for (String name : Resources.getSystem().getStringArray(
205 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
206 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
207 }
208 for (String name : Resources.getSystem().getStringArray(
209 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
210 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
211 }
212 }
213
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800214 // Changes to these global settings are synchronously persisted
215 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
216 static {
217 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
218 }
219
220 // Changes to these secure settings are synchronously persisted
221 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
222 static {
223 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
224 }
225
Svetoslav683914b2015-01-15 14:22:26 -0800226 // Per user secure settings that moved to the for all users global settings.
227 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
228 static {
229 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700230 }
231
Svetoslav683914b2015-01-15 14:22:26 -0800232 // Per user system settings that moved to the for all users global settings.
233 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
234 static {
235 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700236 }
237
Svetoslav683914b2015-01-15 14:22:26 -0800238 // Per user system settings that moved to the per user secure settings.
239 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
240 static {
241 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 }
243
Svetoslav683914b2015-01-15 14:22:26 -0800244 // Per all users global settings that moved to the per user secure settings.
245 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
246 static {
247 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 }
249
Svetoslav683914b2015-01-15 14:22:26 -0800250 // Per user secure settings that are cloned for the managed profiles of the user.
251 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
252 static {
253 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700254 }
255
Svetoslav683914b2015-01-15 14:22:26 -0800256 // Per user system settings that are cloned for the managed profiles of the user.
257 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
258 static {
259 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400260 }
261
Andre Lago3fa139c2016-08-04 13:53:44 +0100262 // Per user system settings that are cloned from the profile's parent when a dependency
263 // in {@link Settings.Secure} is set to "1".
264 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
265 static {
266 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
267 }
268
Svetoslav683914b2015-01-15 14:22:26 -0800269 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700270
Svetoslav683914b2015-01-15 14:22:26 -0800271 @GuardedBy("mLock")
272 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700273
Svet Ganova8f90262016-05-10 08:44:48 -0700274 @GuardedBy("mLock")
275 private HandlerThread mHandlerThread;
276
Makoto Onuki73360ab2017-03-17 11:50:13 -0700277 @GuardedBy("mLock")
278 private Handler mHandler;
279
Svetoslav7ec28e82015-05-20 17:01:10 -0700280 // We have to call in the user manager with no lock held,
281 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800282
yuemingw1d13eae2018-01-30 17:27:54 +0000283 private UserManagerInternal mUserManagerInternal;
284
Svetoslav7ec28e82015-05-20 17:01:10 -0700285 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700286 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700287
Svet Ganov53a441c2016-04-19 19:38:00 -0700288 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800289 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700290 }
291
292 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800293 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700294 }
295
296 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800297 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700298 }
299
300 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800301 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700302 }
303
304 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800305 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700306 }
307
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 @Override
309 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800310 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000311
312 // fail to boot if there're any backed up settings that don't have a non-null validator
313 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000314 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000315 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000316
Svetoslav683914b2015-01-15 14:22:26 -0800317 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700318 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000319 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700320 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700321 mHandlerThread = new HandlerThread(LOG_TAG,
322 Process.THREAD_PRIORITY_BACKGROUND);
323 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700324 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800325 mSettingsRegistry = new SettingsRegistry();
326 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700327 mHandler.post(() -> {
328 registerBroadcastReceivers();
329 startWatchingUserRestrictionChanges();
330 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700331 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800332 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333 return true;
334 }
335
Michal Karpinski2c37b082018-01-18 16:14:27 +0000336 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000337 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
338 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000339
340 failToBootIfOffendersPresent(offenders, "Settings.System");
341 }
342
343 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000344 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
345 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000346
347 failToBootIfOffendersPresent(offenders, "Settings.Global");
348 }
349
Michal Karpinski964943a2018-01-19 16:28:26 +0000350 private void ensureAllBackedUpSecureSettingsHaveValidators() {
351 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
352 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
353
354 failToBootIfOffendersPresent(offenders, "Settings.Secure");
355 }
356
Michal Karpinski5db1e432018-01-18 20:10:24 +0000357 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
358 if (offenders.length() > 0) {
359 throw new RuntimeException("All " + settingsType + " settings that are backed up"
360 + " have to have a non-null validator, but those don't: " + offenders);
361 }
362 }
363
364 private String getOffenders(String[] settingsToBackup, Map<String,
365 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000366 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000367 for (String setting : settingsToBackup) {
368 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000369 offenders.append(setting).append(" ");
370 }
371 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000372 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000373 }
374
Michal Karpinski964943a2018-01-19 16:28:26 +0000375 private final String[] concat(String[] first, String[] second) {
376 if (second == null || second.length == 0) {
377 return first;
378 }
379 final int firstLen = first.length;
380 final int secondLen = second.length;
381 String[] both = new String[firstLen + secondLen];
382 System.arraycopy(first, 0, both, 0, firstLen);
383 System.arraycopy(second, 0, both, firstLen, secondLen);
384 return both;
385 }
386
Svetoslav683914b2015-01-15 14:22:26 -0800387 @Override
388 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700389 final int requestingUserId = getRequestingUserId(args);
390 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700391 case Settings.CALL_METHOD_GET_CONFIG: {
392 Setting setting = getConfigSetting(name);
393 return packageValueForCallResult(setting, isTrackingGeneration(args));
394 }
395
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 case Settings.CALL_METHOD_GET_GLOBAL: {
397 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700398 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800399 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700400
401 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800402 Setting setting = getSecureSetting(name, requestingUserId,
403 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700404 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 }
406
407 case Settings.CALL_METHOD_GET_SYSTEM: {
408 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700409 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700410 }
411
Matt Pape1b31a332018-10-17 09:58:28 -0700412 case Settings.CALL_METHOD_PUT_CONFIG: {
413 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700414 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800415 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700416 break;
417 }
418
Svetoslav7ec28e82015-05-20 17:01:10 -0700419 case Settings.CALL_METHOD_PUT_GLOBAL: {
420 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800421 String tag = getSettingTag(args);
422 final boolean makeDefault = getSettingMakeDefault(args);
423 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700424 break;
425 }
426
427 case Settings.CALL_METHOD_PUT_SECURE: {
428 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800429 String tag = getSettingTag(args);
430 final boolean makeDefault = getSettingMakeDefault(args);
431 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700432 break;
433 }
434
435 case Settings.CALL_METHOD_PUT_SYSTEM: {
436 String value = getSettingValue(args);
437 insertSystemSetting(name, value, requestingUserId);
438 break;
439 }
440
Matt Pape1b31a332018-10-17 09:58:28 -0700441 case Settings.CALL_METHOD_RESET_CONFIG: {
442 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800443 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800444 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700445 break;
446 }
447
Svetoslav Ganove080da92016-12-21 17:10:35 -0800448 case Settings.CALL_METHOD_RESET_GLOBAL: {
449 final int mode = getResetModeEnforcingPermission(args);
450 String tag = getSettingTag(args);
451 resetGlobalSetting(requestingUserId, mode, tag);
452 break;
453 }
454
455 case Settings.CALL_METHOD_RESET_SECURE: {
456 final int mode = getResetModeEnforcingPermission(args);
457 String tag = getSettingTag(args);
458 resetSecureSetting(requestingUserId, mode, tag);
459 break;
460 }
461
Matt Pape6bfc62e2018-11-28 13:16:03 -0800462 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800463 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800464 Bundle result = new Bundle();
465 result.putInt(RESULT_ROWS_DELETED, rows);
466 return result;
467 }
468
469 case Settings.CALL_METHOD_DELETE_GLOBAL: {
470 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
471 Bundle result = new Bundle();
472 result.putInt(RESULT_ROWS_DELETED, rows);
473 return result;
474 }
475
Matt Pape6bfc62e2018-11-28 13:16:03 -0800476 case Settings.CALL_METHOD_DELETE_SECURE: {
477 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
478 Bundle result = new Bundle();
479 result.putInt(RESULT_ROWS_DELETED, rows);
480 return result;
481 }
482
483 case Settings.CALL_METHOD_DELETE_SYSTEM: {
484 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
485 Bundle result = new Bundle();
486 result.putInt(RESULT_ROWS_DELETED, rows);
487 return result;
488 }
489
490 case Settings.CALL_METHOD_LIST_CONFIG: {
491 String prefix = getSettingPrefix(args);
492 Bundle result = new Bundle();
493 result.putSerializable(
494 Settings.NameValueTable.VALUE, (HashMap) getAllConfigFlags(prefix));
495 return result;
496 }
497
498 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800499 Bundle result = new Bundle();
500 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800501 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800502 return result;
503 }
504
505 case Settings.CALL_METHOD_LIST_SECURE: {
506 Bundle result = new Bundle();
507 result.putStringArrayList(RESULT_SETTINGS_LIST,
508 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
509 return result;
510 }
511
Matt Pape6bfc62e2018-11-28 13:16:03 -0800512 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800513 Bundle result = new Bundle();
514 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800515 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800516 return result;
517 }
518
Svetoslav7ec28e82015-05-20 17:01:10 -0700519 default: {
520 Slog.w(LOG_TAG, "call() with invalid method: " + method);
521 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700522 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700523
Christopher Tate06efb532012-08-24 15:29:27 -0700524 return null;
525 }
526
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800527 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800528 public String getType(Uri uri) {
529 Arguments args = new Arguments(uri, null, null, true);
530 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531 return "vnd.android.cursor.dir/" + args.table;
532 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700533 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700534 }
535 }
536
537 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800538 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
539 String order) {
540 if (DEBUG) {
541 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700542 }
543
Svetoslav683914b2015-01-15 14:22:26 -0800544 Arguments args = new Arguments(uri, where, whereArgs, true);
545 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700546
Svetoslav683914b2015-01-15 14:22:26 -0800547 // If a legacy table that is gone, done.
548 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
549 return new MatrixCursor(normalizedProjection, 0);
550 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700551
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 switch (args.table) {
553 case TABLE_GLOBAL: {
554 if (args.name != null) {
555 Setting setting = getGlobalSetting(args.name);
556 return packageSettingForQuery(setting, normalizedProjection);
557 } else {
558 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700559 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700560 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700561
Svetoslav7ec28e82015-05-20 17:01:10 -0700562 case TABLE_SECURE: {
563 final int userId = UserHandle.getCallingUserId();
564 if (args.name != null) {
565 Setting setting = getSecureSetting(args.name, userId);
566 return packageSettingForQuery(setting, normalizedProjection);
567 } else {
568 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800569 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700570 }
Svetoslav683914b2015-01-15 14:22:26 -0800571
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 case TABLE_SYSTEM: {
573 final int userId = UserHandle.getCallingUserId();
574 if (args.name != null) {
575 Setting setting = getSystemSetting(args.name, userId);
576 return packageSettingForQuery(setting, normalizedProjection);
577 } else {
578 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800579 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700580 }
Svetoslav683914b2015-01-15 14:22:26 -0800581
Svetoslav7ec28e82015-05-20 17:01:10 -0700582 default: {
583 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700584 }
585 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700586 }
587
Nicholas Sauer72500532018-11-21 10:30:58 -0800588 private ArrayList<String> buildSettingsList(Cursor cursor) {
589 final ArrayList<String> lines = new ArrayList<String>();
590 try {
591 while (cursor != null && cursor.moveToNext()) {
592 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
593 }
594 } finally {
595 if (cursor != null) {
596 cursor.close();
597 }
598 }
599 return lines;
600 }
601
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700602 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800603 public Uri insert(Uri uri, ContentValues values) {
604 if (DEBUG) {
605 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700606 }
607
Svetoslav683914b2015-01-15 14:22:26 -0800608 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700609
Svetoslav683914b2015-01-15 14:22:26 -0800610 // If a legacy table that is gone, done.
611 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 return null;
613 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700614
Svetoslav683914b2015-01-15 14:22:26 -0800615 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700616 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800617 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700618 }
619
Svetoslav683914b2015-01-15 14:22:26 -0800620 String value = values.getAsString(Settings.Secure.VALUE);
621
Svetoslav7ec28e82015-05-20 17:01:10 -0700622 switch (table) {
623 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800624 if (insertGlobalSetting(name, value, null, false,
625 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700626 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700627 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700628 } break;
629
630 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800631 if (insertSecureSetting(name, value, null, false,
632 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700633 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
634 }
635 } break;
636
637 case TABLE_SYSTEM: {
638 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
639 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
640 }
641 } break;
642
643 default: {
644 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700645 }
646 }
647
Svetoslav683914b2015-01-15 14:22:26 -0800648 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700649 }
650
651 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800652 public int bulkInsert(Uri uri, ContentValues[] allValues) {
653 if (DEBUG) {
654 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700656
Svetoslav683914b2015-01-15 14:22:26 -0800657 int insertionCount = 0;
658 final int valuesCount = allValues.length;
659 for (int i = 0; i < valuesCount; i++) {
660 ContentValues values = allValues[i];
661 if (insert(uri, values) != null) {
662 insertionCount++;
663 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700664 }
Svetoslav683914b2015-01-15 14:22:26 -0800665
666 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700667 }
668
669 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800670 public int delete(Uri uri, String where, String[] whereArgs) {
671 if (DEBUG) {
672 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700674
Svetoslav683914b2015-01-15 14:22:26 -0800675 Arguments args = new Arguments(uri, where, whereArgs, false);
676
677 // If a legacy table that is gone, done.
678 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
679 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700680 }
Svetoslav683914b2015-01-15 14:22:26 -0800681
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700682 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800683 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700684 }
Svetoslav683914b2015-01-15 14:22:26 -0800685
Svetoslav7ec28e82015-05-20 17:01:10 -0700686 switch (args.table) {
687 case TABLE_GLOBAL: {
688 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700689 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700690 }
Svetoslav683914b2015-01-15 14:22:26 -0800691
Svetoslav7ec28e82015-05-20 17:01:10 -0700692 case TABLE_SECURE: {
693 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700694 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700695 }
Svetoslav683914b2015-01-15 14:22:26 -0800696
Svetoslav7ec28e82015-05-20 17:01:10 -0700697 case TABLE_SYSTEM: {
698 final int userId = UserHandle.getCallingUserId();
699 return deleteSystemSetting(args.name, userId) ? 1 : 0;
700 }
701
702 default: {
703 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800704 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700705 }
Svetoslav683914b2015-01-15 14:22:26 -0800706 }
707
708 @Override
709 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
710 if (DEBUG) {
711 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700712 }
Svetoslav683914b2015-01-15 14:22:26 -0800713
714 Arguments args = new Arguments(uri, where, whereArgs, false);
715
716 // If a legacy table that is gone, done.
717 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
718 return 0;
719 }
720
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700721 String name = values.getAsString(Settings.Secure.NAME);
722 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800723 return 0;
724 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700725 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800726
Svetoslav7ec28e82015-05-20 17:01:10 -0700727 switch (args.table) {
728 case TABLE_GLOBAL: {
729 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800730 return updateGlobalSetting(args.name, value, null, false,
731 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700732 }
Svetoslav683914b2015-01-15 14:22:26 -0800733
Svetoslav7ec28e82015-05-20 17:01:10 -0700734 case TABLE_SECURE: {
735 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800736 return updateSecureSetting(args.name, value, null, false,
737 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700738 }
Svetoslav683914b2015-01-15 14:22:26 -0800739
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 case TABLE_SYSTEM: {
741 final int userId = UserHandle.getCallingUserId();
742 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
743 }
Svetoslav683914b2015-01-15 14:22:26 -0800744
Svetoslav7ec28e82015-05-20 17:01:10 -0700745 default: {
746 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800747 }
748 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700749 }
750
751 @Override
752 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100753 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
754 if (userId != UserHandle.getCallingUserId()) {
755 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
756 "Access files from the settings of another user");
757 }
758 uri = ContentProvider.getUriWithoutUserId(uri);
759
Andre Lago3fa139c2016-08-04 13:53:44 +0100760 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700761 final String cacheName;
762 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100763 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700764 cacheName = Settings.System.RINGTONE_CACHE;
765 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100766 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700767 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
768 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100769 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700770 cacheName = Settings.System.ALARM_ALERT_CACHE;
771 } else {
772 throw new FileNotFoundException("Direct file access no longer supported; "
773 + "ringtone playback is available through android.media.Ringtone");
774 }
775
Andre Lago3fa139c2016-08-04 13:53:44 +0100776 int actualCacheOwner;
777 // Redirect cache to parent if ringtone setting is owned by profile parent
778 synchronized (mLock) {
779 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
780 cacheRingtoneSetting);
781 }
782 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700783 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
784 }
785
786 private File getRingtoneCacheDir(int userId) {
787 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
788 cacheDir.mkdir();
789 SELinux.restorecon(cacheDir);
790 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700791 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800792
Eugene Suslad72c3972016-12-27 15:49:30 -0800793 /**
794 * Dump all settings as a proto buf.
795 *
796 * @param fd The file to dump to
797 */
798 void dumpProto(@NonNull FileDescriptor fd) {
799 ProtoOutputStream proto = new ProtoOutputStream(fd);
800
801 synchronized (mLock) {
802 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800803 }
804
805 proto.flush();
806 }
807
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700808 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800809 synchronized (mLock) {
810 final long identity = Binder.clearCallingIdentity();
811 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700812 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800813 final int userCount = users.size();
814 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700815 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800816 }
817 } finally {
818 Binder.restoreCallingIdentity(identity);
819 }
820 }
821 }
822
Andreas Gampeb58893072018-09-05 16:52:31 -0700823 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700824 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700825 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700826 pw.println("CONFIG SETTINGS (user " + userId + ")");
827 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
828 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
829 if (configSettings != null) {
830 dumpSettingsLocked(configSettings, pw);
831 pw.println();
832 configSettings.dumpHistoricalOperations(pw);
833 }
834
Svetoslavb505ccc2015-02-17 12:41:04 -0800835 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700836 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
837 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700838 if (globalSettings != null) {
839 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800840 pw.println();
841 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700842 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800843 }
844
845 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700846 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
847 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700848 if (secureSettings != null) {
849 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800850 pw.println();
851 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700852 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700853
Svetoslavb505ccc2015-02-17 12:41:04 -0800854 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700855 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
856 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700857 if (systemSettings != null) {
858 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800859 pw.println();
860 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700861 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800862 }
863
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700864 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
865 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800866
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700867 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800868
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700869 for (int i = 0; i < nameCount; i++) {
870 String name = names.get(i);
871 Setting setting = settingsState.getSettingLocked(name);
872 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
873 pw.print(" name:"); pw.print(toDumpString(name));
874 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800875 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700876 }
877 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800878 if (setting.getDefaultValue() != null) {
879 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800880 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800881 }
882 if (setting.getTag() != null) {
883 pw.print(" tag:"); pw.print(setting.getTag());
884 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800885 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700886 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800887 }
888
Svetoslav7e0683b2015-08-03 16:02:52 -0700889 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700890 if (s != null) {
891 return s;
892 }
893 return "{null}";
894 }
895
Svetoslav683914b2015-01-15 14:22:26 -0800896 private void registerBroadcastReceivers() {
897 IntentFilter userFilter = new IntentFilter();
898 userFilter.addAction(Intent.ACTION_USER_REMOVED);
899 userFilter.addAction(Intent.ACTION_USER_STOPPED);
900
901 getContext().registerReceiver(new BroadcastReceiver() {
902 @Override
903 public void onReceive(Context context, Intent intent) {
904 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700905 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800906
907 switch (intent.getAction()) {
908 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700909 synchronized (mLock) {
910 mSettingsRegistry.removeUserStateLocked(userId, true);
911 }
Svetoslav683914b2015-01-15 14:22:26 -0800912 } break;
913
914 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700915 synchronized (mLock) {
916 mSettingsRegistry.removeUserStateLocked(userId, false);
917 }
Svetoslav683914b2015-01-15 14:22:26 -0800918 } break;
919 }
920 }
921 }, userFilter);
922
923 PackageMonitor monitor = new PackageMonitor() {
924 @Override
925 public void onPackageRemoved(String packageName, int uid) {
926 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100927 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800928 UserHandle.getUserId(uid));
929 }
930 }
Mark Rathjend891f012017-01-19 04:10:37 +0000931
932 @Override
933 public void onUidRemoved(int uid) {
934 synchronized (mLock) {
935 mSettingsRegistry.onUidRemovedLocked(uid);
936 }
937 }
Zimuzoc56192c2018-07-25 10:40:01 +0100938
939 @Override
940 public void onPackageDataCleared(String packageName, int uid) {
941 synchronized (mLock) {
942 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
943 UserHandle.getUserId(uid));
944 }
945 }
Svetoslav683914b2015-01-15 14:22:26 -0800946 };
947
948 // package changes
949 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
950 UserHandle.ALL, true);
951 }
952
Svet Ganov53a441c2016-04-19 19:38:00 -0700953 private void startWatchingUserRestrictionChanges() {
954 // TODO: The current design of settings looking different based on user restrictions
955 // should be reworked to keep them separate and system code should check the setting
956 // first followed by checking the user restriction before performing an operation.
957 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
958 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
959 Bundle prevRestrictions) -> {
960 // We are changing the settings affected by restrictions to their current
961 // value with a forced update to ensure that all cross profile dependencies
962 // are taken into account. Also make sure the settings update to.. the same
963 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800964 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
965 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700966 final long identity = Binder.clearCallingIdentity();
967 try {
968 synchronized (mLock) {
969 Setting setting = getSecureSetting(
970 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
971 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800972 setting != null ? setting.getValue() : null, null,
973 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700974 }
975 } finally {
976 Binder.restoreCallingIdentity(identity);
977 }
978 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800979 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100980 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
981 newRestrictions.getBoolean(
982 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
983 != prevRestrictions.getBoolean(
984 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700985 final long identity = Binder.clearCallingIdentity();
986 try {
987 synchronized (mLock) {
988 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800989 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700990 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800991 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700992 }
993 } finally {
994 Binder.restoreCallingIdentity(identity);
995 }
996 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800997 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
998 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700999 final long identity = Binder.clearCallingIdentity();
1000 try {
1001 synchronized (mLock) {
1002 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001003 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001004 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001005 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001006 }
1007 } finally {
1008 Binder.restoreCallingIdentity(identity);
1009 }
1010 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001011 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
1012 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001013 final long identity = Binder.clearCallingIdentity();
1014 try {
1015 synchronized (mLock) {
1016 Setting enable = getGlobalSetting(
1017 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001018 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001019 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001020 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001021 Setting include = getGlobalSetting(
1022 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001023 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001024 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001025 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001026 }
1027 } finally {
1028 Binder.restoreCallingIdentity(identity);
1029 }
1030 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001031 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
1032 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001033 final long identity = Binder.clearCallingIdentity();
1034 try {
1035 synchronized (mLock) {
1036 Setting setting = getGlobalSetting(
1037 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001038 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001039 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001040 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001041 }
1042 } finally {
1043 Binder.restoreCallingIdentity(identity);
1044 }
1045 }
1046 });
1047 }
1048
Matt Pape1b31a332018-10-17 09:58:28 -07001049 private Setting getConfigSetting(String name) {
1050 if (DEBUG) {
1051 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1052 }
1053
1054 // TODO(b/117663715): Ensure the caller can access the setting.
1055 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1056
1057 // Get the value.
1058 synchronized (mLock) {
1059 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1060 UserHandle.USER_SYSTEM, name);
1061 }
1062 }
1063
Matt Papec1323dc2018-12-11 12:32:42 -08001064 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001065 if (DEBUG) {
1066 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001067 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001068 }
Matt Papec1323dc2018-12-11 12:32:42 -08001069 return mutateConfigSetting(name, value, null, makeDefault,
1070 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001071 }
1072
Matt Papec1323dc2018-12-11 12:32:42 -08001073 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001074 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001075 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001076 }
Matt Papec1323dc2018-12-11 12:32:42 -08001077 return mutateConfigSetting(name, null, null, false,
1078 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001079 }
1080
Matt Papec1323dc2018-12-11 12:32:42 -08001081 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001082 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001083 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001084 }
Matt Papec1323dc2018-12-11 12:32:42 -08001085 mutateConfigSetting(null, null, prefix, false,
1086 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001087 }
1088
Matt Pape6bfc62e2018-11-28 13:16:03 -08001089 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001090 boolean makeDefault, int operation, int mode) {
Matt Pape1b31a332018-10-17 09:58:28 -07001091 // TODO(b/117663715): check the new permission when it's added.
1092 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1093
Matt Pape1b31a332018-10-17 09:58:28 -07001094 // Perform the mutation.
1095 synchronized (mLock) {
1096 switch (operation) {
1097 case MUTATION_OPERATION_INSERT: {
1098 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001099 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001100 resolveCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001101 }
1102
Matt Pape6bfc62e2018-11-28 13:16:03 -08001103 case MUTATION_OPERATION_DELETE: {
1104 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001105 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001106 }
1107
Matt Pape1b31a332018-10-17 09:58:28 -07001108 case MUTATION_OPERATION_RESET: {
1109 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001110 UserHandle.USER_SYSTEM, resolveCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001111 } return true;
1112 }
1113 }
1114
1115 return false;
1116 }
1117
Matt Pape6bfc62e2018-11-28 13:16:03 -08001118 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1119 if (DEBUG) {
1120 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1121 }
1122
1123 synchronized (mLock) {
1124 // Get the settings.
1125 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1126 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1127
1128 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1129 UserHandle.USER_SYSTEM);
1130
1131 final int nameCount = names.size();
1132 Map<String, String> flagsToValues = new HashMap<>(names.size());
1133
1134 for (int i = 0; i < nameCount; i++) {
1135 String name = names.get(i);
1136 Setting setting = settingsState.getSettingLocked(name);
1137 if (prefix == null || setting.getName().startsWith(prefix)) {
1138 flagsToValues.put(setting.getName(), setting.getValue());
1139 }
1140 }
1141
1142 return flagsToValues;
1143 }
1144 }
1145
Svetoslav7ec28e82015-05-20 17:01:10 -07001146 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001147 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001148 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001149 }
1150
Svetoslav7ec28e82015-05-20 17:01:10 -07001151 synchronized (mLock) {
1152 // Get the settings.
1153 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001154 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001155
Chad Brubaker97bccee2017-01-05 15:51:41 -08001156 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1157 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001158
Svetoslav7ec28e82015-05-20 17:01:10 -07001159 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001160
Svetoslav7ec28e82015-05-20 17:01:10 -07001161 String[] normalizedProjection = normalizeProjection(projection);
1162 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001163
Svetoslav7ec28e82015-05-20 17:01:10 -07001164 // Anyone can get the global settings, so no security checks.
1165 for (int i = 0; i < nameCount; i++) {
1166 String name = names.get(i);
1167 Setting setting = settingsState.getSettingLocked(name);
1168 appendSettingToCursor(result, setting);
1169 }
1170
1171 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001172 }
Svetoslav683914b2015-01-15 14:22:26 -08001173 }
1174
Svetoslav7ec28e82015-05-20 17:01:10 -07001175 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001176 if (DEBUG) {
1177 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1178 }
1179
Chad Brubakera6830e72017-04-28 17:34:36 -07001180 // Ensure the caller can access the setting.
1181 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1182
Svetoslav683914b2015-01-15 14:22:26 -08001183 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001184 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001185 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001186 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001187 }
Svetoslav683914b2015-01-15 14:22:26 -08001188 }
1189
Svetoslav Ganove080da92016-12-21 17:10:35 -08001190 private boolean updateGlobalSetting(String name, String value, String tag,
1191 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001192 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001193 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1194 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1195 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001196 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001197 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1198 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
1200
Svetoslav Ganove080da92016-12-21 17:10:35 -08001201 private boolean insertGlobalSetting(String name, String value, String tag,
1202 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001203 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001204 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1205 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1206 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001208 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1209 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001210 }
1211
Svet Ganov53a441c2016-04-19 19:38:00 -07001212 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001213 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1215 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001216 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001217 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1218 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001219 }
1220
Svetoslav Ganove080da92016-12-21 17:10:35 -08001221 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1222 if (DEBUG) {
1223 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1224 + mode + ", " + tag + ")");
1225 }
1226 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1227 MUTATION_OPERATION_RESET, false, mode);
1228 }
1229
1230 private boolean mutateGlobalSetting(String name, String value, String tag,
1231 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1232 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001233 // Make sure the caller can change the settings - treated as secure.
1234 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1235
Svetoslav683914b2015-01-15 14:22:26 -08001236 // Resolve the userId on whose behalf the call is made.
1237 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1238
Makoto Onuki28da2e32015-11-20 11:30:44 -08001239 // If this is a setting that is currently restricted for this user, do not allow
1240 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001241 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1242 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001243 return false;
1244 }
1245
1246 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001247 synchronized (mLock) {
1248 switch (operation) {
1249 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001250 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1251 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001252 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001253 }
Svetoslav683914b2015-01-15 14:22:26 -08001254
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001256 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001257 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 }
Svetoslav683914b2015-01-15 14:22:26 -08001259
Svetoslav7ec28e82015-05-20 17:01:10 -07001260 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001261 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1262 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001263 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001264 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001265
1266 case MUTATION_OPERATION_RESET: {
1267 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1268 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1269 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001270 }
1271 }
1272
1273 return false;
1274 }
1275
Christopher Tateb218e762017-04-05 16:34:07 -07001276 private PackageInfo getCallingPackageInfo(int userId) {
1277 try {
1278 return mPackageManager.getPackageInfo(getCallingPackage(),
1279 PackageManager.GET_SIGNATURES, userId);
1280 } catch (RemoteException e) {
1281 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1282 }
1283 }
1284
Svetoslav7ec28e82015-05-20 17:01:10 -07001285 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001286 if (DEBUG) {
1287 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1288 }
1289
1290 // Resolve the userId on whose behalf the call is made.
1291 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1292
Christopher Tateb218e762017-04-05 16:34:07 -07001293 // The relevant "calling package" userId will be the owning userId for some
1294 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1295 // up front who the effective "new SSAID" user ID for that settings name will be.
1296 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1297 Settings.Secure.ANDROID_ID);
1298 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1299
Svetoslav7ec28e82015-05-20 17:01:10 -07001300 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001301 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001302
Svetoslav7ec28e82015-05-20 17:01:10 -07001303 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001304
Svetoslav7ec28e82015-05-20 17:01:10 -07001305 String[] normalizedProjection = normalizeProjection(projection);
1306 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001307
Svetoslav7ec28e82015-05-20 17:01:10 -07001308 for (int i = 0; i < nameCount; i++) {
1309 String name = names.get(i);
1310 // Determine the owning user as some profile settings are cloned from the parent.
1311 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1312 name);
Svetoslav683914b2015-01-15 14:22:26 -08001313
Alex Klyubin1991f572017-03-03 14:08:36 -08001314 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1315 // This caller is not permitted to access this setting. Pretend the setting
1316 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001317 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001318 }
Svetoslav683914b2015-01-15 14:22:26 -08001319
Mark Rathjen7599f132017-01-23 14:15:54 -08001320 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001321 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1322 final Setting setting;
1323 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001324 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001325 } else {
1326 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1327 name);
1328 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001329 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001330 }
1331
Svetoslav7ec28e82015-05-20 17:01:10 -07001332 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001333 }
Svetoslav683914b2015-01-15 14:22:26 -08001334 }
1335
Svetoslav7ec28e82015-05-20 17:01:10 -07001336 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001337 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1338 }
1339
1340 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001341 if (DEBUG) {
1342 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1343 }
1344
1345 // Resolve the userId on whose behalf the call is made.
1346 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1347
Chad Brubakera6830e72017-04-28 17:34:36 -07001348 // Ensure the caller can access the setting.
1349 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1350
Svetoslav683914b2015-01-15 14:22:26 -08001351 // Determine the owning user as some profile settings are cloned from the parent.
1352 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1353
Alex Klyubin1991f572017-03-03 14:08:36 -08001354 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1355 // This caller is not permitted to access this setting. Pretend the setting doesn't
1356 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001357 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1358 owningUserId);
1359 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001360 }
1361
Christopher Tateb218e762017-04-05 16:34:07 -07001362 // As of Android O, the SSAID is read from an app-specific entry in table
1363 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1364 if (isNewSsaidSetting(name)) {
1365 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1366 synchronized (mLock) {
1367 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001368 }
Christopher Tateb218e762017-04-05 16:34:07 -07001369 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001370 if (enableOverride) {
1371 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1372 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1373 if (overridden != null) {
1374 return overridden;
1375 }
1376 }
1377 }
Mark Rathjend891f012017-01-19 04:10:37 +00001378
Christopher Tateb218e762017-04-05 16:34:07 -07001379 // Not the SSAID; do a straight lookup
1380 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001381 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001382 owningUserId, name);
1383 }
Svetoslav683914b2015-01-15 14:22:26 -08001384 }
1385
Mark Rathjend891f012017-01-19 04:10:37 +00001386 private boolean isNewSsaidSetting(String name) {
1387 return Settings.Secure.ANDROID_ID.equals(name)
1388 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1389 }
1390
Andreas Gampeb58893072018-09-05 16:52:31 -07001391 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001392 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001393 // Get uid of caller (key) used to store ssaid value
1394 String name = Integer.toString(
1395 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1396
1397 if (DEBUG) {
1398 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1399 }
1400
1401 // Retrieve the ssaid from the table if present.
1402 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1403 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001404 // If the app is an Instant App use its stored SSAID instead of our own.
1405 final String instantSsaid;
1406 final long token = Binder.clearCallingIdentity();
1407 try {
1408 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1409 owningUserId);
1410 } catch (RemoteException e) {
1411 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1412 return null;
1413 } finally {
1414 Binder.restoreCallingIdentity(token);
1415 }
Svet Ganov96c99462017-05-05 14:27:13 -07001416
1417 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1418 SETTINGS_TYPE_SSAID, owningUserId);
1419
Chad Brubaker0d277a72017-04-12 16:56:53 -07001420 if (instantSsaid != null) {
1421 // Use the stored value if it is still valid.
1422 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001423 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001424 }
1425 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001426 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1427 true, callingPkg.packageName);
1428 if (!success) {
1429 throw new IllegalStateException("Failed to update instant app android id");
1430 }
Svet Ganov96c99462017-05-05 14:27:13 -07001431 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1432 owningUserId, name);
1433 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001434 }
Mark Rathjend891f012017-01-19 04:10:37 +00001435
1436 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001437 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001438 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1439 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001440 }
1441
Svet Ganov96c99462017-05-05 14:27:13 -07001442 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1443 }
1444
1445 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1446 // SSAID settings are located in a dedicated table for internal bookkeeping
1447 // but for the world they reside in the secure table, so adjust the key here.
1448 // We have a special name when looking it up but want the world to see it as
1449 // "android_id".
1450 if (ssaidSetting != null) {
1451 return settingsState.new Setting(ssaidSetting) {
1452 @Override
1453 public int getKey() {
1454 final int userId = getUserIdFromKey(super.getKey());
1455 return makeKey(SETTINGS_TYPE_SECURE, userId);
1456 }
1457
1458 @Override
1459 public String getName() {
1460 return Settings.Secure.ANDROID_ID;
1461 }
1462 };
1463 }
1464 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001465 }
1466
Makoto Onuki0000d322017-11-28 16:31:47 -08001467 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1468 synchronized (mLock) {
1469 final Setting setting = getGlobalSetting(
1470 Global.LOCATION_GLOBAL_KILL_SWITCH);
1471 if (!"1".equals(setting.getValue())) {
1472 return null;
1473 }
1474 // Global kill-switch is enabled. Return an empty value.
1475 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1476 SETTINGS_TYPE_SECURE, owningUserId);
1477 return settingsState.new Setting(
1478 Secure.LOCATION_PROVIDERS_ALLOWED,
1479 "", // value
1480 "", // tag
1481 "", // default value
1482 "", // package name
1483 false, // from system
1484 "0" // id
1485 ) {
1486 @Override
1487 public boolean update(String value, boolean setDefault, String packageName,
1488 String tag, boolean forceNonSystemPackage) {
1489 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1490 return false;
1491 }
1492 };
1493 }
1494 }
1495
Svetoslav Ganove080da92016-12-21 17:10:35 -08001496 private boolean insertSecureSetting(String name, String value, String tag,
1497 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001498 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001499 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001500 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1501 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001502 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001503 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1504 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001505 }
1506
Svet Ganov53a441c2016-04-19 19:38:00 -07001507 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001508 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001509 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1510 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001511 }
1512
Svetoslav Ganove080da92016-12-21 17:10:35 -08001513 return mutateSecureSetting(name, null, null, false, requestingUserId,
1514 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001515 }
1516
Svetoslav Ganove080da92016-12-21 17:10:35 -08001517 private boolean updateSecureSetting(String name, String value, String tag,
1518 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001519 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001520 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001521 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1522 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001523 }
1524
Svetoslav Ganove080da92016-12-21 17:10:35 -08001525 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1526 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001527 }
1528
Svetoslav Ganove080da92016-12-21 17:10:35 -08001529 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1530 if (DEBUG) {
1531 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1532 + mode + ", " + tag + ")");
1533 }
1534
1535 mutateSecureSetting(null, null, tag, false, requestingUserId,
1536 MUTATION_OPERATION_RESET, false, mode);
1537 }
1538
1539 private boolean mutateSecureSetting(String name, String value, String tag,
1540 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1541 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001542 // Make sure the caller can change the settings.
1543 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1544
Svetoslav683914b2015-01-15 14:22:26 -08001545 // Resolve the userId on whose behalf the call is made.
1546 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1547
Makoto Onuki28da2e32015-11-20 11:30:44 -08001548 // If this is a setting that is currently restricted for this user, do not allow
1549 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001550 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1551 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001552 return false;
1553 }
1554
1555 // Determine the owning user as some profile settings are cloned from the parent.
1556 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1557
1558 // Only the owning user can change the setting.
1559 if (owningUserId != callingUserId) {
1560 return false;
1561 }
1562
1563 // Special cases for location providers (sigh).
1564 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001565 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1566 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001567 }
1568
1569 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001570 synchronized (mLock) {
1571 switch (operation) {
1572 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001573 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001574 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001575 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001576 }
Svetoslav683914b2015-01-15 14:22:26 -08001577
Svetoslav7ec28e82015-05-20 17:01:10 -07001578 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001579 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001580 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001581 }
Svetoslav683914b2015-01-15 14:22:26 -08001582
Svetoslav7ec28e82015-05-20 17:01:10 -07001583 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001584 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001585 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001586 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001587 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001588
1589 case MUTATION_OPERATION_RESET: {
1590 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1591 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1592 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001593 }
1594 }
1595
1596 return false;
1597 }
1598
Svetoslav7ec28e82015-05-20 17:01:10 -07001599 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001600 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001601 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001602 }
1603
1604 // Resolve the userId on whose behalf the call is made.
1605 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1606
Svetoslav7ec28e82015-05-20 17:01:10 -07001607 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001608 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001609
Svetoslav7ec28e82015-05-20 17:01:10 -07001610 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001611
Svetoslav7ec28e82015-05-20 17:01:10 -07001612 String[] normalizedProjection = normalizeProjection(projection);
1613 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001614
Svetoslav7ec28e82015-05-20 17:01:10 -07001615 for (int i = 0; i < nameCount; i++) {
1616 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001617
Svetoslav7ec28e82015-05-20 17:01:10 -07001618 // Determine the owning user as some profile settings are cloned from the parent.
1619 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1620 name);
Svetoslav683914b2015-01-15 14:22:26 -08001621
Svetoslav7ec28e82015-05-20 17:01:10 -07001622 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001623 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001624 appendSettingToCursor(result, setting);
1625 }
1626
1627 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001628 }
Svetoslav683914b2015-01-15 14:22:26 -08001629 }
1630
Svetoslav7ec28e82015-05-20 17:01:10 -07001631 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001632 if (DEBUG) {
1633 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1634 }
1635
1636 // Resolve the userId on whose behalf the call is made.
1637 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1638
Chad Brubakera6830e72017-04-28 17:34:36 -07001639 // Ensure the caller can access the setting.
1640 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001641
Svetoslav683914b2015-01-15 14:22:26 -08001642 // Determine the owning user as some profile settings are cloned from the parent.
1643 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1644
1645 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001646 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001647 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001648 }
Svetoslav683914b2015-01-15 14:22:26 -08001649 }
1650
Svetoslav7ec28e82015-05-20 17:01:10 -07001651 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001652 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001653 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001654 + requestingUserId + ")");
1655 }
1656
Svetoslav7ec28e82015-05-20 17:01:10 -07001657 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001658 }
1659
Svetoslav7ec28e82015-05-20 17:01:10 -07001660 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001661 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001662 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001663 }
1664
Svetoslav7ec28e82015-05-20 17:01:10 -07001665 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001666 }
1667
Svetoslav7ec28e82015-05-20 17:01:10 -07001668 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001669 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001670 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001671 + requestingUserId + ")");
1672 }
1673
Svetoslav7ec28e82015-05-20 17:01:10 -07001674 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001675 }
1676
Svetoslav7ec28e82015-05-20 17:01:10 -07001677 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001678 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001679 if (!hasWriteSecureSettingsPermission()) {
1680 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1681 // operation is allowed for the calling package through appops.
1682 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1683 Binder.getCallingUid(), getCallingPackage(), true)) {
1684 return false;
1685 }
Svetoslav683914b2015-01-15 14:22:26 -08001686 }
1687
Svetoslav683914b2015-01-15 14:22:26 -08001688 // Resolve the userId on whose behalf the call is made.
1689 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1690
yuemingw1d13eae2018-01-30 17:27:54 +00001691 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1692 name, callingUserId, value, Binder.getCallingUid())) {
1693 return false;
1694 }
1695
Svetoslavd8d25e02015-11-20 13:09:26 -08001696 // Enforce what the calling package can mutate the system settings.
1697 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1698
Svetoslav683914b2015-01-15 14:22:26 -08001699 // Determine the owning user as some profile settings are cloned from the parent.
1700 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1701
1702 // Only the owning user id can change the setting.
1703 if (owningUserId != callingUserId) {
1704 return false;
1705 }
1706
Jeff Sharkey413573a2016-02-22 17:52:45 -07001707 // Invalidate any relevant cache files
1708 String cacheName = null;
1709 if (Settings.System.RINGTONE.equals(name)) {
1710 cacheName = Settings.System.RINGTONE_CACHE;
1711 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1712 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1713 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1714 cacheName = Settings.System.ALARM_ALERT_CACHE;
1715 }
1716 if (cacheName != null) {
1717 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001718 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001719 cacheFile.delete();
1720 }
1721
Svetoslav683914b2015-01-15 14:22:26 -08001722 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001723 synchronized (mLock) {
1724 switch (operation) {
1725 case MUTATION_OPERATION_INSERT: {
1726 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001727 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001728 owningUserId, name, value, null, false, getCallingPackage(),
1729 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001730 }
1731
1732 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001733 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001734 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001735 }
1736
1737 case MUTATION_OPERATION_UPDATE: {
1738 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001739 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001740 owningUserId, name, value, null, false, getCallingPackage(),
1741 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001742 }
Svetoslav683914b2015-01-15 14:22:26 -08001743 }
1744
Svetoslav7ec28e82015-05-20 17:01:10 -07001745 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001746 }
Svetoslav683914b2015-01-15 14:22:26 -08001747 }
1748
Billy Lau6ad2d662015-07-18 00:26:58 +01001749 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001750 // Write secure settings is a more protected permission. If caller has it we are good.
1751 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1752 == PackageManager.PERMISSION_GRANTED) {
1753 return true;
1754 }
1755
Svetoslavf41334b2015-06-23 12:06:03 -07001756 return false;
1757 }
1758
Svetoslav683914b2015-01-15 14:22:26 -08001759 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001760 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001761 if (validator != null && !validator.validate(value)) {
1762 throw new IllegalArgumentException("Invalid value: " + value
1763 + " for setting: " + name);
1764 }
1765 }
1766
Alex Klyubin1991f572017-03-03 14:08:36 -08001767 /**
1768 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1769 */
1770 private boolean isSecureSettingAccessible(String name, int callingUserId,
1771 int owningUserId) {
1772 // Special case for location (sigh).
1773 // This check is not inside the name-based checks below because this method performs checks
1774 // only if the calling user ID is not the same as the owning user ID.
1775 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1776 return false;
1777 }
1778
1779 switch (name) {
1780 case "bluetooth_address":
1781 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1782 // address in this secure setting. Secure settings can normally be read by any app,
1783 // which thus enables them to bypass the recently introduced restrictions on access
1784 // to device identifiers.
1785 // To mitigate this we make this setting available only to callers privileged to see
1786 // this device's MAC addresses, same as through public API
1787 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1788 return getContext().checkCallingOrSelfPermission(
1789 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1790 default:
1791 return true;
1792 }
1793 }
1794
Svetoslav683914b2015-01-15 14:22:26 -08001795 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1796 int owningUserId) {
1797 // Optimization - location providers are restricted only for managed profiles.
1798 if (callingUserId == owningUserId) {
1799 return false;
1800 }
1801 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1802 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1803 new UserHandle(callingUserId))) {
1804 return true;
1805 }
1806 return false;
1807 }
1808
Svetoslav683914b2015-01-15 14:22:26 -08001809 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1810 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1811 }
1812
1813 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001814 final int parentId;
1815 // Resolves dependency if setting has a dependency and the calling user has a parent
1816 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1817 && (parentId = getGroupParentLocked(userId)) != userId) {
1818 // The setting has a dependency and the profile has a parent
1819 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001820 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1821 final long token = Binder.clearCallingIdentity();
1822 try {
1823 Setting settingObj = getSecureSetting(dependency, userId);
1824 if (settingObj != null && settingObj.getValue().equals("1")) {
1825 return parentId;
1826 }
1827 } finally {
1828 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001829 }
1830 }
Svetoslav683914b2015-01-15 14:22:26 -08001831 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1832 }
1833
1834 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1835 final int parentId = getGroupParentLocked(userId);
1836 if (parentId != userId && keys.contains(name)) {
1837 return parentId;
1838 }
1839 return userId;
1840 }
1841
Svetoslavf41334b2015-06-23 12:06:03 -07001842 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001843 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001844 // System/root/shell can mutate whatever secure settings they want.
1845 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001846 final int appId = UserHandle.getAppId(callingUid);
1847 if (appId == android.os.Process.SYSTEM_UID
1848 || appId == Process.SHELL_UID
1849 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001850 return;
1851 }
1852
1853 switch (operation) {
1854 case MUTATION_OPERATION_INSERT:
1855 // Insert updates.
1856 case MUTATION_OPERATION_UPDATE: {
1857 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1858 return;
1859 }
1860
1861 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001862 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001863
1864 // Privileged apps can do whatever they want.
1865 if ((packageInfo.applicationInfo.privateFlags
1866 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1867 return;
1868 }
1869
1870 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1871 packageInfo.applicationInfo.targetSdkVersion, name);
1872 } break;
1873
1874 case MUTATION_OPERATION_DELETE: {
1875 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1876 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1877 throw new IllegalArgumentException("You cannot delete system defined"
1878 + " secure settings.");
1879 }
1880
1881 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001882 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001883
1884 // Privileged apps can do whatever they want.
1885 if ((packageInfo.applicationInfo.privateFlags &
1886 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1887 return;
1888 }
1889
1890 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1891 packageInfo.applicationInfo.targetSdkVersion, name);
1892 } break;
1893 }
1894 }
1895
Todd Kennedybe0b8892017-02-15 14:13:52 -08001896 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001897 switch (settingsType) {
1898 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001899 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001900 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001901 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001902 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001903 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001904 default:
1905 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1906 }
1907 }
1908
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001909 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1910 switch (settingsType) {
1911 case SETTINGS_TYPE_GLOBAL:
1912 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1913 case SETTINGS_TYPE_SYSTEM:
1914 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1915 case SETTINGS_TYPE_SECURE:
1916 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1917 default:
1918 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1919 }
1920 }
1921
Andreas Gampeb58893072018-09-05 16:52:31 -07001922 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001923 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001924 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1925 // in the current form.
1926 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001927 }
1928
Chad Brubakera6830e72017-04-28 17:34:36 -07001929 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001930 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1931 return;
1932 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001933 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001934 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001935 return;
1936 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001937 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1938 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001939 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1940 // breakage in the current form.
1941 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1942 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001943 }
1944 }
1945
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001946 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1947 // We always use the callingUid for this lookup. This means that if hypothetically an
1948 // app was installed in user A with cross user and in user B as an Instant App
1949 // the app in A would be able to see all the settings in user B. However since cross
1950 // user is a system permission and the app must be uninstalled in B and then installed as
1951 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001952 ApplicationInfo ai = null;
1953 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001954 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1955 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001956 } catch (RemoteException ignored) {
1957 }
1958 if (ai == null) {
1959 throw new IllegalStateException("Failed to lookup info for package "
1960 + getCallingPackage());
1961 }
1962 return ai;
1963 }
1964
Xiaohui Chen43765b72015-08-31 10:57:33 -07001965 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001966 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001967 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1968 getCallingPackage(), 0, userId);
1969 if (packageInfo != null) {
1970 return packageInfo;
1971 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001972 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001973 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001974 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001975 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001976 }
1977
1978 private int getGroupParentLocked(int userId) {
1979 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001980 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001981 return userId;
1982 }
1983 // We are in the same process with the user manager and the returned
1984 // user info is a cached instance, so just look up instead of cache.
1985 final long identity = Binder.clearCallingIdentity();
1986 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001987 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001988 UserInfo userInfo = mUserManager.getProfileParent(userId);
1989 return (userInfo != null) ? userInfo.id : userId;
1990 } finally {
1991 Binder.restoreCallingIdentity(identity);
1992 }
1993 }
1994
Svetoslav683914b2015-01-15 14:22:26 -08001995 private void enforceWritePermission(String permission) {
1996 if (getContext().checkCallingOrSelfPermission(permission)
1997 != PackageManager.PERMISSION_GRANTED) {
1998 throw new SecurityException("Permission denial: writing to settings requires:"
1999 + permission);
2000 }
2001 }
2002
2003 /*
2004 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2005 * This setting contains a list of the currently enabled location providers.
2006 * But helper functions in android.providers.Settings can enable or disable
2007 * a single provider by using a "+" or "-" prefix before the provider name.
2008 *
yuemingw1d13eae2018-01-30 17:27:54 +00002009 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2010 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2011 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002012 *
Svetoslav683914b2015-01-15 14:22:26 -08002013 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002014 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002015 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002016 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2017 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002018 if (TextUtils.isEmpty(value)) {
2019 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002020 }
Maggie83e03f52018-03-16 12:22:20 -07002021 Setting oldSetting = getSecureSetting(
2022 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2023 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002024 return false;
2025 }
Maggie83e03f52018-03-16 12:22:20 -07002026 String oldProviders = oldSetting.getValue();
2027 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2028 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2029 Set<String> newProvidersSet = new ArraySet<>();
2030 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002031
Maggie83e03f52018-03-16 12:22:20 -07002032 String[] providerUpdates = value.split(",");
2033 boolean inputError = false;
2034 for (String provider : providerUpdates) {
2035 // do not update location_providers_allowed when input is invalid
2036 if (TextUtils.isEmpty(provider)) {
2037 inputError = true;
2038 break;
Svetoslav683914b2015-01-15 14:22:26 -08002039 }
Maggie83e03f52018-03-16 12:22:20 -07002040 final char prefix = provider.charAt(0);
2041 // do not update location_providers_allowed when input is invalid
2042 if (prefix != '+' && prefix != '-') {
2043 inputError = true;
2044 break;
Svetoslav683914b2015-01-15 14:22:26 -08002045 }
Maggie83e03f52018-03-16 12:22:20 -07002046 // skip prefix
2047 provider = provider.substring(1);
2048 if (prefix == '+') {
2049 newProvidersSet.add(provider);
2050 } else if (prefix == '-') {
2051 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002052 }
Maggie83e03f52018-03-16 12:22:20 -07002053 }
2054 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2055 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002056 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002057 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002058 mSettingsRegistry.notifyForSettingsChange(
2059 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002060 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2061 }
Svetoslav683914b2015-01-15 14:22:26 -08002062 return false;
2063 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002064 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002065 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2066 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002067 }
2068
Svetoslav683914b2015-01-15 14:22:26 -08002069 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2070 int targetSdkVersion, String name) {
2071 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2072 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2073 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2074 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2075 + " This will soon become an error.");
2076 } else {
2077 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2078 + " This will soon become an error.");
2079 }
2080 } else {
2081 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2082 throw new IllegalArgumentException("You cannot change private secure settings.");
2083 } else {
2084 throw new IllegalArgumentException("You cannot keep your settings in"
2085 + " the secure settings.");
2086 }
2087 }
2088 }
2089
2090 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2091 if (requestingUserId == UserHandle.getCallingUserId()) {
2092 return requestingUserId;
2093 }
2094 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2095 Binder.getCallingUid(), requestingUserId, false, true,
2096 "get/set setting for user", null);
2097 }
2098
Svet Ganov53a441c2016-04-19 19:38:00 -07002099 private Bundle packageValueForCallResult(Setting setting,
2100 boolean trackingGeneration) {
2101 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002102 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002103 return NULL_SETTING_BUNDLE;
2104 }
2105 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002106 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002107 Bundle result = new Bundle();
2108 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002109 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002110
Svetoslav Ganove080da92016-12-21 17:10:35 -08002111 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002112 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002113 }
2114
2115 private static int getRequestingUserId(Bundle args) {
2116 final int callingUserId = UserHandle.getCallingUserId();
2117 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2118 : callingUserId;
2119 }
2120
Svet Ganov53a441c2016-04-19 19:38:00 -07002121 private boolean isTrackingGeneration(Bundle args) {
2122 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2123 }
2124
Svetoslav683914b2015-01-15 14:22:26 -08002125 private static String getSettingValue(Bundle args) {
2126 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2127 }
2128
Svetoslav Ganove080da92016-12-21 17:10:35 -08002129 private static String getSettingTag(Bundle args) {
2130 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2131 }
2132
Matt Pape6bfc62e2018-11-28 13:16:03 -08002133 private static String getSettingPrefix(Bundle args) {
2134 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2135 // Append '/' to ensure we only match properties with this exact prefix.
2136 // i.e. "foo" should match "foo/property" but not "foobar/property"
2137 return prefix != null ? prefix + "/" : null;
2138 }
2139
Svetoslav Ganove080da92016-12-21 17:10:35 -08002140 private static boolean getSettingMakeDefault(Bundle args) {
2141 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2142 }
2143
2144 private static int getResetModeEnforcingPermission(Bundle args) {
2145 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2146 switch (mode) {
2147 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2148 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2149 throw new SecurityException("Only system, shell/root on a "
2150 + "debuggable build can reset to untrusted defaults");
2151 }
2152 return mode;
2153 }
2154 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2155 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2156 throw new SecurityException("Only system, shell/root on a "
2157 + "debuggable build can reset untrusted changes");
2158 }
2159 return mode;
2160 }
2161 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2162 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2163 throw new SecurityException("Only system, shell/root on a "
2164 + "debuggable build can reset to trusted defaults");
2165 }
2166 return mode;
2167 }
2168 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2169 return mode;
2170 }
2171 }
2172 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2173 }
2174
2175 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2176 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2177 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2178 && (appId == SHELL_UID || appId == ROOT_UID));
2179 }
2180
Svetoslav683914b2015-01-15 14:22:26 -08002181 private static String getValidTableOrThrow(Uri uri) {
2182 if (uri.getPathSegments().size() > 0) {
2183 String table = uri.getPathSegments().get(0);
2184 if (DatabaseHelper.isValidTable(table)) {
2185 return table;
2186 }
2187 throw new IllegalArgumentException("Bad root path: " + table);
2188 }
2189 throw new IllegalArgumentException("Invalid URI:" + uri);
2190 }
2191
2192 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002193 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002194 return new MatrixCursor(projection, 0);
2195 }
2196 MatrixCursor cursor = new MatrixCursor(projection, 1);
2197 appendSettingToCursor(cursor, setting);
2198 return cursor;
2199 }
2200
2201 private static String[] normalizeProjection(String[] projection) {
2202 if (projection == null) {
2203 return ALL_COLUMNS;
2204 }
2205
2206 final int columnCount = projection.length;
2207 for (int i = 0; i < columnCount; i++) {
2208 String column = projection[i];
2209 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2210 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002211 }
2212 }
2213
Svetoslav683914b2015-01-15 14:22:26 -08002214 return projection;
2215 }
2216
2217 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002218 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002219 return;
2220 }
Svetoslav683914b2015-01-15 14:22:26 -08002221 final int columnCount = cursor.getColumnCount();
2222
2223 String[] values = new String[columnCount];
2224
2225 for (int i = 0; i < columnCount; i++) {
2226 String column = cursor.getColumnName(i);
2227
2228 switch (column) {
2229 case Settings.NameValueTable._ID: {
2230 values[i] = setting.getId();
2231 } break;
2232
2233 case Settings.NameValueTable.NAME: {
2234 values[i] = setting.getName();
2235 } break;
2236
2237 case Settings.NameValueTable.VALUE: {
2238 values[i] = setting.getValue();
2239 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002240 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002241 }
2242
Svetoslav683914b2015-01-15 14:22:26 -08002243 cursor.addRow(values);
2244 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002245
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002246 private static boolean isKeyValid(String key) {
2247 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2248 }
2249
Matt Pape7b1c6cd2019-01-04 08:10:41 -08002250 private String resolveCallingPackage() {
2251 switch (Binder.getCallingUid()) {
2252 case Process.ROOT_UID: {
2253 return "root";
2254 }
2255
2256 case Process.SHELL_UID: {
2257 return "com.android.shell";
2258 }
2259
2260 default: {
2261 return getCallingPackage();
2262 }
2263 }
2264 }
2265
Svetoslav683914b2015-01-15 14:22:26 -08002266 private static final class Arguments {
2267 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2268 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2269
2270 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2271 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2272
2273 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2274 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2275
2276 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2277 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2278
2279 public final String table;
2280 public final String name;
2281
2282 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2283 final int segmentSize = uri.getPathSegments().size();
2284 switch (segmentSize) {
2285 case 1: {
2286 if (where != null
2287 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2288 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2289 && whereArgs.length == 1) {
2290 name = whereArgs[0];
2291 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002292 return;
Svetoslav683914b2015-01-15 14:22:26 -08002293 } else if (where != null
2294 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2295 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2296 final int startIndex = Math.max(where.indexOf("'"),
2297 where.indexOf("\"")) + 1;
2298 final int endIndex = Math.max(where.lastIndexOf("'"),
2299 where.lastIndexOf("\""));
2300 name = where.substring(startIndex, endIndex);
2301 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002302 return;
Svetoslav683914b2015-01-15 14:22:26 -08002303 } else if (supportAll && where == null && whereArgs == null) {
2304 name = null;
2305 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002306 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002307 }
Svetoslav683914b2015-01-15 14:22:26 -08002308 } break;
2309
Svetoslav28494652015-02-12 14:11:42 -08002310 case 2: {
2311 if (where == null && whereArgs == null) {
2312 name = uri.getPathSegments().get(1);
2313 table = computeTableForSetting(uri, name);
2314 return;
2315 }
2316 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002317 }
Svetoslav28494652015-02-12 14:11:42 -08002318
2319 EventLogTags.writeUnsupportedSettingsQuery(
2320 uri.toSafeString(), where, Arrays.toString(whereArgs));
2321 String message = String.format( "Supported SQL:\n"
2322 + " uri content://some_table/some_property with null where and where args\n"
2323 + " uri content://some_table with query name=? and single name as arg\n"
2324 + " uri content://some_table with query name=some_name and null args\n"
2325 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2326 Arrays.toString(whereArgs));
2327 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002328 }
2329
Svetoslav28494652015-02-12 14:11:42 -08002330 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002331 String table = getValidTableOrThrow(uri);
2332
2333 if (name != null) {
2334 if (sSystemMovedToSecureSettings.contains(name)) {
2335 table = TABLE_SECURE;
2336 }
2337
2338 if (sSystemMovedToGlobalSettings.contains(name)) {
2339 table = TABLE_GLOBAL;
2340 }
2341
2342 if (sSecureMovedToGlobalSettings.contains(name)) {
2343 table = TABLE_GLOBAL;
2344 }
2345
2346 if (sGlobalMovedToSecureSettings.contains(name)) {
2347 table = TABLE_SECURE;
2348 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002349 }
Svetoslav683914b2015-01-15 14:22:26 -08002350
2351 return table;
2352 }
2353 }
2354
2355 final class SettingsRegistry {
2356 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2357
Svetoslav683914b2015-01-15 14:22:26 -08002358 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2359 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2360 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002361 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002362 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002363
2364 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002365
2366 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2367
Svet Ganov53a441c2016-04-19 19:38:00 -07002368 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002369
Svetoslav7e0683b2015-08-03 16:02:52 -07002370 private final Handler mHandler;
2371
Svet Ganov53a441c2016-04-19 19:38:00 -07002372 private final BackupManager mBackupManager;
2373
Amith Yamasani39452022017-03-21 15:23:47 -07002374 private String mSettingsCreationBuildId;
2375
Svetoslav683914b2015-01-15 14:22:26 -08002376 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002377 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002378 mGenerationRegistry = new GenerationRegistry(mLock);
2379 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002380 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002381 syncSsaidTableOnStart();
2382 }
2383
2384 private void generateUserKeyLocked(int userId) {
2385 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002386 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002387 final SecureRandom rand = new SecureRandom();
2388 rand.nextBytes(keyBytes);
2389
2390 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002391 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002392
2393 // Store the key in the ssaid table.
2394 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2395 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2396 true, SettingsState.SYSTEM_PACKAGE_NAME);
2397
2398 if (!success) {
2399 throw new IllegalStateException("Ssaid settings not accessible");
2400 }
2401 }
2402
Mark Rathjen7599f132017-01-23 14:15:54 -08002403 private byte[] getLengthPrefix(byte[] data) {
2404 return ByteBuffer.allocate(4).putInt(data.length).array();
2405 }
2406
Christopher Tateb218e762017-04-05 16:34:07 -07002407 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002408 // Read the user's key from the ssaid table.
2409 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002410 if (userKeySetting == null || userKeySetting.isNull()
2411 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002412 // Lazy initialize and store the user key.
2413 generateUserKeyLocked(userId);
2414 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002415 if (userKeySetting == null || userKeySetting.isNull()
2416 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002417 throw new IllegalStateException("User key not accessible");
2418 }
2419 }
2420 final String userKey = userKeySetting.getValue();
2421
2422 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002423 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2424
2425 // Validate that the key is of expected length.
2426 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2427 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002428 throw new IllegalStateException("User key invalid");
2429 }
2430
Mark Rathjen7599f132017-01-23 14:15:54 -08002431 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002432 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002433 m = Mac.getInstance("HmacSHA256");
2434 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002435 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002436 throw new IllegalStateException("HmacSHA256 is not available", e);
2437 } catch (InvalidKeyException e) {
2438 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002439 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002440
Mark Rathjenf42dd912017-06-05 19:04:34 -07002441 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002442 for (int i = 0; i < callingPkg.signatures.length; i++) {
2443 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002444 m.update(getLengthPrefix(sig), 0, 4);
2445 m.update(sig);
2446 }
Mark Rathjend891f012017-01-19 04:10:37 +00002447
2448 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002449 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2450 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002451
2452 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002453 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002454 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2455 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002456 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002457
2458 if (!success) {
2459 throw new IllegalStateException("Ssaid settings not accessible");
2460 }
2461
2462 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2463 }
2464
2465 public void syncSsaidTableOnStart() {
2466 synchronized (mLock) {
2467 // Verify that each user's packages and ssaid's are in sync.
2468 for (UserInfo user : mUserManager.getUsers(true)) {
2469 // Get all uids for the user's packages.
2470 final List<PackageInfo> packages;
2471 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002472 packages = mPackageManager.getInstalledPackages(
2473 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2474 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002475 } catch (RemoteException e) {
2476 throw new IllegalStateException("Package manager not available");
2477 }
2478 final Set<String> appUids = new HashSet<>();
2479 for (PackageInfo info : packages) {
2480 appUids.add(Integer.toString(info.applicationInfo.uid));
2481 }
2482
2483 // Get all uids currently stored in the user's ssaid table.
2484 final Set<String> ssaidUids = new HashSet<>(
2485 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2486 ssaidUids.remove(SSAID_USER_KEY);
2487
2488 // Perform a set difference for the appUids and ssaidUids.
2489 ssaidUids.removeAll(appUids);
2490
2491 // If there are ssaidUids left over they need to be removed from the table.
2492 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2493 user.id);
2494 for (String uid : ssaidUids) {
2495 ssaidSettings.deleteSettingLocked(uid);
2496 }
2497 }
2498 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002499 }
2500
Svetoslav683914b2015-01-15 14:22:26 -08002501 public List<String> getSettingsNamesLocked(int type, int userId) {
2502 final int key = makeKey(type, userId);
2503 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002504 if (settingsState == null) {
2505 return new ArrayList<String>();
2506 }
Svetoslav683914b2015-01-15 14:22:26 -08002507 return settingsState.getSettingNamesLocked();
2508 }
2509
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002510 public SparseBooleanArray getKnownUsersLocked() {
2511 SparseBooleanArray users = new SparseBooleanArray();
2512 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2513 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2514 }
2515 return users;
2516 }
2517
Kweku Adamsb0886f32017-10-31 15:32:09 -07002518 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002519 public SettingsState getSettingsLocked(int type, int userId) {
2520 final int key = makeKey(type, userId);
2521 return peekSettingsStateLocked(key);
2522 }
2523
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002524 public boolean ensureSettingsForUserLocked(int userId) {
2525 // First make sure this user actually exists.
2526 if (mUserManager.getUserInfo(userId) == null) {
2527 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2528 return false;
2529 }
2530
Svetoslav683914b2015-01-15 14:22:26 -08002531 // Migrate the setting for this user if needed.
2532 migrateLegacySettingsForUserIfNeededLocked(userId);
2533
Matt Pape1b31a332018-10-17 09:58:28 -07002534 // Ensure config settings loaded if owner.
2535 if (userId == UserHandle.USER_SYSTEM) {
2536 final int configKey
2537 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2538 ensureSettingsStateLocked(configKey);
2539 }
2540
Svetoslav683914b2015-01-15 14:22:26 -08002541 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002542 if (userId == UserHandle.USER_SYSTEM) {
2543 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002544 ensureSettingsStateLocked(globalKey);
2545 }
2546
2547 // Ensure secure settings loaded.
2548 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2549 ensureSettingsStateLocked(secureKey);
2550
2551 // Make sure the secure settings have an Android id set.
2552 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2553 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2554
2555 // Ensure system settings loaded.
2556 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2557 ensureSettingsStateLocked(systemKey);
2558
Mark Rathjend891f012017-01-19 04:10:37 +00002559 // Ensure secure settings loaded.
2560 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2561 ensureSettingsStateLocked(ssaidKey);
2562
Svetoslav683914b2015-01-15 14:22:26 -08002563 // Upgrade the settings to the latest version.
2564 UpgradeController upgrader = new UpgradeController(userId);
2565 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002566 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002567 }
2568
2569 private void ensureSettingsStateLocked(int key) {
2570 if (mSettingsStates.get(key) == null) {
2571 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002572 SettingsState settingsState = new SettingsState(getContext(), mLock,
2573 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002574 mSettingsStates.put(key, settingsState);
2575 }
2576 }
2577
2578 public void removeUserStateLocked(int userId, boolean permanently) {
2579 // We always keep the global settings in memory.
2580
2581 // Nuke system settings.
2582 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2583 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2584 if (systemSettingsState != null) {
2585 if (permanently) {
2586 mSettingsStates.remove(systemKey);
2587 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002588 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002589 systemSettingsState.destroyLocked(new Runnable() {
2590 @Override
2591 public void run() {
2592 mSettingsStates.remove(systemKey);
2593 }
2594 });
2595 }
2596 }
2597
2598 // Nuke secure settings.
2599 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2600 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2601 if (secureSettingsState != null) {
2602 if (permanently) {
2603 mSettingsStates.remove(secureKey);
2604 secureSettingsState.destroyLocked(null);
2605 } else {
2606 secureSettingsState.destroyLocked(new Runnable() {
2607 @Override
2608 public void run() {
2609 mSettingsStates.remove(secureKey);
2610 }
2611 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002612 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002613 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002614
Mark Rathjend891f012017-01-19 04:10:37 +00002615 // Nuke ssaid settings.
2616 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2617 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2618 if (ssaidSettingsState != null) {
2619 if (permanently) {
2620 mSettingsStates.remove(ssaidKey);
2621 ssaidSettingsState.destroyLocked(null);
2622 } else {
2623 ssaidSettingsState.destroyLocked(new Runnable() {
2624 @Override
2625 public void run() {
2626 mSettingsStates.remove(ssaidKey);
2627 }
2628 });
2629 }
2630 }
2631
Svet Ganov53a441c2016-04-19 19:38:00 -07002632 // Nuke generation tracking data
2633 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002634 }
2635
Svetoslav683914b2015-01-15 14:22:26 -08002636 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002637 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2638 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002639 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2640 packageName, forceNotify, criticalSettings);
2641 }
2642
2643 public boolean insertSettingLocked(int type, int userId, String name, String value,
2644 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2645 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002646 final int key = makeKey(type, userId);
2647
Svetoslav Ganove080da92016-12-21 17:10:35 -08002648 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002649 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002650 if (settingsState != null) {
2651 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002652 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002653 }
Svetoslav683914b2015-01-15 14:22:26 -08002654
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002655 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2656 settingsState.persistSyncLocked();
2657 }
2658
Svet Ganov53a441c2016-04-19 19:38:00 -07002659 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002660 notifyForSettingsChange(key, name);
2661 }
2662 return success;
2663 }
2664
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002665 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2666 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002667 final int key = makeKey(type, userId);
2668
Svetoslav Ganove080da92016-12-21 17:10:35 -08002669 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002670 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002671 if (settingsState != null) {
2672 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002673 }
Svetoslav683914b2015-01-15 14:22:26 -08002674
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002675 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2676 settingsState.persistSyncLocked();
2677 }
2678
Svet Ganov53a441c2016-04-19 19:38:00 -07002679 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002680 notifyForSettingsChange(key, name);
2681 }
2682 return success;
2683 }
2684
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002685 public boolean updateSettingLocked(int type, int userId, String name, String value,
2686 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2687 Set<String> criticalSettings) {
2688 final int key = makeKey(type, userId);
2689
2690 boolean success = false;
2691 SettingsState settingsState = peekSettingsStateLocked(key);
2692 if (settingsState != null) {
2693 success = settingsState.updateSettingLocked(name, value, tag,
2694 makeDefault, packageName);
2695 }
2696
2697 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2698 settingsState.persistSyncLocked();
2699 }
2700
2701 if (forceNotify || success) {
2702 notifyForSettingsChange(key, name);
2703 }
2704
2705 return success;
2706 }
2707
Svetoslav683914b2015-01-15 14:22:26 -08002708 public Setting getSettingLocked(int type, int userId, String name) {
2709 final int key = makeKey(type, userId);
2710
2711 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002712 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002713 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002714 }
Mark Rathjend891f012017-01-19 04:10:37 +00002715
2716 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002717 return settingsState.getSettingLocked(name);
2718 }
2719
Svetoslav Ganove080da92016-12-21 17:10:35 -08002720 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2721 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002722 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2723 }
2724
2725 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2726 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002727 final int key = makeKey(type, userId);
2728 SettingsState settingsState = peekSettingsStateLocked(key);
2729 if (settingsState == null) {
2730 return;
2731 }
2732
2733 switch (mode) {
2734 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2735 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002736 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002737 Setting setting = settingsState.getSettingLocked(name);
2738 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002739 if ((tag != null && !tag.equals(setting.getTag()))
2740 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002741 continue;
2742 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002743 if (settingsState.resetSettingLocked(name)) {
2744 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002745 notifyForSettingsChange(key, name);
2746 }
2747 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002748 if (someSettingChanged) {
2749 settingsState.persistSyncLocked();
2750 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002751 }
2752 } break;
2753
2754 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2755 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002756 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002757 Setting setting = settingsState.getSettingLocked(name);
2758 if (!SettingsState.isSystemPackage(getContext(),
2759 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002760 if (prefix != null && !setting.getName().startsWith(prefix)) {
2761 continue;
2762 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002763 if (settingsState.resetSettingLocked(name)) {
2764 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002765 notifyForSettingsChange(key, name);
2766 }
2767 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002768 if (someSettingChanged) {
2769 settingsState.persistSyncLocked();
2770 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002771 }
2772 } break;
2773
2774 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2775 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002776 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002777 Setting setting = settingsState.getSettingLocked(name);
2778 if (!SettingsState.isSystemPackage(getContext(),
2779 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002780 if (prefix != null && !setting.getName().startsWith(prefix)) {
2781 continue;
2782 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002783 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002784 if (settingsState.resetSettingLocked(name)) {
2785 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002786 notifyForSettingsChange(key, name);
2787 }
2788 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002789 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002790 notifyForSettingsChange(key, name);
2791 }
2792 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002793 if (someSettingChanged) {
2794 settingsState.persistSyncLocked();
2795 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002796 }
2797 } break;
2798
2799 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2800 for (String name : settingsState.getSettingNamesLocked()) {
2801 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002802 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002803 if (prefix != null && !setting.getName().startsWith(prefix)) {
2804 continue;
2805 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002806 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002807 if (settingsState.resetSettingLocked(name)) {
2808 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002809 notifyForSettingsChange(key, name);
2810 }
2811 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002812 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002813 notifyForSettingsChange(key, name);
2814 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002815 if (someSettingChanged) {
2816 settingsState.persistSyncLocked();
2817 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002818 }
2819 } break;
2820 }
2821 }
2822
Zimuzoc56192c2018-07-25 10:40:01 +01002823 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002824 // Global and secure settings are signature protected. Apps signed
2825 // by the platform certificate are generally not uninstalled and
2826 // the main exception is tests. We trust components signed
2827 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002828
2829 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2830 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002831 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002832 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002833 }
Svetoslav683914b2015-01-15 14:22:26 -08002834 }
2835
Mark Rathjend891f012017-01-19 04:10:37 +00002836 public void onUidRemovedLocked(int uid) {
2837 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2838 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002839 if (ssaidSettings != null) {
2840 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2841 }
Mark Rathjend891f012017-01-19 04:10:37 +00002842 }
2843
Kweku Adamsb0886f32017-10-31 15:32:09 -07002844 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002845 private SettingsState peekSettingsStateLocked(int key) {
2846 SettingsState settingsState = mSettingsStates.get(key);
2847 if (settingsState != null) {
2848 return settingsState;
2849 }
2850
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002851 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2852 return null;
2853 }
Svetoslav683914b2015-01-15 14:22:26 -08002854 return mSettingsStates.get(key);
2855 }
2856
2857 private void migrateAllLegacySettingsIfNeeded() {
2858 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002859 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002860 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002861 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002862 return;
2863 }
2864
Amith Yamasani39452022017-03-21 15:23:47 -07002865 mSettingsCreationBuildId = Build.ID;
2866
Svetoslav683914b2015-01-15 14:22:26 -08002867 final long identity = Binder.clearCallingIdentity();
2868 try {
2869 List<UserInfo> users = mUserManager.getUsers(true);
2870
2871 final int userCount = users.size();
2872 for (int i = 0; i < userCount; i++) {
2873 final int userId = users.get(i).id;
2874
2875 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2876 SQLiteDatabase database = dbHelper.getWritableDatabase();
2877 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2878
2879 // Upgrade to the latest version.
2880 UpgradeController upgrader = new UpgradeController(userId);
2881 upgrader.upgradeIfNeededLocked();
2882
2883 // Drop from memory if not a running user.
2884 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2885 removeUserStateLocked(userId, false);
2886 }
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(identity);
2890 }
2891 }
2892 }
2893
2894 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2895 // Every user has secure settings and if no file we need to migrate.
2896 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2897 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002898 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002899 return;
2900 }
2901
2902 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2903 SQLiteDatabase database = dbHelper.getWritableDatabase();
2904
2905 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2906 }
2907
2908 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2909 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002910 // Move over the system settings.
2911 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2912 ensureSettingsStateLocked(systemKey);
2913 SettingsState systemSettings = mSettingsStates.get(systemKey);
2914 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2915 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002916
2917 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002918 // Do this after System settings, since this is the first thing we check when deciding
2919 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002920 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2921 ensureSettingsStateLocked(secureKey);
2922 SettingsState secureSettings = mSettingsStates.get(secureKey);
2923 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2924 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2925 secureSettings.persistSyncLocked();
2926
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002927 // Move over the global settings if owner.
2928 // Do this last, since this is the first thing we check when deciding
2929 // to skip over migration from db to xml for owner user.
2930 if (userId == UserHandle.USER_SYSTEM) {
2931 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2932 ensureSettingsStateLocked(globalKey);
2933 SettingsState globalSettings = mSettingsStates.get(globalKey);
2934 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002935 // If this was just created
2936 if (mSettingsCreationBuildId != null) {
2937 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2938 mSettingsCreationBuildId, null, true,
2939 SettingsState.SYSTEM_PACKAGE_NAME);
2940 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002941 globalSettings.persistSyncLocked();
2942 }
Svetoslav683914b2015-01-15 14:22:26 -08002943
2944 // Drop the database as now all is moved and persisted.
2945 if (DROP_DATABASE_ON_MIGRATION) {
2946 dbHelper.dropDatabase();
2947 } else {
2948 dbHelper.backupDatabase();
2949 }
2950 }
2951
2952 private void migrateLegacySettingsLocked(SettingsState settingsState,
2953 SQLiteDatabase database, String table) {
2954 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2955 queryBuilder.setTables(table);
2956
2957 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2958 null, null, null, null, null);
2959
2960 if (cursor == null) {
2961 return;
2962 }
2963
2964 try {
2965 if (!cursor.moveToFirst()) {
2966 return;
2967 }
2968
2969 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2970 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2971
2972 settingsState.setVersionLocked(database.getVersion());
2973
2974 while (!cursor.isAfterLast()) {
2975 String name = cursor.getString(nameColumnIdx);
2976 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002977 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002978 SettingsState.SYSTEM_PACKAGE_NAME);
2979 cursor.moveToNext();
2980 }
2981 } finally {
2982 cursor.close();
2983 }
2984 }
2985
Andreas Gampeb58893072018-09-05 16:52:31 -07002986 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002987 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2988 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2989
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002990 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002991 return;
2992 }
2993
2994 final int userId = getUserIdFromKey(secureSettings.mKey);
2995
2996 final UserInfo user;
2997 final long identity = Binder.clearCallingIdentity();
2998 try {
2999 user = mUserManager.getUserInfo(userId);
3000 } finally {
3001 Binder.restoreCallingIdentity(identity);
3002 }
3003 if (user == null) {
3004 // Can happen due to races when deleting users - treat as benign.
3005 return;
3006 }
3007
3008 String androidId = Long.toHexString(new SecureRandom().nextLong());
3009 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003010 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003011
3012 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3013 + "] for user " + userId);
3014
3015 // Write a drop box entry if it's a restricted profile
3016 if (user.isRestricted()) {
3017 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3018 Context.DROPBOX_SERVICE);
3019 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3020 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3021 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3022 }
3023 }
3024 }
3025
3026 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003027 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003028 mGenerationRegistry.incrementGeneration(key);
3029
Svet Ganov945864c2018-03-22 21:49:10 -07003030 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003031 final long token = Binder.clearCallingIdentity();
3032 try {
3033 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3034 // When the global kill switch is updated, send the
3035 // change notification for the location setting.
3036 notifyLocationChangeForRunningUsers();
3037 }
3038 notifyGlobalSettingChangeForRunningUsers(key, name);
3039 } finally {
3040 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003041 }
Svet Ganov945864c2018-03-22 21:49:10 -07003042 } else {
3043 final int userId = getUserIdFromKey(key);
3044 final Uri uri = getNotificationUriFor(key, name);
3045 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3046 userId, 0, uri).sendToTarget();
3047 if (isSecureSettingsKey(key)) {
3048 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3049 sSecureCloneToManagedSettings);
3050 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3051 sSystemCloneFromParentOnDependency.values());
3052 } else if (isSystemSettingsKey(key)) {
3053 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3054 sSystemCloneToManagedSettings);
3055 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003056 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003057
Svet Ganov945864c2018-03-22 21:49:10 -07003058 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003059 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003060 }
3061
Svet Ganov53a441c2016-04-19 19:38:00 -07003062 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003063 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003064 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003065 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003066 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003067 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003068 final int key = makeKey(type, profileId);
3069 // Increment the generation first, so observers always see the new value
3070 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003071 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003072 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003073 }
3074 }
3075 }
Svetoslav683914b2015-01-15 14:22:26 -08003076 }
3077
Svet Ganov945864c2018-03-22 21:49:10 -07003078 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3079 // Important: No need to update generation for each user as there
3080 // is a singleton generation entry for the global settings which
3081 // is already incremented be the caller.
3082 final Uri uri = getNotificationUriFor(key, name);
3083 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3084 for (int i = 0; i < users.size(); i++) {
3085 final int userId = users.get(i).id;
3086 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3087 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3088 userId, 0, uri).sendToTarget();
3089 }
3090 }
3091 }
3092
Makoto Onuki0000d322017-11-28 16:31:47 -08003093 private void notifyLocationChangeForRunningUsers() {
3094 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3095
3096 for (int i = 0; i < users.size(); i++) {
3097 final int userId = users.get(i).id;
3098
3099 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3100 continue;
3101 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003102
Svet Ganov945864c2018-03-22 21:49:10 -07003103 // Increment the generation first, so observers always see the new value
3104 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3105 mGenerationRegistry.incrementGeneration(key);
3106
3107 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003108 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3109 userId, 0, uri).sendToTarget();
3110 }
3111 }
3112
Matt Pape1b31a332018-10-17 09:58:28 -07003113 private boolean isConfigSettingsKey(int key) {
3114 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3115 }
3116
Svetoslav683914b2015-01-15 14:22:26 -08003117 private boolean isGlobalSettingsKey(int key) {
3118 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3119 }
3120
3121 private boolean isSystemSettingsKey(int key) {
3122 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3123 }
3124
3125 private boolean isSecureSettingsKey(int key) {
3126 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3127 }
3128
Mark Rathjend891f012017-01-19 04:10:37 +00003129 private boolean isSsaidSettingsKey(int key) {
3130 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3131 }
3132
Svetoslav683914b2015-01-15 14:22:26 -08003133 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003134 if (isConfigSettingsKey(key)) {
3135 final int userId = getUserIdFromKey(key);
3136 return new File(Environment.getUserSystemDirectory(userId),
3137 SETTINGS_FILE_CONFIG);
3138 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003139 final int userId = getUserIdFromKey(key);
3140 return new File(Environment.getUserSystemDirectory(userId),
3141 SETTINGS_FILE_GLOBAL);
3142 } else if (isSystemSettingsKey(key)) {
3143 final int userId = getUserIdFromKey(key);
3144 return new File(Environment.getUserSystemDirectory(userId),
3145 SETTINGS_FILE_SYSTEM);
3146 } else if (isSecureSettingsKey(key)) {
3147 final int userId = getUserIdFromKey(key);
3148 return new File(Environment.getUserSystemDirectory(userId),
3149 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003150 } else if (isSsaidSettingsKey(key)) {
3151 final int userId = getUserIdFromKey(key);
3152 return new File(Environment.getUserSystemDirectory(userId),
3153 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003154 } else {
3155 throw new IllegalArgumentException("Invalid settings key:" + key);
3156 }
3157 }
3158
3159 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003160 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003161 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3162 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003163 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003164 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3165 : Settings.Global.CONTENT_URI;
3166 } else if (isSecureSettingsKey(key)) {
3167 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3168 : Settings.Secure.CONTENT_URI;
3169 } else if (isSystemSettingsKey(key)) {
3170 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3171 : Settings.System.CONTENT_URI;
3172 } else {
3173 throw new IllegalArgumentException("Invalid settings key:" + key);
3174 }
3175 }
3176
3177 private int getMaxBytesPerPackageForType(int type) {
3178 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003179 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003180 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003181 case SETTINGS_TYPE_SECURE:
3182 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003183 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3184 }
3185
3186 default: {
3187 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3188 }
3189 }
3190 }
3191
Svetoslav7e0683b2015-08-03 16:02:52 -07003192 private final class MyHandler extends Handler {
3193 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3194 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3195
3196 public MyHandler(Looper looper) {
3197 super(looper);
3198 }
3199
3200 @Override
3201 public void handleMessage(Message msg) {
3202 switch (msg.what) {
3203 case MSG_NOTIFY_URI_CHANGED: {
3204 final int userId = msg.arg1;
3205 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003206 try {
3207 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3208 } catch (SecurityException e) {
3209 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3210 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003211 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003212 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3213 }
3214 } break;
3215
3216 case MSG_NOTIFY_DATA_CHANGED: {
3217 mBackupManager.dataChanged();
3218 } break;
3219 }
3220 }
3221 }
3222
Svetoslav683914b2015-01-15 14:22:26 -08003223 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003224 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003225
3226 private final int mUserId;
3227
3228 public UpgradeController(int userId) {
3229 mUserId = userId;
3230 }
3231
3232 public void upgradeIfNeededLocked() {
3233 // The version of all settings for a user is the same (all users have secure).
3234 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003235 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003236
3237 // Try an update from the current state.
3238 final int oldVersion = secureSettings.getVersionLocked();
3239 final int newVersion = SETTINGS_VERSION;
3240
Svet Ganovc9755bc2015-03-28 13:21:22 -07003241 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003242 if (oldVersion == newVersion) {
3243 return;
3244 }
3245
3246 // Try to upgrade.
3247 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3248
3249 // If upgrade failed start from scratch and upgrade.
3250 if (curVersion != newVersion) {
3251 // Drop state we have for this user.
3252 removeUserStateLocked(mUserId, true);
3253
3254 // Recreate the database.
3255 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3256 SQLiteDatabase database = dbHelper.getWritableDatabase();
3257 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3258
3259 // Migrate the settings for this user.
3260 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3261
3262 // Now upgrade should work fine.
3263 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003264
3265 // Make a note what happened, so we don't wonder why data was lost
3266 String reason = "Settings rebuilt! Current version: "
3267 + curVersion + " while expected: " + newVersion;
3268 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003269 Settings.Global.DATABASE_DOWNGRADE_REASON,
3270 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003271 }
3272
3273 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003274 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003275 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003276 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003277 globalSettings.setVersionLocked(newVersion);
3278 }
3279
3280 // Set the secure settings version.
3281 secureSettings.setVersionLocked(newVersion);
3282
3283 // Set the system settings version.
3284 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003285 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003286 systemSettings.setVersionLocked(newVersion);
3287 }
3288
3289 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003290 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003291 }
3292
3293 private SettingsState getSecureSettingsLocked(int userId) {
3294 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3295 }
3296
Mark Rathjend891f012017-01-19 04:10:37 +00003297 private SettingsState getSsaidSettingsLocked(int userId) {
3298 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3299 }
3300
Svetoslav683914b2015-01-15 14:22:26 -08003301 private SettingsState getSystemSettingsLocked(int userId) {
3302 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3303 }
3304
Jeff Brown503cffc2015-03-26 18:08:51 -07003305 /**
3306 * You must perform all necessary mutations to bring the settings
3307 * for this user from the old to the new version. When you add a new
3308 * upgrade step you *must* update SETTINGS_VERSION.
3309 *
3310 * This is an example of moving a setting from secure to global.
3311 *
3312 * // v119: Example settings changes.
3313 * if (currentVersion == 118) {
3314 * if (userId == UserHandle.USER_OWNER) {
3315 * // Remove from the secure settings.
3316 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3317 * String name = "example_setting_to_move";
3318 * String value = secureSettings.getSetting(name);
3319 * secureSettings.deleteSetting(name);
3320 *
3321 * // Add to the global settings.
3322 * SettingsState globalSettings = getGlobalSettingsLocked();
3323 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3324 * }
3325 *
3326 * // Update the current version.
3327 * currentVersion = 119;
3328 * }
3329 */
Svetoslav683914b2015-01-15 14:22:26 -08003330 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3331 if (DEBUG) {
3332 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3333 + oldVersion + " to version: " + newVersion);
3334 }
3335
Jeff Brown503cffc2015-03-26 18:08:51 -07003336 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003337
John Spurlocke11ae112015-05-11 16:09:03 -04003338 // v119: Reset zen + ringer mode.
3339 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003340 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003341 final SettingsState globalSettings = getGlobalSettingsLocked();
3342 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003343 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3344 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003345 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003346 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3347 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003348 }
3349 currentVersion = 119;
3350 }
3351
Jason Monk27bbb2d2015-03-31 16:46:39 -04003352 // v120: Add double tap to wake setting.
3353 if (currentVersion == 119) {
3354 SettingsState secureSettings = getSecureSettingsLocked(userId);
3355 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3356 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003357 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003358 SettingsState.SYSTEM_PACKAGE_NAME);
3359
3360 currentVersion = 120;
3361 }
3362
Svetoslav7e0683b2015-08-03 16:02:52 -07003363 if (currentVersion == 120) {
3364 // Before 121, we used a different string encoding logic. We just bump the
3365 // version here; SettingsState knows how to handle pre-version 120 files.
3366 currentVersion = 121;
3367 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003368
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003369 if (currentVersion == 121) {
3370 // Version 122: allow OEMs to set a default payment component in resources.
3371 // Note that we only write the default if no default has been set;
3372 // if there is, we just leave the default at whatever it currently is.
3373 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3374 String defaultComponent = (getContext().getResources().getString(
3375 R.string.def_nfc_payment_component));
3376 Setting currentSetting = secureSettings.getSettingLocked(
3377 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3378 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003379 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003380 secureSettings.insertSettingLocked(
3381 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003382 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003383 }
3384 currentVersion = 122;
3385 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003386
3387 if (currentVersion == 122) {
3388 // Version 123: Adding a default value for the ability to add a user from
3389 // the lock screen.
3390 if (userId == UserHandle.USER_SYSTEM) {
3391 final SettingsState globalSettings = getGlobalSettingsLocked();
3392 Setting currentSetting = globalSettings.getSettingLocked(
3393 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003394 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003395 globalSettings.insertSettingLocked(
3396 Settings.Global.ADD_USERS_WHEN_LOCKED,
3397 getContext().getResources().getBoolean(
3398 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003399 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003400 }
3401 }
3402 currentVersion = 123;
3403 }
Bryce Leebd179282015-12-17 19:01:37 -08003404
3405 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003406 final SettingsState globalSettings = getGlobalSettingsLocked();
3407 String defaultDisabledProfiles = (getContext().getResources().getString(
3408 R.string.def_bluetooth_disabled_profiles));
3409 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003410 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003411 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003412 }
3413
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003414 if (currentVersion == 124) {
3415 // Version 124: allow OEMs to set a default value for whether IME should be
3416 // shown when a physical keyboard is connected.
3417 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3418 Setting currentSetting = secureSettings.getSettingLocked(
3419 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003420 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003421 secureSettings.insertSettingLocked(
3422 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3423 getContext().getResources().getBoolean(
3424 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003425 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003426 }
3427 currentVersion = 125;
3428 }
3429
Ruben Brunk98576cf2016-03-07 18:54:28 -08003430 if (currentVersion == 125) {
3431 // Version 125: Allow OEMs to set the default VR service.
3432 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3433
3434 Setting currentSetting = secureSettings.getSettingLocked(
3435 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003436 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003437 ArraySet<ComponentName> l =
3438 SystemConfig.getInstance().getDefaultVrComponents();
3439
3440 if (l != null && !l.isEmpty()) {
3441 StringBuilder b = new StringBuilder();
3442 boolean start = true;
3443 for (ComponentName c : l) {
3444 if (!start) {
3445 b.append(':');
3446 }
3447 b.append(c.flattenToString());
3448 start = false;
3449 }
3450 secureSettings.insertSettingLocked(
3451 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003452 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003453 }
3454
3455 }
3456 currentVersion = 126;
3457 }
3458
Daniel U02ba6122016-04-01 18:41:42 +01003459 if (currentVersion == 126) {
3460 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3461 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3462 if (mUserManager.isManagedProfile(userId)) {
3463 final SettingsState systemSecureSettings =
3464 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3465
3466 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3467 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003468 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003469 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3470 secureSettings.insertSettingLocked(
3471 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003472 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003473 SettingsState.SYSTEM_PACKAGE_NAME);
3474 }
3475
3476 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3477 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003478 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003479 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3480 secureSettings.insertSettingLocked(
3481 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003482 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003483 SettingsState.SYSTEM_PACKAGE_NAME);
3484 }
3485 }
3486 currentVersion = 127;
3487 }
3488
Steven Ngdc20ba62016-04-26 18:19:04 +01003489 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003490 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003491 currentVersion = 128;
3492 }
3493
Julia Reynolds1f721e12016-07-11 08:50:58 -04003494 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003495 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003496 currentVersion = 129;
3497 }
3498
Dan Sandler71f85e92016-07-20 13:46:05 -04003499 if (currentVersion == 129) {
3500 // default longpress timeout changed from 500 to 400. If unchanged from the old
3501 // default, update to the new default.
3502 final SettingsState systemSecureSettings =
3503 getSecureSettingsLocked(userId);
3504 final String oldValue = systemSecureSettings.getSettingLocked(
3505 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3506 if (TextUtils.equals("500", oldValue)) {
3507 systemSecureSettings.insertSettingLocked(
3508 Settings.Secure.LONG_PRESS_TIMEOUT,
3509 String.valueOf(getContext().getResources().getInteger(
3510 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003511 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003512 }
3513 currentVersion = 130;
3514 }
3515
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003516 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003517 // Split Ambient settings
3518 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3519 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3520 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3521
3522 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003523 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003524 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003525 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003526 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003527 }
3528 currentVersion = 131;
3529 }
3530
3531 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003532 // Initialize new multi-press timeout to default value
3533 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3534 final String oldValue = systemSecureSettings.getSettingLocked(
3535 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3536 if (TextUtils.equals(null, oldValue)) {
3537 systemSecureSettings.insertSettingLocked(
3538 Settings.Secure.MULTI_PRESS_TIMEOUT,
3539 String.valueOf(getContext().getResources().getInteger(
3540 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003541 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003542 }
3543
Adrian Roos69741a22016-10-21 14:49:17 -07003544 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003545 }
3546
Adrian Roos69741a22016-10-21 14:49:17 -07003547 if (currentVersion == 132) {
3548 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003549 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3550 String defaultSyncParentSounds = (getContext().getResources()
3551 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3552 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003553 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3554 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003555 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003556 }
3557
Adrian Roos69741a22016-10-21 14:49:17 -07003558 if (currentVersion == 133) {
3559 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003560 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003561 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3562 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003563 String defaultEndButtonBehavior = Integer.toString(getContext()
3564 .getResources().getInteger(R.integer.def_end_button_behavior));
3565 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003566 defaultEndButtonBehavior, null, true,
3567 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003568 }
Adrian Roos69741a22016-10-21 14:49:17 -07003569 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003570 }
3571
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003572 if (currentVersion == 134) {
3573 // Remove setting that specifies if magnification values should be preserved.
3574 // This setting defaulted to true and never has a UI.
3575 getSecureSettingsLocked(userId).deleteSettingLocked(
3576 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3577 currentVersion = 135;
3578 }
3579
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003580 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003581 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003582 currentVersion = 136;
3583 }
3584
Mark Rathjend891f012017-01-19 04:10:37 +00003585 if (currentVersion == 136) {
3586 // Version 136: Store legacy SSAID for all apps currently installed on the
3587 // device as first step in migrating SSAID to be unique per application.
3588
3589 final boolean isUpgrade;
3590 try {
3591 isUpgrade = mPackageManager.isUpgrade();
3592 } catch (RemoteException e) {
3593 throw new IllegalStateException("Package manager not available");
3594 }
3595 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3596 // user data or first boot on a new device should use new ssaid generation.
3597 if (isUpgrade) {
3598 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003599 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3600 userId, Settings.Secure.ANDROID_ID);
3601 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3602 || legacySsaidSetting.getValue() == null) {
3603 throw new IllegalStateException("Legacy ssaid not accessible");
3604 }
3605 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003606
3607 // Fill each uid with the legacy ssaid to be backwards compatible.
3608 final List<PackageInfo> packages;
3609 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003610 packages = mPackageManager.getInstalledPackages(
3611 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3612 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003613 } catch (RemoteException e) {
3614 throw new IllegalStateException("Package manager not available");
3615 }
3616
3617 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3618 for (PackageInfo info : packages) {
3619 // Check if the UID already has an entry in the table.
3620 final String uid = Integer.toString(info.applicationInfo.uid);
3621 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3622
3623 if (ssaid.isNull() || ssaid.getValue() == null) {
3624 // Android Id doesn't exist for this package so create it.
3625 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3626 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003627 if (DEBUG) {
3628 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3629 }
Mark Rathjend891f012017-01-19 04:10:37 +00003630 }
3631 }
3632 }
3633
3634 currentVersion = 137;
3635 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003636 if (currentVersion == 137) {
3637 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3638 // default value set to 1. The user can no longer change the value of this
3639 // setting through the UI.
3640 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3641 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003642 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3643 && secureSetting.getSettingLocked(
3644 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3645
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003646 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3647 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003648 // For managed profiles with profile owners, DevicePolicyManagerService
3649 // may want to set the user restriction in this case
3650 secureSetting.insertSettingLocked(
3651 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3652 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003653 }
3654 currentVersion = 138;
3655 }
Mark Rathjend891f012017-01-19 04:10:37 +00003656
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003657 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003658 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003659 currentVersion = 139;
3660 }
3661
Phil Weaver385912e2017-02-10 10:06:56 -08003662 if (currentVersion == 139) {
3663 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3664 // the user can no longer change the value of this setting through the UI.
3665 // Force to true.
3666 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3667 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3668 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3669 currentVersion = 140;
3670 }
3671
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003672 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003673 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003674 currentVersion = 141;
3675 }
3676
Svet Ganov13701552017-02-23 12:45:17 -08003677 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003678 // This implementation was incorrectly setting the current value of
3679 // settings changed by non-system packages as the default which default
3680 // is set by the system. We add a new upgrade step at the end to properly
3681 // handle this case which would also fix incorrect changes made by the
3682 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003683 currentVersion = 142;
3684 }
3685
Stephen Chen5d0922f2017-03-27 10:28:04 -07003686 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003687 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003688 if (userId == UserHandle.USER_SYSTEM) {
3689 final SettingsState globalSettings = getGlobalSettingsLocked();
3690 Setting currentSetting = globalSettings.getSettingLocked(
3691 Settings.Global.WIFI_WAKEUP_ENABLED);
3692 if (currentSetting.isNull()) {
3693 globalSettings.insertSettingLocked(
3694 Settings.Global.WIFI_WAKEUP_ENABLED,
3695 getContext().getResources().getBoolean(
3696 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3697 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3698 }
3699 }
3700
3701 currentVersion = 143;
3702 }
3703
Felipe Lemeff355092017-04-03 12:55:02 -07003704 if (currentVersion == 143) {
3705 // Version 144: Set a default value for Autofill service.
3706 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3707 final Setting currentSetting = secureSettings
3708 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3709 if (currentSetting.isNull()) {
3710 final String defaultValue = getContext().getResources().getString(
3711 com.android.internal.R.string.config_defaultAutofillService);
3712 if (defaultValue != null) {
3713 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3714 + "for user " + userId);
3715 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3716 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3717 }
3718 }
3719
3720 currentVersion = 144;
3721 }
3722
Jeremy Joslin45caa252017-05-04 11:22:46 -07003723 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003724 // Version 145: Removed
3725 currentVersion = 145;
3726 }
3727
3728 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003729 // Version 146: In step 142 we had a bug where incorrectly
3730 // some settings were considered system set and as a result
3731 // made the default and marked as the default being set by
3732 // the system. Here reevaluate the default and default system
3733 // set flags. This would both fix corruption by the old impl
3734 // of step 142 and also properly handle devices which never
3735 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003736 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003737 SettingsState globalSettings = getGlobalSettingsLocked();
3738 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3739 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003740 }
3741
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003742 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3743 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3744 secureSettings.persistSyncLocked();
3745
3746 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3747 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3748 systemSettings.persistSyncLocked();
3749
Amin Shaikh86367962017-06-07 08:58:22 -07003750 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003751 }
3752
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003753 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003754 // Version 147: Removed. (This version previously allowed showing the
3755 // "wifi_wakeup_available" setting).
3756 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003757 currentVersion = 147;
3758 }
3759
3760 if (currentVersion == 147) {
3761 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003762 if (userId == UserHandle.USER_SYSTEM) {
3763 final SettingsState globalSettings = getGlobalSettingsLocked();
3764 final Setting currentSetting = globalSettings.getSettingLocked(
3765 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3766 if (currentSetting.isNull()) {
3767 globalSettings.insertSettingLocked(
3768 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3769 getContext().getResources().getBoolean(
3770 R.bool.def_restrict_background_data) ? "1" : "0",
3771 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3772 }
3773 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003774 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003775 }
3776
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003777 if (currentVersion == 148) {
3778 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3779 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3780 final String oldValue = systemSecureSettings.getSettingLocked(
3781 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3782 if (TextUtils.equals(null, oldValue)) {
3783 final String defaultValue = getContext().getResources().getString(
3784 R.string.def_backup_manager_constants);
3785 if (!TextUtils.isEmpty(defaultValue)) {
3786 systemSecureSettings.insertSettingLocked(
3787 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3788 true, SettingsState.SYSTEM_PACKAGE_NAME);
3789 }
3790 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003791 currentVersion = 149;
3792 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003793
3794 if (currentVersion == 149) {
3795 // Version 150: Set a default value for mobile data always on
3796 final SettingsState globalSettings = getGlobalSettingsLocked();
3797 final Setting currentSetting = globalSettings.getSettingLocked(
3798 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3799 if (currentSetting.isNull()) {
3800 globalSettings.insertSettingLocked(
3801 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3802 getContext().getResources().getBoolean(
3803 R.bool.def_mobile_data_always_on) ? "1" : "0",
3804 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3805 }
3806
3807 currentVersion = 150;
3808 }
3809
Mike Digman4af4a6f2018-01-16 14:49:38 -08003810 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003811 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003812 currentVersion = 151;
3813 }
3814
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003815 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003816 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3817 // by default but it is now no longer configurable).
3818 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003819 currentVersion = 152;
3820 }
3821
Joe LaPenna250d7842018-01-25 10:19:42 -08003822 if (currentVersion == 152) {
3823 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3824 currentVersion = 153;
3825 }
3826
Ben Linb4df8bc2018-01-29 11:48:20 -08003827 if (currentVersion == 153) {
3828 // Version 154: Read notification badge configuration from config.
3829 // If user has already set the value, don't do anything.
3830 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3831 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3832 Settings.Secure.NOTIFICATION_BADGING);
3833 if (showNotificationBadges.isNull()) {
3834 final boolean defaultValue = getContext().getResources().getBoolean(
3835 com.android.internal.R.bool.config_notificationBadging);
3836 systemSecureSettings.insertSettingLocked(
3837 Secure.NOTIFICATION_BADGING,
3838 defaultValue ? "1" : "0",
3839 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3840 }
3841 currentVersion = 154;
3842 }
3843
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003844 if (currentVersion == 154) {
3845 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3846 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3847 final String oldValue = systemSecureSettings.getSettingLocked(
3848 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3849 if (TextUtils.equals(null, oldValue)) {
3850 final String defaultValue = getContext().getResources().getString(
3851 R.string.def_backup_local_transport_parameters);
3852 if (!TextUtils.isEmpty(defaultValue)) {
3853 systemSecureSettings.insertSettingLocked(
3854 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3855 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3856 }
3857
3858 }
3859 currentVersion = 155;
3860 }
3861
Beverlyda904812018-03-02 09:55:30 -05003862 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003863 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003864 final SettingsState globalSettings = getGlobalSettingsLocked();
3865 final String oldValue = globalSettings.getSettingLocked(
3866 Global.CHARGING_STARTED_SOUND).getValue();
3867 final String oldDefault = getContext().getResources().getString(
3868 R.string.def_wireless_charging_started_sound);
3869 if (TextUtils.equals(null, oldValue)
3870 || TextUtils.equals(oldValue, oldDefault)) {
3871 final String defaultValue = getContext().getResources().getString(
3872 R.string.def_charging_started_sound);
3873 if (!TextUtils.isEmpty(defaultValue)) {
3874 globalSettings.insertSettingLocked(
3875 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3876 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3877 }
3878
3879 }
3880 currentVersion = 156;
3881 }
3882
Beverly09da25f2018-02-26 09:17:07 -05003883 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003884 // Version 157: Set a default value for zen duration,
3885 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003886 final SettingsState globalSettings = getGlobalSettingsLocked();
3887 final Setting currentSetting = globalSettings.getSettingLocked(
3888 Global.ZEN_DURATION);
3889 if (currentSetting.isNull()) {
3890 String defaultZenDuration = Integer.toString(getContext()
3891 .getResources().getInteger(R.integer.def_zen_duration));
3892 globalSettings.insertSettingLocked(
3893 Global.ZEN_DURATION, defaultZenDuration,
3894 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3895 }
Beverly09da25f2018-02-26 09:17:07 -05003896 currentVersion = 157;
3897 }
Annie Mengd069a882018-03-13 15:31:40 +00003898
3899 if (currentVersion == 157) {
3900 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3901 final SettingsState globalSettings = getGlobalSettingsLocked();
3902 final String oldValue = globalSettings.getSettingLocked(
3903 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3904 if (TextUtils.equals(null, oldValue)) {
3905 final String defaultValue = getContext().getResources().getString(
3906 R.string.def_backup_agent_timeout_parameters);
3907 if (!TextUtils.isEmpty(defaultValue)) {
3908 globalSettings.insertSettingLocked(
3909 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3910 null, true,
3911 SettingsState.SYSTEM_PACKAGE_NAME);
3912 }
3913 }
3914 currentVersion = 158;
3915 }
Roshan Pius9c396672018-03-02 14:54:13 -08003916
3917 if (currentVersion == 158) {
3918 // Remove setting that specifies wifi bgscan throttling params
3919 getGlobalSettingsLocked().deleteSettingLocked(
3920 "wifi_scan_background_throttle_interval_ms");
3921 getGlobalSettingsLocked().deleteSettingLocked(
3922 "wifi_scan_background_throttle_package_whitelist");
3923 currentVersion = 159;
3924 }
3925
Pavel Grafovc5c97302018-03-19 13:37:15 +00003926 if (currentVersion == 159) {
3927 // Version 160: Hiding notifications from the lockscreen is only available as
3928 // primary user option, profiles can only make them redacted. If a profile was
3929 // configured to not show lockscreen notifications, ensure that at the very
3930 // least these will be come hidden.
3931 if (mUserManager.isManagedProfile(userId)) {
3932 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3933 Setting showNotifications = secureSettings.getSettingLocked(
3934 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3935 // The default value is "1", check if user has turned it off.
3936 if ("0".equals(showNotifications.getValue())) {
3937 secureSettings.insertSettingLocked(
3938 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3939 null /* tag */, false /* makeDefault */,
3940 SettingsState.SYSTEM_PACKAGE_NAME);
3941 }
3942 // The setting is no longer valid for managed profiles, it should be
3943 // treated as if it was set to "1".
3944 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3945 }
3946 currentVersion = 160;
3947 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003948
3949 if (currentVersion == 160) {
3950 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003951 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003952 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3953 final SettingsState globalSettings = getGlobalSettingsLocked();
3954
3955 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003956 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3957 if (TextUtils.equals(null, oldValue)) {
3958 globalSettings.insertSettingLocked(
3959 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3960 Integer.toString(getContext().getResources().getInteger(
3961 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3962 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3963 }
3964
3965 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003966 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3967 if (TextUtils.equals(null, oldValue)) {
3968 globalSettings.insertSettingLocked(
3969 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3970 Integer.toString(getContext().getResources().getInteger(
3971 R.integer.def_sound_trigger_detection_service_op_timeout)),
3972 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3973 }
3974 currentVersion = 161;
3975 }
3976
Mike Digman55272862018-02-20 14:35:17 -08003977 if (currentVersion == 161) {
3978 // Version 161: Add a gesture for silencing phones
3979 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3980 final Setting currentSetting = secureSettings.getSettingLocked(
3981 Secure.VOLUME_HUSH_GESTURE);
3982 if (currentSetting.isNull()) {
3983 secureSettings.insertSettingLocked(
3984 Secure.VOLUME_HUSH_GESTURE,
3985 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3986 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3987 }
3988
3989 currentVersion = 162;
3990 }
3991
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003992 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003993 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003994 currentVersion = 163;
3995 }
3996
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003997 if (currentVersion == 163) {
3998 // Version 163: Update default value of
3999 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
4000 final SettingsState settings = getGlobalSettingsLocked();
4001 final Setting currentSetting = settings.getSettingLocked(
4002 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
4003 if (currentSetting.isDefaultFromSystem()) {
4004 settings.insertSettingLocked(
4005 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
4006 Integer.toString(getContext().getResources().getInteger(
4007 R.integer
4008 .def_max_sound_trigger_detection_service_ops_per_day)),
4009 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4010 }
4011
4012 currentVersion = 164;
4013 }
4014
Julia Reynolds76bfa602018-04-23 09:38:47 -04004015 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004016 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004017 currentVersion = 165;
4018 }
4019
Beverly301e92a2018-04-27 09:43:05 -04004020 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004021 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4022 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004023 currentVersion = 166;
4024 }
4025
Beverly38fcfd02018-05-18 17:33:40 -04004026 if (currentVersion == 166) {
4027 // Version 166: add default values for hush gesture used and manual ringer
4028 // toggle
4029 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4030 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4031 Secure.HUSH_GESTURE_USED);
4032 if (currentHushUsedSetting.isNull()) {
4033 secureSettings.insertSettingLocked(
4034 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4035 SettingsState.SYSTEM_PACKAGE_NAME);
4036 }
4037
4038 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4039 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4040 if (currentRingerToggleCountSetting.isNull()) {
4041 secureSettings.insertSettingLocked(
4042 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4043 SettingsState.SYSTEM_PACKAGE_NAME);
4044 }
4045 currentVersion = 167;
4046 }
4047
Beverly155c9d22018-05-23 18:03:23 -04004048 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004049 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4050 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004051 currentVersion = 168;
4052 }
4053
Michael Wright0e9eeee2018-05-26 00:31:20 +01004054 if (currentVersion == 168) {
4055 // Version 168: by default, vibrate for phone calls
4056 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4057 final Setting currentSetting = systemSettings.getSettingLocked(
4058 Settings.System.VIBRATE_WHEN_RINGING);
4059 if (currentSetting.isNull()) {
4060 systemSettings.insertSettingLocked(
4061 Settings.System.VIBRATE_WHEN_RINGING,
4062 getContext().getResources().getBoolean(
4063 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4064 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4065 }
4066 currentVersion = 169;
4067 }
4068
Nadav Barf9f115d2018-06-24 10:06:50 +03004069 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004070 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4071 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4072 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004073
Beverly91d0a632018-07-02 16:45:00 -04004074 final SettingsState globalSettings = getGlobalSettingsLocked();
4075 final Setting globalZenDuration = globalSettings.getSettingLocked(
4076 Global.ZEN_DURATION);
4077
4078 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4079 final Setting secureZenDuration = secureSettings.getSettingLocked(
4080 Secure.ZEN_DURATION);
4081
4082 // ZEN_DURATION
4083 if (!globalZenDuration.isNull()) {
4084 secureSettings.insertSettingLocked(
4085 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4086 SettingsState.SYSTEM_PACKAGE_NAME);
4087
4088 // set global zen duration setting to null since it's deprecated
4089 globalSettings.insertSettingLocked(
4090 Global.ZEN_DURATION, null, null, true,
4091 SettingsState.SYSTEM_PACKAGE_NAME);
4092 } else if (secureZenDuration.isNull()) {
4093 String defaultZenDuration = Integer.toString(getContext()
4094 .getResources().getInteger(R.integer.def_zen_duration));
4095 secureSettings.insertSettingLocked(
4096 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4097 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004098 }
Beverly91d0a632018-07-02 16:45:00 -04004099
4100 // SHOW_ZEN_SETTINGS_SUGGESTION
4101 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4102 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4103 if (currentShowZenSettingSuggestion.isNull()) {
4104 secureSettings.insertSettingLocked(
4105 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4106 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4107 }
4108
4109 // ZEN_SETTINGS_UPDATED
4110 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4111 Secure.ZEN_SETTINGS_UPDATED);
4112 if (currentUpdatedSetting.isNull()) {
4113 secureSettings.insertSettingLocked(
4114 Secure.ZEN_SETTINGS_UPDATED, "0",
4115 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4116 }
4117
4118 // ZEN_SETTINGS_SUGGESTION_VIEWED
4119 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4120 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4121 if (currentSettingSuggestionViewed.isNull()) {
4122 secureSettings.insertSettingLocked(
4123 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4124 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4125 }
4126
Nadav Barf9f115d2018-06-24 10:06:50 +03004127 currentVersion = 170;
4128 }
4129
Beverly91d0a632018-07-02 16:45:00 -04004130 if (currentVersion == 170) {
4131 // Version 170: Set the default value for Secure Settings:
4132 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4133
4134 final SettingsState globalSettings = getGlobalSettingsLocked();
4135 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4136
4137 // CHARGING_SOUNDS_ENABLED
4138 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4139 Global.CHARGING_SOUNDS_ENABLED);
4140 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4141 Secure.CHARGING_SOUNDS_ENABLED);
4142
4143 if (!globalChargingSoundEnabled.isNull()) {
4144 secureSettings.insertSettingLocked(
4145 Secure.CHARGING_SOUNDS_ENABLED,
4146 globalChargingSoundEnabled.getValue(), null, false,
4147 SettingsState.SYSTEM_PACKAGE_NAME);
4148
4149 // set global charging_sounds_enabled setting to null since it's deprecated
4150 globalSettings.insertSettingLocked(
4151 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4152 SettingsState.SYSTEM_PACKAGE_NAME);
4153 } else if (secureChargingSoundsEnabled.isNull()) {
4154 String defChargingSoundsEnabled = getContext().getResources()
4155 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4156 secureSettings.insertSettingLocked(
4157 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4158 true, SettingsState.SYSTEM_PACKAGE_NAME);
4159 }
4160
4161 // CHARGING_VIBRATION_ENABLED
4162 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4163 Secure.CHARGING_VIBRATION_ENABLED);
4164
4165 if (secureChargingVibrationEnabled.isNull()) {
4166 String defChargingVibrationEnabled = getContext().getResources()
4167 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4168 secureSettings.insertSettingLocked(
4169 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4170 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4171 }
4172
4173 currentVersion = 171;
4174 }
4175
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004176 if (currentVersion == 171) {
4177 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4178 // be muted.
4179 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4180 final Setting currentSetting = systemSettings.getSettingLocked(
4181 Settings.System.MUTE_STREAMS_AFFECTED);
4182 if (!currentSetting.isNull()) {
4183 try {
4184 int currentSettingIntegerValue = Integer.parseInt(
4185 currentSetting.getValue());
4186 if ((currentSettingIntegerValue
4187 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4188 systemSettings.insertSettingLocked(
4189 Settings.System.MUTE_STREAMS_AFFECTED,
4190 Integer.toString(
4191 currentSettingIntegerValue
4192 | (1 << AudioManager.STREAM_VOICE_CALL)),
4193 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4194 }
4195 } catch (NumberFormatException e) {
4196 // remove the setting in case it is not a valid integer
4197 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4198 + "setting, removing setting", e);
4199 systemSettings.deleteSettingLocked(
4200 Settings.System.MUTE_STREAMS_AFFECTED);
4201 }
4202
4203 }
4204 currentVersion = 172;
4205 }
4206
Felipe Lemeff355092017-04-03 12:55:02 -07004207 // vXXX: Add new settings above this point.
4208
Dan Sandler71f85e92016-07-20 13:46:05 -04004209 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004210 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004211 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004212 + currentVersion +
4213 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4214 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004215 if (DEBUG) {
4216 throw new RuntimeException("db upgrade error");
4217 }
4218 }
4219
Jeff Brown503cffc2015-03-26 18:08:51 -07004220 // Return the current version.
4221 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004222 }
4223 }
Svet Ganov13701552017-02-23 12:45:17 -08004224
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004225 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4226 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004227 List<String> names = settings.getSettingNamesLocked();
4228 final int nameCount = names.size();
4229 for (int i = 0; i < nameCount; i++) {
4230 String name = names.get(i);
4231 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004232
4233 // In the upgrade case we pretend the call is made from the app
4234 // that made the last change to the setting to properly determine
4235 // whether the call has been made by a system component.
4236 int callingUid = -1;
4237 try {
4238 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4239 } catch (RemoteException e) {
4240 /* ignore - handled below */
4241 }
4242 if (callingUid < 0) {
4243 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4244 continue;
4245 }
4246 try {
4247 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4248 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004249 if (systemSet) {
4250 settings.insertSettingLocked(name, setting.getValue(),
4251 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004252 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4253 // We had a bug where changes by non-system packages were marked
4254 // as system made and as a result set as the default. Therefore, if
4255 // the package changed the setting last is not a system one but the
4256 // setting is marked as its default coming from the system we clear
4257 // the default and clear the system set flag.
4258 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004259 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004260 } catch (IllegalStateException e) {
4261 // If the package goes over its quota during the upgrade, don't
4262 // crash but just log the error as the system does the upgrade.
4263 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4264
Svet Ganov13701552017-02-23 12:45:17 -08004265 }
4266 }
4267 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004268 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004269}