blob: 5153f9ea86d167a8b324fc9a00a39474672ecedd [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.
Stanislav Zholnin596437f2018-12-28 15:34:23 +00001055 // enforceReadPermission(READ_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001056
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) {
Stanislav Zholnin596437f2018-12-28 15:34:23 +00001091
1092 // TODO(b/117663715): Ensure the caller can access the setting.
1093 // enforceReadPermission(WRITE_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001094
Matt Pape1b31a332018-10-17 09:58:28 -07001095 // Perform the mutation.
1096 synchronized (mLock) {
1097 switch (operation) {
1098 case MUTATION_OPERATION_INSERT: {
1099 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001100 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001101 resolveCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001102 }
1103
Matt Pape6bfc62e2018-11-28 13:16:03 -08001104 case MUTATION_OPERATION_DELETE: {
1105 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001106 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001107 }
1108
Matt Pape1b31a332018-10-17 09:58:28 -07001109 case MUTATION_OPERATION_RESET: {
1110 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001111 UserHandle.USER_SYSTEM, resolveCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001112 } return true;
1113 }
1114 }
1115
1116 return false;
1117 }
1118
Matt Pape6bfc62e2018-11-28 13:16:03 -08001119 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1120 if (DEBUG) {
1121 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1122 }
1123
1124 synchronized (mLock) {
1125 // Get the settings.
1126 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1127 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1128
1129 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1130 UserHandle.USER_SYSTEM);
1131
1132 final int nameCount = names.size();
1133 Map<String, String> flagsToValues = new HashMap<>(names.size());
1134
1135 for (int i = 0; i < nameCount; i++) {
1136 String name = names.get(i);
1137 Setting setting = settingsState.getSettingLocked(name);
1138 if (prefix == null || setting.getName().startsWith(prefix)) {
1139 flagsToValues.put(setting.getName(), setting.getValue());
1140 }
1141 }
1142
1143 return flagsToValues;
1144 }
1145 }
1146
Svetoslav7ec28e82015-05-20 17:01:10 -07001147 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001148 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001149 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001150 }
1151
Svetoslav7ec28e82015-05-20 17:01:10 -07001152 synchronized (mLock) {
1153 // Get the settings.
1154 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001155 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001156
Chad Brubaker97bccee2017-01-05 15:51:41 -08001157 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1158 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001159
Svetoslav7ec28e82015-05-20 17:01:10 -07001160 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001161
Svetoslav7ec28e82015-05-20 17:01:10 -07001162 String[] normalizedProjection = normalizeProjection(projection);
1163 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001164
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 // Anyone can get the global settings, so no security checks.
1166 for (int i = 0; i < nameCount; i++) {
1167 String name = names.get(i);
1168 Setting setting = settingsState.getSettingLocked(name);
1169 appendSettingToCursor(result, setting);
1170 }
1171
1172 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001173 }
Svetoslav683914b2015-01-15 14:22:26 -08001174 }
1175
Svetoslav7ec28e82015-05-20 17:01:10 -07001176 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001177 if (DEBUG) {
1178 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1179 }
1180
Chad Brubakera6830e72017-04-28 17:34:36 -07001181 // Ensure the caller can access the setting.
1182 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1183
Svetoslav683914b2015-01-15 14:22:26 -08001184 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001185 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001186 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001187 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001188 }
Svetoslav683914b2015-01-15 14:22:26 -08001189 }
1190
Svetoslav Ganove080da92016-12-21 17:10:35 -08001191 private boolean updateGlobalSetting(String name, String value, String tag,
1192 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001193 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001194 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1195 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1196 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001197 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001198 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1199 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001200 }
1201
Svetoslav Ganove080da92016-12-21 17:10:35 -08001202 private boolean insertGlobalSetting(String name, String value, String tag,
1203 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001204 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001205 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1206 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1207 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001208 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001209 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1210 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001211 }
1212
Svet Ganov53a441c2016-04-19 19:38:00 -07001213 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001214 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001215 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1216 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001217 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001218 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1219 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001220 }
1221
Svetoslav Ganove080da92016-12-21 17:10:35 -08001222 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1223 if (DEBUG) {
1224 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1225 + mode + ", " + tag + ")");
1226 }
1227 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1228 MUTATION_OPERATION_RESET, false, mode);
1229 }
1230
1231 private boolean mutateGlobalSetting(String name, String value, String tag,
1232 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1233 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001234 // Make sure the caller can change the settings - treated as secure.
1235 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1236
Svetoslav683914b2015-01-15 14:22:26 -08001237 // Resolve the userId on whose behalf the call is made.
1238 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1239
Makoto Onuki28da2e32015-11-20 11:30:44 -08001240 // If this is a setting that is currently restricted for this user, do not allow
1241 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001242 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1243 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001244 return false;
1245 }
1246
1247 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001248 synchronized (mLock) {
1249 switch (operation) {
1250 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001251 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1252 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001253 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001254 }
Svetoslav683914b2015-01-15 14:22:26 -08001255
Svetoslav7ec28e82015-05-20 17:01:10 -07001256 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001257 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001258 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001259 }
Svetoslav683914b2015-01-15 14:22:26 -08001260
Svetoslav7ec28e82015-05-20 17:01:10 -07001261 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001262 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1263 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001264 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001265 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001266
1267 case MUTATION_OPERATION_RESET: {
1268 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1269 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1270 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001271 }
1272 }
1273
1274 return false;
1275 }
1276
Christopher Tateb218e762017-04-05 16:34:07 -07001277 private PackageInfo getCallingPackageInfo(int userId) {
1278 try {
1279 return mPackageManager.getPackageInfo(getCallingPackage(),
1280 PackageManager.GET_SIGNATURES, userId);
1281 } catch (RemoteException e) {
1282 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1283 }
1284 }
1285
Svetoslav7ec28e82015-05-20 17:01:10 -07001286 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001287 if (DEBUG) {
1288 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1289 }
1290
1291 // Resolve the userId on whose behalf the call is made.
1292 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1293
Christopher Tateb218e762017-04-05 16:34:07 -07001294 // The relevant "calling package" userId will be the owning userId for some
1295 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1296 // up front who the effective "new SSAID" user ID for that settings name will be.
1297 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1298 Settings.Secure.ANDROID_ID);
1299 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1300
Svetoslav7ec28e82015-05-20 17:01:10 -07001301 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001302 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001303
Svetoslav7ec28e82015-05-20 17:01:10 -07001304 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001305
Svetoslav7ec28e82015-05-20 17:01:10 -07001306 String[] normalizedProjection = normalizeProjection(projection);
1307 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001308
Svetoslav7ec28e82015-05-20 17:01:10 -07001309 for (int i = 0; i < nameCount; i++) {
1310 String name = names.get(i);
1311 // Determine the owning user as some profile settings are cloned from the parent.
1312 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1313 name);
Svetoslav683914b2015-01-15 14:22:26 -08001314
Alex Klyubin1991f572017-03-03 14:08:36 -08001315 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1316 // This caller is not permitted to access this setting. Pretend the setting
1317 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001318 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 }
Svetoslav683914b2015-01-15 14:22:26 -08001320
Mark Rathjen7599f132017-01-23 14:15:54 -08001321 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001322 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1323 final Setting setting;
1324 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001325 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001326 } else {
1327 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1328 name);
1329 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001330 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001331 }
1332
Svetoslav7ec28e82015-05-20 17:01:10 -07001333 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001334 }
Svetoslav683914b2015-01-15 14:22:26 -08001335 }
1336
Svetoslav7ec28e82015-05-20 17:01:10 -07001337 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001338 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1339 }
1340
1341 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001342 if (DEBUG) {
1343 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1344 }
1345
1346 // Resolve the userId on whose behalf the call is made.
1347 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1348
Chad Brubakera6830e72017-04-28 17:34:36 -07001349 // Ensure the caller can access the setting.
1350 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1351
Svetoslav683914b2015-01-15 14:22:26 -08001352 // Determine the owning user as some profile settings are cloned from the parent.
1353 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1354
Alex Klyubin1991f572017-03-03 14:08:36 -08001355 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1356 // This caller is not permitted to access this setting. Pretend the setting doesn't
1357 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001358 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1359 owningUserId);
1360 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001361 }
1362
Christopher Tateb218e762017-04-05 16:34:07 -07001363 // As of Android O, the SSAID is read from an app-specific entry in table
1364 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1365 if (isNewSsaidSetting(name)) {
1366 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1367 synchronized (mLock) {
1368 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001369 }
Christopher Tateb218e762017-04-05 16:34:07 -07001370 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001371 if (enableOverride) {
1372 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1373 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1374 if (overridden != null) {
1375 return overridden;
1376 }
1377 }
1378 }
Mark Rathjend891f012017-01-19 04:10:37 +00001379
Christopher Tateb218e762017-04-05 16:34:07 -07001380 // Not the SSAID; do a straight lookup
1381 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001382 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001383 owningUserId, name);
1384 }
Svetoslav683914b2015-01-15 14:22:26 -08001385 }
1386
Mark Rathjend891f012017-01-19 04:10:37 +00001387 private boolean isNewSsaidSetting(String name) {
1388 return Settings.Secure.ANDROID_ID.equals(name)
1389 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1390 }
1391
Andreas Gampeb58893072018-09-05 16:52:31 -07001392 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001393 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001394 // Get uid of caller (key) used to store ssaid value
1395 String name = Integer.toString(
1396 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1397
1398 if (DEBUG) {
1399 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1400 }
1401
1402 // Retrieve the ssaid from the table if present.
1403 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1404 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001405 // If the app is an Instant App use its stored SSAID instead of our own.
1406 final String instantSsaid;
1407 final long token = Binder.clearCallingIdentity();
1408 try {
1409 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1410 owningUserId);
1411 } catch (RemoteException e) {
1412 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1413 return null;
1414 } finally {
1415 Binder.restoreCallingIdentity(token);
1416 }
Svet Ganov96c99462017-05-05 14:27:13 -07001417
1418 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1419 SETTINGS_TYPE_SSAID, owningUserId);
1420
Chad Brubaker0d277a72017-04-12 16:56:53 -07001421 if (instantSsaid != null) {
1422 // Use the stored value if it is still valid.
1423 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001424 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001425 }
1426 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001427 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1428 true, callingPkg.packageName);
1429 if (!success) {
1430 throw new IllegalStateException("Failed to update instant app android id");
1431 }
Svet Ganov96c99462017-05-05 14:27:13 -07001432 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1433 owningUserId, name);
1434 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001435 }
Mark Rathjend891f012017-01-19 04:10:37 +00001436
1437 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001438 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001439 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1440 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001441 }
1442
Svet Ganov96c99462017-05-05 14:27:13 -07001443 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1444 }
1445
1446 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1447 // SSAID settings are located in a dedicated table for internal bookkeeping
1448 // but for the world they reside in the secure table, so adjust the key here.
1449 // We have a special name when looking it up but want the world to see it as
1450 // "android_id".
1451 if (ssaidSetting != null) {
1452 return settingsState.new Setting(ssaidSetting) {
1453 @Override
1454 public int getKey() {
1455 final int userId = getUserIdFromKey(super.getKey());
1456 return makeKey(SETTINGS_TYPE_SECURE, userId);
1457 }
1458
1459 @Override
1460 public String getName() {
1461 return Settings.Secure.ANDROID_ID;
1462 }
1463 };
1464 }
1465 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001466 }
1467
Makoto Onuki0000d322017-11-28 16:31:47 -08001468 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1469 synchronized (mLock) {
1470 final Setting setting = getGlobalSetting(
1471 Global.LOCATION_GLOBAL_KILL_SWITCH);
1472 if (!"1".equals(setting.getValue())) {
1473 return null;
1474 }
1475 // Global kill-switch is enabled. Return an empty value.
1476 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1477 SETTINGS_TYPE_SECURE, owningUserId);
1478 return settingsState.new Setting(
1479 Secure.LOCATION_PROVIDERS_ALLOWED,
1480 "", // value
1481 "", // tag
1482 "", // default value
1483 "", // package name
1484 false, // from system
1485 "0" // id
1486 ) {
1487 @Override
1488 public boolean update(String value, boolean setDefault, String packageName,
1489 String tag, boolean forceNonSystemPackage) {
1490 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1491 return false;
1492 }
1493 };
1494 }
1495 }
1496
Svetoslav Ganove080da92016-12-21 17:10:35 -08001497 private boolean insertSecureSetting(String name, String value, String tag,
1498 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001499 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001500 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001501 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1502 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001503 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001504 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1505 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001506 }
1507
Svet Ganov53a441c2016-04-19 19:38:00 -07001508 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001509 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001510 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1511 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001512 }
1513
Svetoslav Ganove080da92016-12-21 17:10:35 -08001514 return mutateSecureSetting(name, null, null, false, requestingUserId,
1515 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001516 }
1517
Svetoslav Ganove080da92016-12-21 17:10:35 -08001518 private boolean updateSecureSetting(String name, String value, String tag,
1519 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001520 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001521 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001522 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1523 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001524 }
1525
Svetoslav Ganove080da92016-12-21 17:10:35 -08001526 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1527 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001528 }
1529
Svetoslav Ganove080da92016-12-21 17:10:35 -08001530 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1531 if (DEBUG) {
1532 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1533 + mode + ", " + tag + ")");
1534 }
1535
1536 mutateSecureSetting(null, null, tag, false, requestingUserId,
1537 MUTATION_OPERATION_RESET, false, mode);
1538 }
1539
1540 private boolean mutateSecureSetting(String name, String value, String tag,
1541 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1542 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001543 // Make sure the caller can change the settings.
1544 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1545
Svetoslav683914b2015-01-15 14:22:26 -08001546 // Resolve the userId on whose behalf the call is made.
1547 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1548
Makoto Onuki28da2e32015-11-20 11:30:44 -08001549 // If this is a setting that is currently restricted for this user, do not allow
1550 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001551 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1552 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001553 return false;
1554 }
1555
1556 // Determine the owning user as some profile settings are cloned from the parent.
1557 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1558
1559 // Only the owning user can change the setting.
1560 if (owningUserId != callingUserId) {
1561 return false;
1562 }
1563
1564 // Special cases for location providers (sigh).
1565 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001566 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1567 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001568 }
1569
1570 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001571 synchronized (mLock) {
1572 switch (operation) {
1573 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001574 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001575 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001576 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001577 }
Svetoslav683914b2015-01-15 14:22:26 -08001578
Svetoslav7ec28e82015-05-20 17:01:10 -07001579 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001580 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001581 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001582 }
Svetoslav683914b2015-01-15 14:22:26 -08001583
Svetoslav7ec28e82015-05-20 17:01:10 -07001584 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001585 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001586 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001587 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001588 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001589
1590 case MUTATION_OPERATION_RESET: {
1591 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1592 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1593 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001594 }
1595 }
1596
1597 return false;
1598 }
1599
Svetoslav7ec28e82015-05-20 17:01:10 -07001600 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001601 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001602 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001603 }
1604
1605 // Resolve the userId on whose behalf the call is made.
1606 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1607
Svetoslav7ec28e82015-05-20 17:01:10 -07001608 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001609 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001610
Svetoslav7ec28e82015-05-20 17:01:10 -07001611 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001612
Svetoslav7ec28e82015-05-20 17:01:10 -07001613 String[] normalizedProjection = normalizeProjection(projection);
1614 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001615
Svetoslav7ec28e82015-05-20 17:01:10 -07001616 for (int i = 0; i < nameCount; i++) {
1617 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001618
Svetoslav7ec28e82015-05-20 17:01:10 -07001619 // Determine the owning user as some profile settings are cloned from the parent.
1620 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1621 name);
Svetoslav683914b2015-01-15 14:22:26 -08001622
Svetoslav7ec28e82015-05-20 17:01:10 -07001623 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001624 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001625 appendSettingToCursor(result, setting);
1626 }
1627
1628 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001629 }
Svetoslav683914b2015-01-15 14:22:26 -08001630 }
1631
Svetoslav7ec28e82015-05-20 17:01:10 -07001632 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001633 if (DEBUG) {
1634 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1635 }
1636
1637 // Resolve the userId on whose behalf the call is made.
1638 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1639
Chad Brubakera6830e72017-04-28 17:34:36 -07001640 // Ensure the caller can access the setting.
1641 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001642
Svetoslav683914b2015-01-15 14:22:26 -08001643 // Determine the owning user as some profile settings are cloned from the parent.
1644 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1645
1646 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001647 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001648 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001649 }
Svetoslav683914b2015-01-15 14:22:26 -08001650 }
1651
Svetoslav7ec28e82015-05-20 17:01:10 -07001652 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001653 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001654 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001655 + requestingUserId + ")");
1656 }
1657
Svetoslav7ec28e82015-05-20 17:01:10 -07001658 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001659 }
1660
Svetoslav7ec28e82015-05-20 17:01:10 -07001661 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001662 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001663 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001664 }
1665
Svetoslav7ec28e82015-05-20 17:01:10 -07001666 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001667 }
1668
Svetoslav7ec28e82015-05-20 17:01:10 -07001669 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001670 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001671 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001672 + requestingUserId + ")");
1673 }
1674
Svetoslav7ec28e82015-05-20 17:01:10 -07001675 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001676 }
1677
Svetoslav7ec28e82015-05-20 17:01:10 -07001678 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001679 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001680 if (!hasWriteSecureSettingsPermission()) {
1681 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1682 // operation is allowed for the calling package through appops.
1683 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1684 Binder.getCallingUid(), getCallingPackage(), true)) {
1685 return false;
1686 }
Svetoslav683914b2015-01-15 14:22:26 -08001687 }
1688
Svetoslav683914b2015-01-15 14:22:26 -08001689 // Resolve the userId on whose behalf the call is made.
1690 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1691
yuemingw1d13eae2018-01-30 17:27:54 +00001692 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1693 name, callingUserId, value, Binder.getCallingUid())) {
1694 return false;
1695 }
1696
Svetoslavd8d25e02015-11-20 13:09:26 -08001697 // Enforce what the calling package can mutate the system settings.
1698 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1699
Svetoslav683914b2015-01-15 14:22:26 -08001700 // Determine the owning user as some profile settings are cloned from the parent.
1701 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1702
1703 // Only the owning user id can change the setting.
1704 if (owningUserId != callingUserId) {
1705 return false;
1706 }
1707
Jeff Sharkey413573a2016-02-22 17:52:45 -07001708 // Invalidate any relevant cache files
1709 String cacheName = null;
1710 if (Settings.System.RINGTONE.equals(name)) {
1711 cacheName = Settings.System.RINGTONE_CACHE;
1712 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1713 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1714 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1715 cacheName = Settings.System.ALARM_ALERT_CACHE;
1716 }
1717 if (cacheName != null) {
1718 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001719 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001720 cacheFile.delete();
1721 }
1722
Svetoslav683914b2015-01-15 14:22:26 -08001723 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001724 synchronized (mLock) {
1725 switch (operation) {
1726 case MUTATION_OPERATION_INSERT: {
1727 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001728 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001729 owningUserId, name, value, null, false, getCallingPackage(),
1730 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001731 }
1732
1733 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001734 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001735 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001736 }
1737
1738 case MUTATION_OPERATION_UPDATE: {
1739 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001740 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001741 owningUserId, name, value, null, false, getCallingPackage(),
1742 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001743 }
Svetoslav683914b2015-01-15 14:22:26 -08001744 }
1745
Svetoslav7ec28e82015-05-20 17:01:10 -07001746 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001747 }
Svetoslav683914b2015-01-15 14:22:26 -08001748 }
1749
Billy Lau6ad2d662015-07-18 00:26:58 +01001750 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001751 // Write secure settings is a more protected permission. If caller has it we are good.
1752 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1753 == PackageManager.PERMISSION_GRANTED) {
1754 return true;
1755 }
1756
Svetoslavf41334b2015-06-23 12:06:03 -07001757 return false;
1758 }
1759
Svetoslav683914b2015-01-15 14:22:26 -08001760 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001761 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001762 if (validator != null && !validator.validate(value)) {
1763 throw new IllegalArgumentException("Invalid value: " + value
1764 + " for setting: " + name);
1765 }
1766 }
1767
Alex Klyubin1991f572017-03-03 14:08:36 -08001768 /**
1769 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1770 */
1771 private boolean isSecureSettingAccessible(String name, int callingUserId,
1772 int owningUserId) {
1773 // Special case for location (sigh).
1774 // This check is not inside the name-based checks below because this method performs checks
1775 // only if the calling user ID is not the same as the owning user ID.
1776 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1777 return false;
1778 }
1779
1780 switch (name) {
1781 case "bluetooth_address":
1782 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1783 // address in this secure setting. Secure settings can normally be read by any app,
1784 // which thus enables them to bypass the recently introduced restrictions on access
1785 // to device identifiers.
1786 // To mitigate this we make this setting available only to callers privileged to see
1787 // this device's MAC addresses, same as through public API
1788 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1789 return getContext().checkCallingOrSelfPermission(
1790 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1791 default:
1792 return true;
1793 }
1794 }
1795
Svetoslav683914b2015-01-15 14:22:26 -08001796 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1797 int owningUserId) {
1798 // Optimization - location providers are restricted only for managed profiles.
1799 if (callingUserId == owningUserId) {
1800 return false;
1801 }
1802 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1803 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1804 new UserHandle(callingUserId))) {
1805 return true;
1806 }
1807 return false;
1808 }
1809
Svetoslav683914b2015-01-15 14:22:26 -08001810 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1811 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1812 }
1813
1814 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001815 final int parentId;
1816 // Resolves dependency if setting has a dependency and the calling user has a parent
1817 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1818 && (parentId = getGroupParentLocked(userId)) != userId) {
1819 // The setting has a dependency and the profile has a parent
1820 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001821 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1822 final long token = Binder.clearCallingIdentity();
1823 try {
1824 Setting settingObj = getSecureSetting(dependency, userId);
1825 if (settingObj != null && settingObj.getValue().equals("1")) {
1826 return parentId;
1827 }
1828 } finally {
1829 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001830 }
1831 }
Svetoslav683914b2015-01-15 14:22:26 -08001832 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1833 }
1834
1835 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1836 final int parentId = getGroupParentLocked(userId);
1837 if (parentId != userId && keys.contains(name)) {
1838 return parentId;
1839 }
1840 return userId;
1841 }
1842
Svetoslavf41334b2015-06-23 12:06:03 -07001843 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001844 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001845 // System/root/shell can mutate whatever secure settings they want.
1846 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001847 final int appId = UserHandle.getAppId(callingUid);
1848 if (appId == android.os.Process.SYSTEM_UID
1849 || appId == Process.SHELL_UID
1850 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001851 return;
1852 }
1853
1854 switch (operation) {
1855 case MUTATION_OPERATION_INSERT:
1856 // Insert updates.
1857 case MUTATION_OPERATION_UPDATE: {
1858 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1859 return;
1860 }
1861
1862 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001863 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001864
1865 // Privileged apps can do whatever they want.
1866 if ((packageInfo.applicationInfo.privateFlags
1867 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1868 return;
1869 }
1870
1871 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1872 packageInfo.applicationInfo.targetSdkVersion, name);
1873 } break;
1874
1875 case MUTATION_OPERATION_DELETE: {
1876 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1877 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1878 throw new IllegalArgumentException("You cannot delete system defined"
1879 + " secure settings.");
1880 }
1881
1882 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001883 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001884
1885 // Privileged apps can do whatever they want.
1886 if ((packageInfo.applicationInfo.privateFlags &
1887 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1888 return;
1889 }
1890
1891 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1892 packageInfo.applicationInfo.targetSdkVersion, name);
1893 } break;
1894 }
1895 }
1896
Todd Kennedybe0b8892017-02-15 14:13:52 -08001897 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001898 switch (settingsType) {
1899 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001900 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001901 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001902 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001903 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001904 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001905 default:
1906 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1907 }
1908 }
1909
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001910 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1911 switch (settingsType) {
1912 case SETTINGS_TYPE_GLOBAL:
1913 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1914 case SETTINGS_TYPE_SYSTEM:
1915 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1916 case SETTINGS_TYPE_SECURE:
1917 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1918 default:
1919 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1920 }
1921 }
1922
Andreas Gampeb58893072018-09-05 16:52:31 -07001923 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001924 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001925 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1926 // in the current form.
1927 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001928 }
1929
Chad Brubakera6830e72017-04-28 17:34:36 -07001930 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001931 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1932 return;
1933 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001934 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001935 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001936 return;
1937 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001938 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1939 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001940 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1941 // breakage in the current form.
1942 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1943 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001944 }
1945 }
1946
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001947 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1948 // We always use the callingUid for this lookup. This means that if hypothetically an
1949 // app was installed in user A with cross user and in user B as an Instant App
1950 // the app in A would be able to see all the settings in user B. However since cross
1951 // user is a system permission and the app must be uninstalled in B and then installed as
1952 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001953 ApplicationInfo ai = null;
1954 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001955 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1956 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001957 } catch (RemoteException ignored) {
1958 }
1959 if (ai == null) {
1960 throw new IllegalStateException("Failed to lookup info for package "
1961 + getCallingPackage());
1962 }
1963 return ai;
1964 }
1965
Xiaohui Chen43765b72015-08-31 10:57:33 -07001966 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001967 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001968 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1969 getCallingPackage(), 0, userId);
1970 if (packageInfo != null) {
1971 return packageInfo;
1972 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001973 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001974 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001975 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001976 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001977 }
1978
1979 private int getGroupParentLocked(int userId) {
1980 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001981 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001982 return userId;
1983 }
1984 // We are in the same process with the user manager and the returned
1985 // user info is a cached instance, so just look up instead of cache.
1986 final long identity = Binder.clearCallingIdentity();
1987 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001988 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001989 UserInfo userInfo = mUserManager.getProfileParent(userId);
1990 return (userInfo != null) ? userInfo.id : userId;
1991 } finally {
1992 Binder.restoreCallingIdentity(identity);
1993 }
1994 }
1995
Svetoslav683914b2015-01-15 14:22:26 -08001996 private void enforceWritePermission(String permission) {
1997 if (getContext().checkCallingOrSelfPermission(permission)
1998 != PackageManager.PERMISSION_GRANTED) {
1999 throw new SecurityException("Permission denial: writing to settings requires:"
2000 + permission);
2001 }
2002 }
2003
2004 /*
2005 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2006 * This setting contains a list of the currently enabled location providers.
2007 * But helper functions in android.providers.Settings can enable or disable
2008 * a single provider by using a "+" or "-" prefix before the provider name.
2009 *
yuemingw1d13eae2018-01-30 17:27:54 +00002010 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2011 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2012 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002013 *
Svetoslav683914b2015-01-15 14:22:26 -08002014 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002015 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002016 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002017 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2018 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002019 if (TextUtils.isEmpty(value)) {
2020 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002021 }
Maggie83e03f52018-03-16 12:22:20 -07002022 Setting oldSetting = getSecureSetting(
2023 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2024 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002025 return false;
2026 }
Maggie83e03f52018-03-16 12:22:20 -07002027 String oldProviders = oldSetting.getValue();
2028 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2029 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2030 Set<String> newProvidersSet = new ArraySet<>();
2031 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002032
Maggie83e03f52018-03-16 12:22:20 -07002033 String[] providerUpdates = value.split(",");
2034 boolean inputError = false;
2035 for (String provider : providerUpdates) {
2036 // do not update location_providers_allowed when input is invalid
2037 if (TextUtils.isEmpty(provider)) {
2038 inputError = true;
2039 break;
Svetoslav683914b2015-01-15 14:22:26 -08002040 }
Maggie83e03f52018-03-16 12:22:20 -07002041 final char prefix = provider.charAt(0);
2042 // do not update location_providers_allowed when input is invalid
2043 if (prefix != '+' && prefix != '-') {
2044 inputError = true;
2045 break;
Svetoslav683914b2015-01-15 14:22:26 -08002046 }
Maggie83e03f52018-03-16 12:22:20 -07002047 // skip prefix
2048 provider = provider.substring(1);
2049 if (prefix == '+') {
2050 newProvidersSet.add(provider);
2051 } else if (prefix == '-') {
2052 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002053 }
Maggie83e03f52018-03-16 12:22:20 -07002054 }
2055 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2056 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002057 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002058 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002059 mSettingsRegistry.notifyForSettingsChange(
2060 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002061 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2062 }
Svetoslav683914b2015-01-15 14:22:26 -08002063 return false;
2064 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002065 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002066 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2067 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002068 }
2069
Svetoslav683914b2015-01-15 14:22:26 -08002070 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2071 int targetSdkVersion, String name) {
2072 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2073 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2074 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2075 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2076 + " This will soon become an error.");
2077 } else {
2078 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2079 + " This will soon become an error.");
2080 }
2081 } else {
2082 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2083 throw new IllegalArgumentException("You cannot change private secure settings.");
2084 } else {
2085 throw new IllegalArgumentException("You cannot keep your settings in"
2086 + " the secure settings.");
2087 }
2088 }
2089 }
2090
2091 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2092 if (requestingUserId == UserHandle.getCallingUserId()) {
2093 return requestingUserId;
2094 }
2095 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2096 Binder.getCallingUid(), requestingUserId, false, true,
2097 "get/set setting for user", null);
2098 }
2099
Svet Ganov53a441c2016-04-19 19:38:00 -07002100 private Bundle packageValueForCallResult(Setting setting,
2101 boolean trackingGeneration) {
2102 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002103 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002104 return NULL_SETTING_BUNDLE;
2105 }
2106 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002107 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002108 Bundle result = new Bundle();
2109 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002110 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002111
Svetoslav Ganove080da92016-12-21 17:10:35 -08002112 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002113 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002114 }
2115
2116 private static int getRequestingUserId(Bundle args) {
2117 final int callingUserId = UserHandle.getCallingUserId();
2118 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2119 : callingUserId;
2120 }
2121
Svet Ganov53a441c2016-04-19 19:38:00 -07002122 private boolean isTrackingGeneration(Bundle args) {
2123 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2124 }
2125
Svetoslav683914b2015-01-15 14:22:26 -08002126 private static String getSettingValue(Bundle args) {
2127 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2128 }
2129
Svetoslav Ganove080da92016-12-21 17:10:35 -08002130 private static String getSettingTag(Bundle args) {
2131 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2132 }
2133
Matt Pape6bfc62e2018-11-28 13:16:03 -08002134 private static String getSettingPrefix(Bundle args) {
2135 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2136 // Append '/' to ensure we only match properties with this exact prefix.
2137 // i.e. "foo" should match "foo/property" but not "foobar/property"
2138 return prefix != null ? prefix + "/" : null;
2139 }
2140
Svetoslav Ganove080da92016-12-21 17:10:35 -08002141 private static boolean getSettingMakeDefault(Bundle args) {
2142 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2143 }
2144
2145 private static int getResetModeEnforcingPermission(Bundle args) {
2146 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2147 switch (mode) {
2148 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2149 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2150 throw new SecurityException("Only system, shell/root on a "
2151 + "debuggable build can reset to untrusted defaults");
2152 }
2153 return mode;
2154 }
2155 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2156 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2157 throw new SecurityException("Only system, shell/root on a "
2158 + "debuggable build can reset untrusted changes");
2159 }
2160 return mode;
2161 }
2162 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2163 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2164 throw new SecurityException("Only system, shell/root on a "
2165 + "debuggable build can reset to trusted defaults");
2166 }
2167 return mode;
2168 }
2169 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2170 return mode;
2171 }
2172 }
2173 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2174 }
2175
2176 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2177 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2178 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2179 && (appId == SHELL_UID || appId == ROOT_UID));
2180 }
2181
Svetoslav683914b2015-01-15 14:22:26 -08002182 private static String getValidTableOrThrow(Uri uri) {
2183 if (uri.getPathSegments().size() > 0) {
2184 String table = uri.getPathSegments().get(0);
2185 if (DatabaseHelper.isValidTable(table)) {
2186 return table;
2187 }
2188 throw new IllegalArgumentException("Bad root path: " + table);
2189 }
2190 throw new IllegalArgumentException("Invalid URI:" + uri);
2191 }
2192
2193 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002194 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002195 return new MatrixCursor(projection, 0);
2196 }
2197 MatrixCursor cursor = new MatrixCursor(projection, 1);
2198 appendSettingToCursor(cursor, setting);
2199 return cursor;
2200 }
2201
2202 private static String[] normalizeProjection(String[] projection) {
2203 if (projection == null) {
2204 return ALL_COLUMNS;
2205 }
2206
2207 final int columnCount = projection.length;
2208 for (int i = 0; i < columnCount; i++) {
2209 String column = projection[i];
2210 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2211 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002212 }
2213 }
2214
Svetoslav683914b2015-01-15 14:22:26 -08002215 return projection;
2216 }
2217
2218 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002219 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002220 return;
2221 }
Svetoslav683914b2015-01-15 14:22:26 -08002222 final int columnCount = cursor.getColumnCount();
2223
2224 String[] values = new String[columnCount];
2225
2226 for (int i = 0; i < columnCount; i++) {
2227 String column = cursor.getColumnName(i);
2228
2229 switch (column) {
2230 case Settings.NameValueTable._ID: {
2231 values[i] = setting.getId();
2232 } break;
2233
2234 case Settings.NameValueTable.NAME: {
2235 values[i] = setting.getName();
2236 } break;
2237
2238 case Settings.NameValueTable.VALUE: {
2239 values[i] = setting.getValue();
2240 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002241 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002242 }
2243
Svetoslav683914b2015-01-15 14:22:26 -08002244 cursor.addRow(values);
2245 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002246
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002247 private static boolean isKeyValid(String key) {
2248 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2249 }
2250
Matt Pape7b1c6cd2019-01-04 08:10:41 -08002251 private String resolveCallingPackage() {
2252 switch (Binder.getCallingUid()) {
2253 case Process.ROOT_UID: {
2254 return "root";
2255 }
2256
2257 case Process.SHELL_UID: {
2258 return "com.android.shell";
2259 }
2260
2261 default: {
2262 return getCallingPackage();
2263 }
2264 }
2265 }
2266
Svetoslav683914b2015-01-15 14:22:26 -08002267 private static final class Arguments {
2268 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2269 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2270
2271 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2272 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2273
2274 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2275 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2276
2277 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2278 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2279
2280 public final String table;
2281 public final String name;
2282
2283 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2284 final int segmentSize = uri.getPathSegments().size();
2285 switch (segmentSize) {
2286 case 1: {
2287 if (where != null
2288 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2289 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2290 && whereArgs.length == 1) {
2291 name = whereArgs[0];
2292 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002293 return;
Svetoslav683914b2015-01-15 14:22:26 -08002294 } else if (where != null
2295 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2296 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2297 final int startIndex = Math.max(where.indexOf("'"),
2298 where.indexOf("\"")) + 1;
2299 final int endIndex = Math.max(where.lastIndexOf("'"),
2300 where.lastIndexOf("\""));
2301 name = where.substring(startIndex, endIndex);
2302 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002303 return;
Svetoslav683914b2015-01-15 14:22:26 -08002304 } else if (supportAll && where == null && whereArgs == null) {
2305 name = null;
2306 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002307 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002308 }
Svetoslav683914b2015-01-15 14:22:26 -08002309 } break;
2310
Svetoslav28494652015-02-12 14:11:42 -08002311 case 2: {
2312 if (where == null && whereArgs == null) {
2313 name = uri.getPathSegments().get(1);
2314 table = computeTableForSetting(uri, name);
2315 return;
2316 }
2317 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002318 }
Svetoslav28494652015-02-12 14:11:42 -08002319
2320 EventLogTags.writeUnsupportedSettingsQuery(
2321 uri.toSafeString(), where, Arrays.toString(whereArgs));
2322 String message = String.format( "Supported SQL:\n"
2323 + " uri content://some_table/some_property with null where and where args\n"
2324 + " uri content://some_table with query name=? and single name as arg\n"
2325 + " uri content://some_table with query name=some_name and null args\n"
2326 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2327 Arrays.toString(whereArgs));
2328 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002329 }
2330
Svetoslav28494652015-02-12 14:11:42 -08002331 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002332 String table = getValidTableOrThrow(uri);
2333
2334 if (name != null) {
2335 if (sSystemMovedToSecureSettings.contains(name)) {
2336 table = TABLE_SECURE;
2337 }
2338
2339 if (sSystemMovedToGlobalSettings.contains(name)) {
2340 table = TABLE_GLOBAL;
2341 }
2342
2343 if (sSecureMovedToGlobalSettings.contains(name)) {
2344 table = TABLE_GLOBAL;
2345 }
2346
2347 if (sGlobalMovedToSecureSettings.contains(name)) {
2348 table = TABLE_SECURE;
2349 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002350 }
Svetoslav683914b2015-01-15 14:22:26 -08002351
2352 return table;
2353 }
2354 }
2355
2356 final class SettingsRegistry {
2357 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2358
Svetoslav683914b2015-01-15 14:22:26 -08002359 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2360 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2361 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002362 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002363 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002364
2365 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002366
2367 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2368
Svet Ganov53a441c2016-04-19 19:38:00 -07002369 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002370
Svetoslav7e0683b2015-08-03 16:02:52 -07002371 private final Handler mHandler;
2372
Svet Ganov53a441c2016-04-19 19:38:00 -07002373 private final BackupManager mBackupManager;
2374
Amith Yamasani39452022017-03-21 15:23:47 -07002375 private String mSettingsCreationBuildId;
2376
Svetoslav683914b2015-01-15 14:22:26 -08002377 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002378 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002379 mGenerationRegistry = new GenerationRegistry(mLock);
2380 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002381 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002382 syncSsaidTableOnStart();
2383 }
2384
2385 private void generateUserKeyLocked(int userId) {
2386 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002387 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002388 final SecureRandom rand = new SecureRandom();
2389 rand.nextBytes(keyBytes);
2390
2391 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002392 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002393
2394 // Store the key in the ssaid table.
2395 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2396 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2397 true, SettingsState.SYSTEM_PACKAGE_NAME);
2398
2399 if (!success) {
2400 throw new IllegalStateException("Ssaid settings not accessible");
2401 }
2402 }
2403
Mark Rathjen7599f132017-01-23 14:15:54 -08002404 private byte[] getLengthPrefix(byte[] data) {
2405 return ByteBuffer.allocate(4).putInt(data.length).array();
2406 }
2407
Christopher Tateb218e762017-04-05 16:34:07 -07002408 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002409 // Read the user's key from the ssaid table.
2410 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002411 if (userKeySetting == null || userKeySetting.isNull()
2412 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002413 // Lazy initialize and store the user key.
2414 generateUserKeyLocked(userId);
2415 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002416 if (userKeySetting == null || userKeySetting.isNull()
2417 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002418 throw new IllegalStateException("User key not accessible");
2419 }
2420 }
2421 final String userKey = userKeySetting.getValue();
2422
2423 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002424 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2425
2426 // Validate that the key is of expected length.
2427 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2428 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002429 throw new IllegalStateException("User key invalid");
2430 }
2431
Mark Rathjen7599f132017-01-23 14:15:54 -08002432 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002433 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002434 m = Mac.getInstance("HmacSHA256");
2435 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002436 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002437 throw new IllegalStateException("HmacSHA256 is not available", e);
2438 } catch (InvalidKeyException e) {
2439 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002440 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002441
Mark Rathjenf42dd912017-06-05 19:04:34 -07002442 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002443 for (int i = 0; i < callingPkg.signatures.length; i++) {
2444 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002445 m.update(getLengthPrefix(sig), 0, 4);
2446 m.update(sig);
2447 }
Mark Rathjend891f012017-01-19 04:10:37 +00002448
2449 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002450 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2451 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002452
2453 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002454 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002455 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2456 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002457 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002458
2459 if (!success) {
2460 throw new IllegalStateException("Ssaid settings not accessible");
2461 }
2462
2463 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2464 }
2465
2466 public void syncSsaidTableOnStart() {
2467 synchronized (mLock) {
2468 // Verify that each user's packages and ssaid's are in sync.
2469 for (UserInfo user : mUserManager.getUsers(true)) {
2470 // Get all uids for the user's packages.
2471 final List<PackageInfo> packages;
2472 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002473 packages = mPackageManager.getInstalledPackages(
2474 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2475 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002476 } catch (RemoteException e) {
2477 throw new IllegalStateException("Package manager not available");
2478 }
2479 final Set<String> appUids = new HashSet<>();
2480 for (PackageInfo info : packages) {
2481 appUids.add(Integer.toString(info.applicationInfo.uid));
2482 }
2483
2484 // Get all uids currently stored in the user's ssaid table.
2485 final Set<String> ssaidUids = new HashSet<>(
2486 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2487 ssaidUids.remove(SSAID_USER_KEY);
2488
2489 // Perform a set difference for the appUids and ssaidUids.
2490 ssaidUids.removeAll(appUids);
2491
2492 // If there are ssaidUids left over they need to be removed from the table.
2493 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2494 user.id);
2495 for (String uid : ssaidUids) {
2496 ssaidSettings.deleteSettingLocked(uid);
2497 }
2498 }
2499 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002500 }
2501
Svetoslav683914b2015-01-15 14:22:26 -08002502 public List<String> getSettingsNamesLocked(int type, int userId) {
2503 final int key = makeKey(type, userId);
2504 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002505 if (settingsState == null) {
2506 return new ArrayList<String>();
2507 }
Svetoslav683914b2015-01-15 14:22:26 -08002508 return settingsState.getSettingNamesLocked();
2509 }
2510
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002511 public SparseBooleanArray getKnownUsersLocked() {
2512 SparseBooleanArray users = new SparseBooleanArray();
2513 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2514 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2515 }
2516 return users;
2517 }
2518
Kweku Adamsb0886f32017-10-31 15:32:09 -07002519 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002520 public SettingsState getSettingsLocked(int type, int userId) {
2521 final int key = makeKey(type, userId);
2522 return peekSettingsStateLocked(key);
2523 }
2524
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002525 public boolean ensureSettingsForUserLocked(int userId) {
2526 // First make sure this user actually exists.
2527 if (mUserManager.getUserInfo(userId) == null) {
2528 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2529 return false;
2530 }
2531
Svetoslav683914b2015-01-15 14:22:26 -08002532 // Migrate the setting for this user if needed.
2533 migrateLegacySettingsForUserIfNeededLocked(userId);
2534
Matt Pape1b31a332018-10-17 09:58:28 -07002535 // Ensure config settings loaded if owner.
2536 if (userId == UserHandle.USER_SYSTEM) {
2537 final int configKey
2538 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2539 ensureSettingsStateLocked(configKey);
2540 }
2541
Svetoslav683914b2015-01-15 14:22:26 -08002542 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002543 if (userId == UserHandle.USER_SYSTEM) {
2544 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002545 ensureSettingsStateLocked(globalKey);
2546 }
2547
2548 // Ensure secure settings loaded.
2549 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2550 ensureSettingsStateLocked(secureKey);
2551
2552 // Make sure the secure settings have an Android id set.
2553 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2554 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2555
2556 // Ensure system settings loaded.
2557 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2558 ensureSettingsStateLocked(systemKey);
2559
Mark Rathjend891f012017-01-19 04:10:37 +00002560 // Ensure secure settings loaded.
2561 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2562 ensureSettingsStateLocked(ssaidKey);
2563
Svetoslav683914b2015-01-15 14:22:26 -08002564 // Upgrade the settings to the latest version.
2565 UpgradeController upgrader = new UpgradeController(userId);
2566 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002567 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002568 }
2569
2570 private void ensureSettingsStateLocked(int key) {
2571 if (mSettingsStates.get(key) == null) {
2572 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002573 SettingsState settingsState = new SettingsState(getContext(), mLock,
2574 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002575 mSettingsStates.put(key, settingsState);
2576 }
2577 }
2578
2579 public void removeUserStateLocked(int userId, boolean permanently) {
2580 // We always keep the global settings in memory.
2581
2582 // Nuke system settings.
2583 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2584 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2585 if (systemSettingsState != null) {
2586 if (permanently) {
2587 mSettingsStates.remove(systemKey);
2588 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002589 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002590 systemSettingsState.destroyLocked(new Runnable() {
2591 @Override
2592 public void run() {
2593 mSettingsStates.remove(systemKey);
2594 }
2595 });
2596 }
2597 }
2598
2599 // Nuke secure settings.
2600 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2601 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2602 if (secureSettingsState != null) {
2603 if (permanently) {
2604 mSettingsStates.remove(secureKey);
2605 secureSettingsState.destroyLocked(null);
2606 } else {
2607 secureSettingsState.destroyLocked(new Runnable() {
2608 @Override
2609 public void run() {
2610 mSettingsStates.remove(secureKey);
2611 }
2612 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002613 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002614 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002615
Mark Rathjend891f012017-01-19 04:10:37 +00002616 // Nuke ssaid settings.
2617 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2618 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2619 if (ssaidSettingsState != null) {
2620 if (permanently) {
2621 mSettingsStates.remove(ssaidKey);
2622 ssaidSettingsState.destroyLocked(null);
2623 } else {
2624 ssaidSettingsState.destroyLocked(new Runnable() {
2625 @Override
2626 public void run() {
2627 mSettingsStates.remove(ssaidKey);
2628 }
2629 });
2630 }
2631 }
2632
Svet Ganov53a441c2016-04-19 19:38:00 -07002633 // Nuke generation tracking data
2634 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002635 }
2636
Svetoslav683914b2015-01-15 14:22:26 -08002637 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002638 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2639 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002640 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2641 packageName, forceNotify, criticalSettings);
2642 }
2643
2644 public boolean insertSettingLocked(int type, int userId, String name, String value,
2645 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2646 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002647 final int key = makeKey(type, userId);
2648
Svetoslav Ganove080da92016-12-21 17:10:35 -08002649 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002650 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002651 if (settingsState != null) {
2652 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002653 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002654 }
Svetoslav683914b2015-01-15 14:22:26 -08002655
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002656 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2657 settingsState.persistSyncLocked();
2658 }
2659
Svet Ganov53a441c2016-04-19 19:38:00 -07002660 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002661 notifyForSettingsChange(key, name);
2662 }
2663 return success;
2664 }
2665
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002666 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2667 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002668 final int key = makeKey(type, userId);
2669
Svetoslav Ganove080da92016-12-21 17:10:35 -08002670 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002671 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002672 if (settingsState != null) {
2673 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002674 }
Svetoslav683914b2015-01-15 14:22:26 -08002675
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002676 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2677 settingsState.persistSyncLocked();
2678 }
2679
Svet Ganov53a441c2016-04-19 19:38:00 -07002680 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002681 notifyForSettingsChange(key, name);
2682 }
2683 return success;
2684 }
2685
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002686 public boolean updateSettingLocked(int type, int userId, String name, String value,
2687 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2688 Set<String> criticalSettings) {
2689 final int key = makeKey(type, userId);
2690
2691 boolean success = false;
2692 SettingsState settingsState = peekSettingsStateLocked(key);
2693 if (settingsState != null) {
2694 success = settingsState.updateSettingLocked(name, value, tag,
2695 makeDefault, packageName);
2696 }
2697
2698 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2699 settingsState.persistSyncLocked();
2700 }
2701
2702 if (forceNotify || success) {
2703 notifyForSettingsChange(key, name);
2704 }
2705
2706 return success;
2707 }
2708
Svetoslav683914b2015-01-15 14:22:26 -08002709 public Setting getSettingLocked(int type, int userId, String name) {
2710 final int key = makeKey(type, userId);
2711
2712 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002713 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002714 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002715 }
Mark Rathjend891f012017-01-19 04:10:37 +00002716
2717 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002718 return settingsState.getSettingLocked(name);
2719 }
2720
Svetoslav Ganove080da92016-12-21 17:10:35 -08002721 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2722 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002723 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2724 }
2725
2726 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2727 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002728 final int key = makeKey(type, userId);
2729 SettingsState settingsState = peekSettingsStateLocked(key);
2730 if (settingsState == null) {
2731 return;
2732 }
2733
2734 switch (mode) {
2735 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2736 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002737 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002738 Setting setting = settingsState.getSettingLocked(name);
2739 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002740 if ((tag != null && !tag.equals(setting.getTag()))
2741 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002742 continue;
2743 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002744 if (settingsState.resetSettingLocked(name)) {
2745 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002746 notifyForSettingsChange(key, name);
2747 }
2748 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002749 if (someSettingChanged) {
2750 settingsState.persistSyncLocked();
2751 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002752 }
2753 } break;
2754
2755 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2756 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002757 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002758 Setting setting = settingsState.getSettingLocked(name);
2759 if (!SettingsState.isSystemPackage(getContext(),
2760 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002761 if (prefix != null && !setting.getName().startsWith(prefix)) {
2762 continue;
2763 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002764 if (settingsState.resetSettingLocked(name)) {
2765 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002766 notifyForSettingsChange(key, name);
2767 }
2768 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002769 if (someSettingChanged) {
2770 settingsState.persistSyncLocked();
2771 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002772 }
2773 } break;
2774
2775 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2776 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002777 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002778 Setting setting = settingsState.getSettingLocked(name);
2779 if (!SettingsState.isSystemPackage(getContext(),
2780 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002781 if (prefix != null && !setting.getName().startsWith(prefix)) {
2782 continue;
2783 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002784 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002785 if (settingsState.resetSettingLocked(name)) {
2786 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002787 notifyForSettingsChange(key, name);
2788 }
2789 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002790 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002791 notifyForSettingsChange(key, name);
2792 }
2793 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002794 if (someSettingChanged) {
2795 settingsState.persistSyncLocked();
2796 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002797 }
2798 } break;
2799
2800 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2801 for (String name : settingsState.getSettingNamesLocked()) {
2802 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002803 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002804 if (prefix != null && !setting.getName().startsWith(prefix)) {
2805 continue;
2806 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002807 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002808 if (settingsState.resetSettingLocked(name)) {
2809 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002810 notifyForSettingsChange(key, name);
2811 }
2812 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002813 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002814 notifyForSettingsChange(key, name);
2815 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002816 if (someSettingChanged) {
2817 settingsState.persistSyncLocked();
2818 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002819 }
2820 } break;
2821 }
2822 }
2823
Zimuzoc56192c2018-07-25 10:40:01 +01002824 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002825 // Global and secure settings are signature protected. Apps signed
2826 // by the platform certificate are generally not uninstalled and
2827 // the main exception is tests. We trust components signed
2828 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002829
2830 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2831 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002832 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002833 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002834 }
Svetoslav683914b2015-01-15 14:22:26 -08002835 }
2836
Mark Rathjend891f012017-01-19 04:10:37 +00002837 public void onUidRemovedLocked(int uid) {
2838 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2839 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002840 if (ssaidSettings != null) {
2841 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2842 }
Mark Rathjend891f012017-01-19 04:10:37 +00002843 }
2844
Kweku Adamsb0886f32017-10-31 15:32:09 -07002845 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002846 private SettingsState peekSettingsStateLocked(int key) {
2847 SettingsState settingsState = mSettingsStates.get(key);
2848 if (settingsState != null) {
2849 return settingsState;
2850 }
2851
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002852 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2853 return null;
2854 }
Svetoslav683914b2015-01-15 14:22:26 -08002855 return mSettingsStates.get(key);
2856 }
2857
2858 private void migrateAllLegacySettingsIfNeeded() {
2859 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002860 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002861 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002862 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002863 return;
2864 }
2865
Amith Yamasani39452022017-03-21 15:23:47 -07002866 mSettingsCreationBuildId = Build.ID;
2867
Svetoslav683914b2015-01-15 14:22:26 -08002868 final long identity = Binder.clearCallingIdentity();
2869 try {
2870 List<UserInfo> users = mUserManager.getUsers(true);
2871
2872 final int userCount = users.size();
2873 for (int i = 0; i < userCount; i++) {
2874 final int userId = users.get(i).id;
2875
2876 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2877 SQLiteDatabase database = dbHelper.getWritableDatabase();
2878 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2879
2880 // Upgrade to the latest version.
2881 UpgradeController upgrader = new UpgradeController(userId);
2882 upgrader.upgradeIfNeededLocked();
2883
2884 // Drop from memory if not a running user.
2885 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2886 removeUserStateLocked(userId, false);
2887 }
2888 }
2889 } finally {
2890 Binder.restoreCallingIdentity(identity);
2891 }
2892 }
2893 }
2894
2895 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2896 // Every user has secure settings and if no file we need to migrate.
2897 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2898 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002899 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002900 return;
2901 }
2902
2903 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2904 SQLiteDatabase database = dbHelper.getWritableDatabase();
2905
2906 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2907 }
2908
2909 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2910 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002911 // Move over the system settings.
2912 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2913 ensureSettingsStateLocked(systemKey);
2914 SettingsState systemSettings = mSettingsStates.get(systemKey);
2915 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2916 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002917
2918 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002919 // Do this after System settings, since this is the first thing we check when deciding
2920 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002921 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2922 ensureSettingsStateLocked(secureKey);
2923 SettingsState secureSettings = mSettingsStates.get(secureKey);
2924 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2925 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2926 secureSettings.persistSyncLocked();
2927
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002928 // Move over the global settings if owner.
2929 // Do this last, since this is the first thing we check when deciding
2930 // to skip over migration from db to xml for owner user.
2931 if (userId == UserHandle.USER_SYSTEM) {
2932 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2933 ensureSettingsStateLocked(globalKey);
2934 SettingsState globalSettings = mSettingsStates.get(globalKey);
2935 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002936 // If this was just created
2937 if (mSettingsCreationBuildId != null) {
2938 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2939 mSettingsCreationBuildId, null, true,
2940 SettingsState.SYSTEM_PACKAGE_NAME);
2941 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002942 globalSettings.persistSyncLocked();
2943 }
Svetoslav683914b2015-01-15 14:22:26 -08002944
2945 // Drop the database as now all is moved and persisted.
2946 if (DROP_DATABASE_ON_MIGRATION) {
2947 dbHelper.dropDatabase();
2948 } else {
2949 dbHelper.backupDatabase();
2950 }
2951 }
2952
2953 private void migrateLegacySettingsLocked(SettingsState settingsState,
2954 SQLiteDatabase database, String table) {
2955 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2956 queryBuilder.setTables(table);
2957
2958 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2959 null, null, null, null, null);
2960
2961 if (cursor == null) {
2962 return;
2963 }
2964
2965 try {
2966 if (!cursor.moveToFirst()) {
2967 return;
2968 }
2969
2970 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2971 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2972
2973 settingsState.setVersionLocked(database.getVersion());
2974
2975 while (!cursor.isAfterLast()) {
2976 String name = cursor.getString(nameColumnIdx);
2977 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002978 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002979 SettingsState.SYSTEM_PACKAGE_NAME);
2980 cursor.moveToNext();
2981 }
2982 } finally {
2983 cursor.close();
2984 }
2985 }
2986
Andreas Gampeb58893072018-09-05 16:52:31 -07002987 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002988 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2989 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2990
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002991 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002992 return;
2993 }
2994
2995 final int userId = getUserIdFromKey(secureSettings.mKey);
2996
2997 final UserInfo user;
2998 final long identity = Binder.clearCallingIdentity();
2999 try {
3000 user = mUserManager.getUserInfo(userId);
3001 } finally {
3002 Binder.restoreCallingIdentity(identity);
3003 }
3004 if (user == null) {
3005 // Can happen due to races when deleting users - treat as benign.
3006 return;
3007 }
3008
3009 String androidId = Long.toHexString(new SecureRandom().nextLong());
3010 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003011 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003012
3013 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3014 + "] for user " + userId);
3015
3016 // Write a drop box entry if it's a restricted profile
3017 if (user.isRestricted()) {
3018 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3019 Context.DROPBOX_SERVICE);
3020 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3021 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3022 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3023 }
3024 }
3025 }
3026
3027 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003028 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003029 mGenerationRegistry.incrementGeneration(key);
3030
Svet Ganov945864c2018-03-22 21:49:10 -07003031 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003032 final long token = Binder.clearCallingIdentity();
3033 try {
3034 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3035 // When the global kill switch is updated, send the
3036 // change notification for the location setting.
3037 notifyLocationChangeForRunningUsers();
3038 }
3039 notifyGlobalSettingChangeForRunningUsers(key, name);
3040 } finally {
3041 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003042 }
Svet Ganov945864c2018-03-22 21:49:10 -07003043 } else {
3044 final int userId = getUserIdFromKey(key);
3045 final Uri uri = getNotificationUriFor(key, name);
3046 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3047 userId, 0, uri).sendToTarget();
3048 if (isSecureSettingsKey(key)) {
3049 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3050 sSecureCloneToManagedSettings);
3051 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3052 sSystemCloneFromParentOnDependency.values());
3053 } else if (isSystemSettingsKey(key)) {
3054 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3055 sSystemCloneToManagedSettings);
3056 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003057 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003058
Svet Ganov945864c2018-03-22 21:49:10 -07003059 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003060 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003061 }
3062
Svet Ganov53a441c2016-04-19 19:38:00 -07003063 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003064 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003065 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003066 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003067 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003068 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003069 final int key = makeKey(type, profileId);
3070 // Increment the generation first, so observers always see the new value
3071 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003072 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003073 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003074 }
3075 }
3076 }
Svetoslav683914b2015-01-15 14:22:26 -08003077 }
3078
Svet Ganov945864c2018-03-22 21:49:10 -07003079 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3080 // Important: No need to update generation for each user as there
3081 // is a singleton generation entry for the global settings which
3082 // is already incremented be the caller.
3083 final Uri uri = getNotificationUriFor(key, name);
3084 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3085 for (int i = 0; i < users.size(); i++) {
3086 final int userId = users.get(i).id;
3087 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3088 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3089 userId, 0, uri).sendToTarget();
3090 }
3091 }
3092 }
3093
Makoto Onuki0000d322017-11-28 16:31:47 -08003094 private void notifyLocationChangeForRunningUsers() {
3095 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3096
3097 for (int i = 0; i < users.size(); i++) {
3098 final int userId = users.get(i).id;
3099
3100 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3101 continue;
3102 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003103
Svet Ganov945864c2018-03-22 21:49:10 -07003104 // Increment the generation first, so observers always see the new value
3105 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3106 mGenerationRegistry.incrementGeneration(key);
3107
3108 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003109 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3110 userId, 0, uri).sendToTarget();
3111 }
3112 }
3113
Matt Pape1b31a332018-10-17 09:58:28 -07003114 private boolean isConfigSettingsKey(int key) {
3115 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3116 }
3117
Svetoslav683914b2015-01-15 14:22:26 -08003118 private boolean isGlobalSettingsKey(int key) {
3119 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3120 }
3121
3122 private boolean isSystemSettingsKey(int key) {
3123 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3124 }
3125
3126 private boolean isSecureSettingsKey(int key) {
3127 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3128 }
3129
Mark Rathjend891f012017-01-19 04:10:37 +00003130 private boolean isSsaidSettingsKey(int key) {
3131 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3132 }
3133
Svetoslav683914b2015-01-15 14:22:26 -08003134 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003135 if (isConfigSettingsKey(key)) {
3136 final int userId = getUserIdFromKey(key);
3137 return new File(Environment.getUserSystemDirectory(userId),
3138 SETTINGS_FILE_CONFIG);
3139 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003140 final int userId = getUserIdFromKey(key);
3141 return new File(Environment.getUserSystemDirectory(userId),
3142 SETTINGS_FILE_GLOBAL);
3143 } else if (isSystemSettingsKey(key)) {
3144 final int userId = getUserIdFromKey(key);
3145 return new File(Environment.getUserSystemDirectory(userId),
3146 SETTINGS_FILE_SYSTEM);
3147 } else if (isSecureSettingsKey(key)) {
3148 final int userId = getUserIdFromKey(key);
3149 return new File(Environment.getUserSystemDirectory(userId),
3150 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003151 } else if (isSsaidSettingsKey(key)) {
3152 final int userId = getUserIdFromKey(key);
3153 return new File(Environment.getUserSystemDirectory(userId),
3154 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003155 } else {
3156 throw new IllegalArgumentException("Invalid settings key:" + key);
3157 }
3158 }
3159
3160 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003161 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003162 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3163 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003164 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003165 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3166 : Settings.Global.CONTENT_URI;
3167 } else if (isSecureSettingsKey(key)) {
3168 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3169 : Settings.Secure.CONTENT_URI;
3170 } else if (isSystemSettingsKey(key)) {
3171 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3172 : Settings.System.CONTENT_URI;
3173 } else {
3174 throw new IllegalArgumentException("Invalid settings key:" + key);
3175 }
3176 }
3177
3178 private int getMaxBytesPerPackageForType(int type) {
3179 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003180 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003181 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003182 case SETTINGS_TYPE_SECURE:
3183 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003184 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3185 }
3186
3187 default: {
3188 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3189 }
3190 }
3191 }
3192
Svetoslav7e0683b2015-08-03 16:02:52 -07003193 private final class MyHandler extends Handler {
3194 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3195 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3196
3197 public MyHandler(Looper looper) {
3198 super(looper);
3199 }
3200
3201 @Override
3202 public void handleMessage(Message msg) {
3203 switch (msg.what) {
3204 case MSG_NOTIFY_URI_CHANGED: {
3205 final int userId = msg.arg1;
3206 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003207 try {
3208 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3209 } catch (SecurityException e) {
3210 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3211 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003212 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003213 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3214 }
3215 } break;
3216
3217 case MSG_NOTIFY_DATA_CHANGED: {
3218 mBackupManager.dataChanged();
3219 } break;
3220 }
3221 }
3222 }
3223
Svetoslav683914b2015-01-15 14:22:26 -08003224 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003225 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003226
3227 private final int mUserId;
3228
3229 public UpgradeController(int userId) {
3230 mUserId = userId;
3231 }
3232
3233 public void upgradeIfNeededLocked() {
3234 // The version of all settings for a user is the same (all users have secure).
3235 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003236 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003237
3238 // Try an update from the current state.
3239 final int oldVersion = secureSettings.getVersionLocked();
3240 final int newVersion = SETTINGS_VERSION;
3241
Svet Ganovc9755bc2015-03-28 13:21:22 -07003242 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003243 if (oldVersion == newVersion) {
3244 return;
3245 }
3246
3247 // Try to upgrade.
3248 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3249
3250 // If upgrade failed start from scratch and upgrade.
3251 if (curVersion != newVersion) {
3252 // Drop state we have for this user.
3253 removeUserStateLocked(mUserId, true);
3254
3255 // Recreate the database.
3256 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3257 SQLiteDatabase database = dbHelper.getWritableDatabase();
3258 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3259
3260 // Migrate the settings for this user.
3261 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3262
3263 // Now upgrade should work fine.
3264 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003265
3266 // Make a note what happened, so we don't wonder why data was lost
3267 String reason = "Settings rebuilt! Current version: "
3268 + curVersion + " while expected: " + newVersion;
3269 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003270 Settings.Global.DATABASE_DOWNGRADE_REASON,
3271 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003272 }
3273
3274 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003275 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003276 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003277 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003278 globalSettings.setVersionLocked(newVersion);
3279 }
3280
3281 // Set the secure settings version.
3282 secureSettings.setVersionLocked(newVersion);
3283
3284 // Set the system settings version.
3285 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003286 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003287 systemSettings.setVersionLocked(newVersion);
3288 }
3289
3290 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003291 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003292 }
3293
3294 private SettingsState getSecureSettingsLocked(int userId) {
3295 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3296 }
3297
Mark Rathjend891f012017-01-19 04:10:37 +00003298 private SettingsState getSsaidSettingsLocked(int userId) {
3299 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3300 }
3301
Svetoslav683914b2015-01-15 14:22:26 -08003302 private SettingsState getSystemSettingsLocked(int userId) {
3303 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3304 }
3305
Jeff Brown503cffc2015-03-26 18:08:51 -07003306 /**
3307 * You must perform all necessary mutations to bring the settings
3308 * for this user from the old to the new version. When you add a new
3309 * upgrade step you *must* update SETTINGS_VERSION.
3310 *
3311 * This is an example of moving a setting from secure to global.
3312 *
3313 * // v119: Example settings changes.
3314 * if (currentVersion == 118) {
3315 * if (userId == UserHandle.USER_OWNER) {
3316 * // Remove from the secure settings.
3317 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3318 * String name = "example_setting_to_move";
3319 * String value = secureSettings.getSetting(name);
3320 * secureSettings.deleteSetting(name);
3321 *
3322 * // Add to the global settings.
3323 * SettingsState globalSettings = getGlobalSettingsLocked();
3324 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3325 * }
3326 *
3327 * // Update the current version.
3328 * currentVersion = 119;
3329 * }
3330 */
Svetoslav683914b2015-01-15 14:22:26 -08003331 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3332 if (DEBUG) {
3333 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3334 + oldVersion + " to version: " + newVersion);
3335 }
3336
Jeff Brown503cffc2015-03-26 18:08:51 -07003337 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003338
John Spurlocke11ae112015-05-11 16:09:03 -04003339 // v119: Reset zen + ringer mode.
3340 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003341 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003342 final SettingsState globalSettings = getGlobalSettingsLocked();
3343 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003344 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3345 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003346 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003347 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3348 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003349 }
3350 currentVersion = 119;
3351 }
3352
Jason Monk27bbb2d2015-03-31 16:46:39 -04003353 // v120: Add double tap to wake setting.
3354 if (currentVersion == 119) {
3355 SettingsState secureSettings = getSecureSettingsLocked(userId);
3356 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3357 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003358 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003359 SettingsState.SYSTEM_PACKAGE_NAME);
3360
3361 currentVersion = 120;
3362 }
3363
Svetoslav7e0683b2015-08-03 16:02:52 -07003364 if (currentVersion == 120) {
3365 // Before 121, we used a different string encoding logic. We just bump the
3366 // version here; SettingsState knows how to handle pre-version 120 files.
3367 currentVersion = 121;
3368 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003369
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003370 if (currentVersion == 121) {
3371 // Version 122: allow OEMs to set a default payment component in resources.
3372 // Note that we only write the default if no default has been set;
3373 // if there is, we just leave the default at whatever it currently is.
3374 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3375 String defaultComponent = (getContext().getResources().getString(
3376 R.string.def_nfc_payment_component));
3377 Setting currentSetting = secureSettings.getSettingLocked(
3378 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3379 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003380 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003381 secureSettings.insertSettingLocked(
3382 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003383 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003384 }
3385 currentVersion = 122;
3386 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003387
3388 if (currentVersion == 122) {
3389 // Version 123: Adding a default value for the ability to add a user from
3390 // the lock screen.
3391 if (userId == UserHandle.USER_SYSTEM) {
3392 final SettingsState globalSettings = getGlobalSettingsLocked();
3393 Setting currentSetting = globalSettings.getSettingLocked(
3394 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003395 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003396 globalSettings.insertSettingLocked(
3397 Settings.Global.ADD_USERS_WHEN_LOCKED,
3398 getContext().getResources().getBoolean(
3399 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003400 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003401 }
3402 }
3403 currentVersion = 123;
3404 }
Bryce Leebd179282015-12-17 19:01:37 -08003405
3406 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003407 final SettingsState globalSettings = getGlobalSettingsLocked();
3408 String defaultDisabledProfiles = (getContext().getResources().getString(
3409 R.string.def_bluetooth_disabled_profiles));
3410 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003411 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003412 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003413 }
3414
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003415 if (currentVersion == 124) {
3416 // Version 124: allow OEMs to set a default value for whether IME should be
3417 // shown when a physical keyboard is connected.
3418 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3419 Setting currentSetting = secureSettings.getSettingLocked(
3420 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003421 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003422 secureSettings.insertSettingLocked(
3423 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3424 getContext().getResources().getBoolean(
3425 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003426 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003427 }
3428 currentVersion = 125;
3429 }
3430
Ruben Brunk98576cf2016-03-07 18:54:28 -08003431 if (currentVersion == 125) {
3432 // Version 125: Allow OEMs to set the default VR service.
3433 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3434
3435 Setting currentSetting = secureSettings.getSettingLocked(
3436 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003437 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003438 ArraySet<ComponentName> l =
3439 SystemConfig.getInstance().getDefaultVrComponents();
3440
3441 if (l != null && !l.isEmpty()) {
3442 StringBuilder b = new StringBuilder();
3443 boolean start = true;
3444 for (ComponentName c : l) {
3445 if (!start) {
3446 b.append(':');
3447 }
3448 b.append(c.flattenToString());
3449 start = false;
3450 }
3451 secureSettings.insertSettingLocked(
3452 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003453 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003454 }
3455
3456 }
3457 currentVersion = 126;
3458 }
3459
Daniel U02ba6122016-04-01 18:41:42 +01003460 if (currentVersion == 126) {
3461 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3462 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3463 if (mUserManager.isManagedProfile(userId)) {
3464 final SettingsState systemSecureSettings =
3465 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3466
3467 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3468 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003469 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003470 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3471 secureSettings.insertSettingLocked(
3472 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003473 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003474 SettingsState.SYSTEM_PACKAGE_NAME);
3475 }
3476
3477 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3478 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003479 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003480 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3481 secureSettings.insertSettingLocked(
3482 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003483 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003484 SettingsState.SYSTEM_PACKAGE_NAME);
3485 }
3486 }
3487 currentVersion = 127;
3488 }
3489
Steven Ngdc20ba62016-04-26 18:19:04 +01003490 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003491 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003492 currentVersion = 128;
3493 }
3494
Julia Reynolds1f721e12016-07-11 08:50:58 -04003495 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003496 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003497 currentVersion = 129;
3498 }
3499
Dan Sandler71f85e92016-07-20 13:46:05 -04003500 if (currentVersion == 129) {
3501 // default longpress timeout changed from 500 to 400. If unchanged from the old
3502 // default, update to the new default.
3503 final SettingsState systemSecureSettings =
3504 getSecureSettingsLocked(userId);
3505 final String oldValue = systemSecureSettings.getSettingLocked(
3506 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3507 if (TextUtils.equals("500", oldValue)) {
3508 systemSecureSettings.insertSettingLocked(
3509 Settings.Secure.LONG_PRESS_TIMEOUT,
3510 String.valueOf(getContext().getResources().getInteger(
3511 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003512 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003513 }
3514 currentVersion = 130;
3515 }
3516
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003517 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003518 // Split Ambient settings
3519 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3520 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3521 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3522
3523 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003524 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003525 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003526 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003527 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003528 }
3529 currentVersion = 131;
3530 }
3531
3532 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003533 // Initialize new multi-press timeout to default value
3534 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3535 final String oldValue = systemSecureSettings.getSettingLocked(
3536 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3537 if (TextUtils.equals(null, oldValue)) {
3538 systemSecureSettings.insertSettingLocked(
3539 Settings.Secure.MULTI_PRESS_TIMEOUT,
3540 String.valueOf(getContext().getResources().getInteger(
3541 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003542 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003543 }
3544
Adrian Roos69741a22016-10-21 14:49:17 -07003545 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003546 }
3547
Adrian Roos69741a22016-10-21 14:49:17 -07003548 if (currentVersion == 132) {
3549 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003550 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3551 String defaultSyncParentSounds = (getContext().getResources()
3552 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3553 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003554 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3555 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003556 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003557 }
3558
Adrian Roos69741a22016-10-21 14:49:17 -07003559 if (currentVersion == 133) {
3560 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003561 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003562 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3563 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003564 String defaultEndButtonBehavior = Integer.toString(getContext()
3565 .getResources().getInteger(R.integer.def_end_button_behavior));
3566 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003567 defaultEndButtonBehavior, null, true,
3568 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003569 }
Adrian Roos69741a22016-10-21 14:49:17 -07003570 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003571 }
3572
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003573 if (currentVersion == 134) {
3574 // Remove setting that specifies if magnification values should be preserved.
3575 // This setting defaulted to true and never has a UI.
3576 getSecureSettingsLocked(userId).deleteSettingLocked(
3577 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3578 currentVersion = 135;
3579 }
3580
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003581 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003582 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003583 currentVersion = 136;
3584 }
3585
Mark Rathjend891f012017-01-19 04:10:37 +00003586 if (currentVersion == 136) {
3587 // Version 136: Store legacy SSAID for all apps currently installed on the
3588 // device as first step in migrating SSAID to be unique per application.
3589
3590 final boolean isUpgrade;
3591 try {
3592 isUpgrade = mPackageManager.isUpgrade();
3593 } catch (RemoteException e) {
3594 throw new IllegalStateException("Package manager not available");
3595 }
3596 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3597 // user data or first boot on a new device should use new ssaid generation.
3598 if (isUpgrade) {
3599 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003600 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3601 userId, Settings.Secure.ANDROID_ID);
3602 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3603 || legacySsaidSetting.getValue() == null) {
3604 throw new IllegalStateException("Legacy ssaid not accessible");
3605 }
3606 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003607
3608 // Fill each uid with the legacy ssaid to be backwards compatible.
3609 final List<PackageInfo> packages;
3610 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003611 packages = mPackageManager.getInstalledPackages(
3612 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3613 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003614 } catch (RemoteException e) {
3615 throw new IllegalStateException("Package manager not available");
3616 }
3617
3618 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3619 for (PackageInfo info : packages) {
3620 // Check if the UID already has an entry in the table.
3621 final String uid = Integer.toString(info.applicationInfo.uid);
3622 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3623
3624 if (ssaid.isNull() || ssaid.getValue() == null) {
3625 // Android Id doesn't exist for this package so create it.
3626 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3627 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003628 if (DEBUG) {
3629 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3630 }
Mark Rathjend891f012017-01-19 04:10:37 +00003631 }
3632 }
3633 }
3634
3635 currentVersion = 137;
3636 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003637 if (currentVersion == 137) {
3638 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3639 // default value set to 1. The user can no longer change the value of this
3640 // setting through the UI.
3641 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3642 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003643 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3644 && secureSetting.getSettingLocked(
3645 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3646
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003647 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3648 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003649 // For managed profiles with profile owners, DevicePolicyManagerService
3650 // may want to set the user restriction in this case
3651 secureSetting.insertSettingLocked(
3652 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3653 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003654 }
3655 currentVersion = 138;
3656 }
Mark Rathjend891f012017-01-19 04:10:37 +00003657
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003658 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003659 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003660 currentVersion = 139;
3661 }
3662
Phil Weaver385912e2017-02-10 10:06:56 -08003663 if (currentVersion == 139) {
3664 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3665 // the user can no longer change the value of this setting through the UI.
3666 // Force to true.
3667 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3668 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3669 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3670 currentVersion = 140;
3671 }
3672
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003673 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003674 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003675 currentVersion = 141;
3676 }
3677
Svet Ganov13701552017-02-23 12:45:17 -08003678 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003679 // This implementation was incorrectly setting the current value of
3680 // settings changed by non-system packages as the default which default
3681 // is set by the system. We add a new upgrade step at the end to properly
3682 // handle this case which would also fix incorrect changes made by the
3683 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003684 currentVersion = 142;
3685 }
3686
Stephen Chen5d0922f2017-03-27 10:28:04 -07003687 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003688 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003689 if (userId == UserHandle.USER_SYSTEM) {
3690 final SettingsState globalSettings = getGlobalSettingsLocked();
3691 Setting currentSetting = globalSettings.getSettingLocked(
3692 Settings.Global.WIFI_WAKEUP_ENABLED);
3693 if (currentSetting.isNull()) {
3694 globalSettings.insertSettingLocked(
3695 Settings.Global.WIFI_WAKEUP_ENABLED,
3696 getContext().getResources().getBoolean(
3697 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3698 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3699 }
3700 }
3701
3702 currentVersion = 143;
3703 }
3704
Felipe Lemeff355092017-04-03 12:55:02 -07003705 if (currentVersion == 143) {
3706 // Version 144: Set a default value for Autofill service.
3707 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3708 final Setting currentSetting = secureSettings
3709 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3710 if (currentSetting.isNull()) {
3711 final String defaultValue = getContext().getResources().getString(
3712 com.android.internal.R.string.config_defaultAutofillService);
3713 if (defaultValue != null) {
3714 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3715 + "for user " + userId);
3716 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3717 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3718 }
3719 }
3720
3721 currentVersion = 144;
3722 }
3723
Jeremy Joslin45caa252017-05-04 11:22:46 -07003724 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003725 // Version 145: Removed
3726 currentVersion = 145;
3727 }
3728
3729 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003730 // Version 146: In step 142 we had a bug where incorrectly
3731 // some settings were considered system set and as a result
3732 // made the default and marked as the default being set by
3733 // the system. Here reevaluate the default and default system
3734 // set flags. This would both fix corruption by the old impl
3735 // of step 142 and also properly handle devices which never
3736 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003737 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003738 SettingsState globalSettings = getGlobalSettingsLocked();
3739 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3740 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003741 }
3742
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003743 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3744 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3745 secureSettings.persistSyncLocked();
3746
3747 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3748 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3749 systemSettings.persistSyncLocked();
3750
Amin Shaikh86367962017-06-07 08:58:22 -07003751 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003752 }
3753
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003754 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003755 // Version 147: Removed. (This version previously allowed showing the
3756 // "wifi_wakeup_available" setting).
3757 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003758 currentVersion = 147;
3759 }
3760
3761 if (currentVersion == 147) {
3762 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003763 if (userId == UserHandle.USER_SYSTEM) {
3764 final SettingsState globalSettings = getGlobalSettingsLocked();
3765 final Setting currentSetting = globalSettings.getSettingLocked(
3766 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3767 if (currentSetting.isNull()) {
3768 globalSettings.insertSettingLocked(
3769 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3770 getContext().getResources().getBoolean(
3771 R.bool.def_restrict_background_data) ? "1" : "0",
3772 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3773 }
3774 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003775 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003776 }
3777
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003778 if (currentVersion == 148) {
3779 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3780 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3781 final String oldValue = systemSecureSettings.getSettingLocked(
3782 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3783 if (TextUtils.equals(null, oldValue)) {
3784 final String defaultValue = getContext().getResources().getString(
3785 R.string.def_backup_manager_constants);
3786 if (!TextUtils.isEmpty(defaultValue)) {
3787 systemSecureSettings.insertSettingLocked(
3788 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3789 true, SettingsState.SYSTEM_PACKAGE_NAME);
3790 }
3791 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003792 currentVersion = 149;
3793 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003794
3795 if (currentVersion == 149) {
3796 // Version 150: Set a default value for mobile data always on
3797 final SettingsState globalSettings = getGlobalSettingsLocked();
3798 final Setting currentSetting = globalSettings.getSettingLocked(
3799 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3800 if (currentSetting.isNull()) {
3801 globalSettings.insertSettingLocked(
3802 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3803 getContext().getResources().getBoolean(
3804 R.bool.def_mobile_data_always_on) ? "1" : "0",
3805 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3806 }
3807
3808 currentVersion = 150;
3809 }
3810
Mike Digman4af4a6f2018-01-16 14:49:38 -08003811 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003812 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003813 currentVersion = 151;
3814 }
3815
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003816 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003817 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3818 // by default but it is now no longer configurable).
3819 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003820 currentVersion = 152;
3821 }
3822
Joe LaPenna250d7842018-01-25 10:19:42 -08003823 if (currentVersion == 152) {
3824 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3825 currentVersion = 153;
3826 }
3827
Ben Linb4df8bc2018-01-29 11:48:20 -08003828 if (currentVersion == 153) {
3829 // Version 154: Read notification badge configuration from config.
3830 // If user has already set the value, don't do anything.
3831 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3832 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3833 Settings.Secure.NOTIFICATION_BADGING);
3834 if (showNotificationBadges.isNull()) {
3835 final boolean defaultValue = getContext().getResources().getBoolean(
3836 com.android.internal.R.bool.config_notificationBadging);
3837 systemSecureSettings.insertSettingLocked(
3838 Secure.NOTIFICATION_BADGING,
3839 defaultValue ? "1" : "0",
3840 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3841 }
3842 currentVersion = 154;
3843 }
3844
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003845 if (currentVersion == 154) {
3846 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3847 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3848 final String oldValue = systemSecureSettings.getSettingLocked(
3849 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3850 if (TextUtils.equals(null, oldValue)) {
3851 final String defaultValue = getContext().getResources().getString(
3852 R.string.def_backup_local_transport_parameters);
3853 if (!TextUtils.isEmpty(defaultValue)) {
3854 systemSecureSettings.insertSettingLocked(
3855 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3856 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3857 }
3858
3859 }
3860 currentVersion = 155;
3861 }
3862
Beverlyda904812018-03-02 09:55:30 -05003863 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003864 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003865 final SettingsState globalSettings = getGlobalSettingsLocked();
3866 final String oldValue = globalSettings.getSettingLocked(
3867 Global.CHARGING_STARTED_SOUND).getValue();
3868 final String oldDefault = getContext().getResources().getString(
3869 R.string.def_wireless_charging_started_sound);
3870 if (TextUtils.equals(null, oldValue)
3871 || TextUtils.equals(oldValue, oldDefault)) {
3872 final String defaultValue = getContext().getResources().getString(
3873 R.string.def_charging_started_sound);
3874 if (!TextUtils.isEmpty(defaultValue)) {
3875 globalSettings.insertSettingLocked(
3876 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3877 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3878 }
3879
3880 }
3881 currentVersion = 156;
3882 }
3883
Beverly09da25f2018-02-26 09:17:07 -05003884 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003885 // Version 157: Set a default value for zen duration,
3886 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003887 final SettingsState globalSettings = getGlobalSettingsLocked();
3888 final Setting currentSetting = globalSettings.getSettingLocked(
3889 Global.ZEN_DURATION);
3890 if (currentSetting.isNull()) {
3891 String defaultZenDuration = Integer.toString(getContext()
3892 .getResources().getInteger(R.integer.def_zen_duration));
3893 globalSettings.insertSettingLocked(
3894 Global.ZEN_DURATION, defaultZenDuration,
3895 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3896 }
Beverly09da25f2018-02-26 09:17:07 -05003897 currentVersion = 157;
3898 }
Annie Mengd069a882018-03-13 15:31:40 +00003899
3900 if (currentVersion == 157) {
3901 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3902 final SettingsState globalSettings = getGlobalSettingsLocked();
3903 final String oldValue = globalSettings.getSettingLocked(
3904 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3905 if (TextUtils.equals(null, oldValue)) {
3906 final String defaultValue = getContext().getResources().getString(
3907 R.string.def_backup_agent_timeout_parameters);
3908 if (!TextUtils.isEmpty(defaultValue)) {
3909 globalSettings.insertSettingLocked(
3910 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3911 null, true,
3912 SettingsState.SYSTEM_PACKAGE_NAME);
3913 }
3914 }
3915 currentVersion = 158;
3916 }
Roshan Pius9c396672018-03-02 14:54:13 -08003917
3918 if (currentVersion == 158) {
3919 // Remove setting that specifies wifi bgscan throttling params
3920 getGlobalSettingsLocked().deleteSettingLocked(
3921 "wifi_scan_background_throttle_interval_ms");
3922 getGlobalSettingsLocked().deleteSettingLocked(
3923 "wifi_scan_background_throttle_package_whitelist");
3924 currentVersion = 159;
3925 }
3926
Pavel Grafovc5c97302018-03-19 13:37:15 +00003927 if (currentVersion == 159) {
3928 // Version 160: Hiding notifications from the lockscreen is only available as
3929 // primary user option, profiles can only make them redacted. If a profile was
3930 // configured to not show lockscreen notifications, ensure that at the very
3931 // least these will be come hidden.
3932 if (mUserManager.isManagedProfile(userId)) {
3933 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3934 Setting showNotifications = secureSettings.getSettingLocked(
3935 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3936 // The default value is "1", check if user has turned it off.
3937 if ("0".equals(showNotifications.getValue())) {
3938 secureSettings.insertSettingLocked(
3939 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3940 null /* tag */, false /* makeDefault */,
3941 SettingsState.SYSTEM_PACKAGE_NAME);
3942 }
3943 // The setting is no longer valid for managed profiles, it should be
3944 // treated as if it was set to "1".
3945 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3946 }
3947 currentVersion = 160;
3948 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003949
3950 if (currentVersion == 160) {
3951 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003952 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003953 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3954 final SettingsState globalSettings = getGlobalSettingsLocked();
3955
3956 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003957 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3958 if (TextUtils.equals(null, oldValue)) {
3959 globalSettings.insertSettingLocked(
3960 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3961 Integer.toString(getContext().getResources().getInteger(
3962 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3963 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3964 }
3965
3966 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003967 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3968 if (TextUtils.equals(null, oldValue)) {
3969 globalSettings.insertSettingLocked(
3970 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3971 Integer.toString(getContext().getResources().getInteger(
3972 R.integer.def_sound_trigger_detection_service_op_timeout)),
3973 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3974 }
3975 currentVersion = 161;
3976 }
3977
Mike Digman55272862018-02-20 14:35:17 -08003978 if (currentVersion == 161) {
3979 // Version 161: Add a gesture for silencing phones
3980 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3981 final Setting currentSetting = secureSettings.getSettingLocked(
3982 Secure.VOLUME_HUSH_GESTURE);
3983 if (currentSetting.isNull()) {
3984 secureSettings.insertSettingLocked(
3985 Secure.VOLUME_HUSH_GESTURE,
3986 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3987 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3988 }
3989
3990 currentVersion = 162;
3991 }
3992
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003993 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003994 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003995 currentVersion = 163;
3996 }
3997
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003998 if (currentVersion == 163) {
3999 // Version 163: Update default value of
4000 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
4001 final SettingsState settings = getGlobalSettingsLocked();
4002 final Setting currentSetting = settings.getSettingLocked(
4003 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
4004 if (currentSetting.isDefaultFromSystem()) {
4005 settings.insertSettingLocked(
4006 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
4007 Integer.toString(getContext().getResources().getInteger(
4008 R.integer
4009 .def_max_sound_trigger_detection_service_ops_per_day)),
4010 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4011 }
4012
4013 currentVersion = 164;
4014 }
4015
Julia Reynolds76bfa602018-04-23 09:38:47 -04004016 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004017 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004018 currentVersion = 165;
4019 }
4020
Beverly301e92a2018-04-27 09:43:05 -04004021 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004022 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4023 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004024 currentVersion = 166;
4025 }
4026
Beverly38fcfd02018-05-18 17:33:40 -04004027 if (currentVersion == 166) {
4028 // Version 166: add default values for hush gesture used and manual ringer
4029 // toggle
4030 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4031 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4032 Secure.HUSH_GESTURE_USED);
4033 if (currentHushUsedSetting.isNull()) {
4034 secureSettings.insertSettingLocked(
4035 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4036 SettingsState.SYSTEM_PACKAGE_NAME);
4037 }
4038
4039 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4040 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4041 if (currentRingerToggleCountSetting.isNull()) {
4042 secureSettings.insertSettingLocked(
4043 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4044 SettingsState.SYSTEM_PACKAGE_NAME);
4045 }
4046 currentVersion = 167;
4047 }
4048
Beverly155c9d22018-05-23 18:03:23 -04004049 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004050 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4051 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004052 currentVersion = 168;
4053 }
4054
Michael Wright0e9eeee2018-05-26 00:31:20 +01004055 if (currentVersion == 168) {
4056 // Version 168: by default, vibrate for phone calls
4057 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4058 final Setting currentSetting = systemSettings.getSettingLocked(
4059 Settings.System.VIBRATE_WHEN_RINGING);
4060 if (currentSetting.isNull()) {
4061 systemSettings.insertSettingLocked(
4062 Settings.System.VIBRATE_WHEN_RINGING,
4063 getContext().getResources().getBoolean(
4064 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4065 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4066 }
4067 currentVersion = 169;
4068 }
4069
Nadav Barf9f115d2018-06-24 10:06:50 +03004070 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004071 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4072 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4073 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004074
Beverly91d0a632018-07-02 16:45:00 -04004075 final SettingsState globalSettings = getGlobalSettingsLocked();
4076 final Setting globalZenDuration = globalSettings.getSettingLocked(
4077 Global.ZEN_DURATION);
4078
4079 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4080 final Setting secureZenDuration = secureSettings.getSettingLocked(
4081 Secure.ZEN_DURATION);
4082
4083 // ZEN_DURATION
4084 if (!globalZenDuration.isNull()) {
4085 secureSettings.insertSettingLocked(
4086 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4087 SettingsState.SYSTEM_PACKAGE_NAME);
4088
4089 // set global zen duration setting to null since it's deprecated
4090 globalSettings.insertSettingLocked(
4091 Global.ZEN_DURATION, null, null, true,
4092 SettingsState.SYSTEM_PACKAGE_NAME);
4093 } else if (secureZenDuration.isNull()) {
4094 String defaultZenDuration = Integer.toString(getContext()
4095 .getResources().getInteger(R.integer.def_zen_duration));
4096 secureSettings.insertSettingLocked(
4097 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4098 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004099 }
Beverly91d0a632018-07-02 16:45:00 -04004100
4101 // SHOW_ZEN_SETTINGS_SUGGESTION
4102 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4103 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4104 if (currentShowZenSettingSuggestion.isNull()) {
4105 secureSettings.insertSettingLocked(
4106 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4107 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4108 }
4109
4110 // ZEN_SETTINGS_UPDATED
4111 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4112 Secure.ZEN_SETTINGS_UPDATED);
4113 if (currentUpdatedSetting.isNull()) {
4114 secureSettings.insertSettingLocked(
4115 Secure.ZEN_SETTINGS_UPDATED, "0",
4116 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4117 }
4118
4119 // ZEN_SETTINGS_SUGGESTION_VIEWED
4120 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4121 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4122 if (currentSettingSuggestionViewed.isNull()) {
4123 secureSettings.insertSettingLocked(
4124 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4125 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4126 }
4127
Nadav Barf9f115d2018-06-24 10:06:50 +03004128 currentVersion = 170;
4129 }
4130
Beverly91d0a632018-07-02 16:45:00 -04004131 if (currentVersion == 170) {
4132 // Version 170: Set the default value for Secure Settings:
4133 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4134
4135 final SettingsState globalSettings = getGlobalSettingsLocked();
4136 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4137
4138 // CHARGING_SOUNDS_ENABLED
4139 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4140 Global.CHARGING_SOUNDS_ENABLED);
4141 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4142 Secure.CHARGING_SOUNDS_ENABLED);
4143
4144 if (!globalChargingSoundEnabled.isNull()) {
Beverlyff9c5872019-01-02 15:44:00 -05004145 if (secureChargingSoundsEnabled.isNull()) {
4146 secureSettings.insertSettingLocked(
4147 Secure.CHARGING_SOUNDS_ENABLED,
4148 globalChargingSoundEnabled.getValue(), null, false,
4149 SettingsState.SYSTEM_PACKAGE_NAME);
4150 }
Beverly91d0a632018-07-02 16:45:00 -04004151
4152 // set global charging_sounds_enabled setting to null since it's deprecated
4153 globalSettings.insertSettingLocked(
4154 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4155 SettingsState.SYSTEM_PACKAGE_NAME);
4156 } else if (secureChargingSoundsEnabled.isNull()) {
4157 String defChargingSoundsEnabled = getContext().getResources()
4158 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4159 secureSettings.insertSettingLocked(
4160 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4161 true, SettingsState.SYSTEM_PACKAGE_NAME);
4162 }
4163
4164 // CHARGING_VIBRATION_ENABLED
4165 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4166 Secure.CHARGING_VIBRATION_ENABLED);
4167
4168 if (secureChargingVibrationEnabled.isNull()) {
4169 String defChargingVibrationEnabled = getContext().getResources()
4170 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4171 secureSettings.insertSettingLocked(
4172 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4173 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4174 }
4175
4176 currentVersion = 171;
4177 }
4178
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004179 if (currentVersion == 171) {
4180 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4181 // be muted.
4182 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4183 final Setting currentSetting = systemSettings.getSettingLocked(
4184 Settings.System.MUTE_STREAMS_AFFECTED);
4185 if (!currentSetting.isNull()) {
4186 try {
4187 int currentSettingIntegerValue = Integer.parseInt(
4188 currentSetting.getValue());
4189 if ((currentSettingIntegerValue
4190 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4191 systemSettings.insertSettingLocked(
4192 Settings.System.MUTE_STREAMS_AFFECTED,
4193 Integer.toString(
4194 currentSettingIntegerValue
4195 | (1 << AudioManager.STREAM_VOICE_CALL)),
4196 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4197 }
4198 } catch (NumberFormatException e) {
4199 // remove the setting in case it is not a valid integer
4200 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4201 + "setting, removing setting", e);
4202 systemSettings.deleteSettingLocked(
4203 Settings.System.MUTE_STREAMS_AFFECTED);
4204 }
4205
4206 }
4207 currentVersion = 172;
4208 }
4209
Felipe Lemeff355092017-04-03 12:55:02 -07004210 // vXXX: Add new settings above this point.
4211
Dan Sandler71f85e92016-07-20 13:46:05 -04004212 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004213 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004214 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004215 + currentVersion +
4216 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4217 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004218 if (DEBUG) {
4219 throw new RuntimeException("db upgrade error");
4220 }
4221 }
4222
Jeff Brown503cffc2015-03-26 18:08:51 -07004223 // Return the current version.
4224 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004225 }
4226 }
Svet Ganov13701552017-02-23 12:45:17 -08004227
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004228 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4229 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004230 List<String> names = settings.getSettingNamesLocked();
4231 final int nameCount = names.size();
4232 for (int i = 0; i < nameCount; i++) {
4233 String name = names.get(i);
4234 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004235
4236 // In the upgrade case we pretend the call is made from the app
4237 // that made the last change to the setting to properly determine
4238 // whether the call has been made by a system component.
4239 int callingUid = -1;
4240 try {
4241 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4242 } catch (RemoteException e) {
4243 /* ignore - handled below */
4244 }
4245 if (callingUid < 0) {
4246 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4247 continue;
4248 }
4249 try {
4250 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4251 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004252 if (systemSet) {
4253 settings.insertSettingLocked(name, setting.getValue(),
4254 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004255 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4256 // We had a bug where changes by non-system packages were marked
4257 // as system made and as a result set as the default. Therefore, if
4258 // the package changed the setting last is not a system one but the
4259 // setting is marked as its default coming from the system we clear
4260 // the default and clear the system set flag.
4261 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004262 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004263 } catch (IllegalStateException e) {
4264 // If the package goes over its quota during the upgrade, don't
4265 // crash but just log the error as the system does the upgrade.
4266 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4267
Svet Ganov13701552017-02-23 12:45:17 -08004268 }
4269 }
4270 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004271 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004272}