blob: 9e46ad6061eb6e1a1842d9924913ed49157e8e37 [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
Irina Dumitrescue3696872019-01-09 16:07:59 +000087import com.google.android.collect.Sets;
88
Svetoslav683914b2015-01-15 14:22:26 -080089import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080090import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080092import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080093import java.nio.ByteBuffer;
94import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000095import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080096import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070097import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080098import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000099import java.util.Collection;
Matt Pape6bfc62e2018-11-28 13:16:03 -0800100import java.util.HashMap;
Mark Rathjend891f012017-01-19 04:10:37 +0000101import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -0800102import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -0800103import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100104import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800105import java.util.Set;
106import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000107
Mark Rathjen7599f132017-01-23 14:15:54 -0800108import javax.crypto.Mac;
109import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700110
Svetoslav Ganove080da92016-12-21 17:10:35 -0800111
Svetoslav683914b2015-01-15 14:22:26 -0800112/**
113 * <p>
114 * This class is a content provider that publishes the system settings.
115 * It can be accessed via the content provider APIs or via custom call
116 * commands. The latter is a bit faster and is the preferred way to access
117 * the platform settings.
118 * </p>
119 * <p>
120 * There are three settings types, global (with signature level protection
121 * and shared across users), secure (with signature permission level
122 * protection and per user), and system (with dangerous permission level
123 * protection and per user). Global settings are stored under the device owner.
124 * Each of these settings is represented by a {@link
125 * com.android.providers.settings.SettingsState} object mapped to an integer
126 * key derived from the setting type in the most significant bits and user
127 * id in the least significant bits. Settings are synchronously loaded on
128 * instantiation of a SettingsState and asynchronously persisted on mutation.
129 * Settings are stored in the user specific system directory.
130 * </p>
131 * <p>
132 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
133 * and get a warning. Targeting higher API version prohibits this as the
134 * system settings are not a place for apps to save their state. When a package
135 * is removed the settings it added are deleted. Apps cannot delete system
136 * settings added by the platform. System settings values are validated to
137 * ensure the clients do not put bad values. Global and secure settings are
138 * changed only by trusted parties, therefore no validation is performed. Also
139 * there is a limit on the amount of app specific settings that can be added
140 * to prevent unlimited growth of the system process memory footprint.
141 * </p>
142 */
143@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700145 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700146
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700147 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800148
149 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700150
Christopher Tate06efb532012-08-24 15:29:27 -0700151 private static final String TABLE_SYSTEM = "system";
152 private static final String TABLE_SECURE = "secure";
153 private static final String TABLE_GLOBAL = "global";
Matt Pape6bfc62e2018-11-28 13:16:03 -0800154 private static final String TABLE_CONFIG = "config";
Svetoslav683914b2015-01-15 14:22:26 -0800155
156 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final String TABLE_FAVORITES = "favorites";
158 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800159 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
160 private static final String TABLE_BOOKMARKS = "bookmarks";
161 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Svetoslav683914b2015-01-15 14:22:26 -0800163 // The set of removed legacy tables.
164 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700165 static {
Svetoslav683914b2015-01-15 14:22:26 -0800166 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
167 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
168 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
169 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
170 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
171 }
Christopher Tate06efb532012-08-24 15:29:27 -0700172
Svetoslav683914b2015-01-15 14:22:26 -0800173 private static final int MUTATION_OPERATION_INSERT = 1;
174 private static final int MUTATION_OPERATION_DELETE = 2;
175 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800176 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400177
Svetoslav683914b2015-01-15 14:22:26 -0800178 private static final String[] ALL_COLUMNS = new String[] {
179 Settings.NameValueTable._ID,
180 Settings.NameValueTable.NAME,
181 Settings.NameValueTable.VALUE
182 };
183
Makoto Onuki53f0e022017-11-29 13:51:01 -0800184 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
185 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
186 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
187 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700188 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700189
190 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
191 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700192
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800193 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800194 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800195
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700196 // Overlay specified settings whitelisted for Instant Apps
197 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
198 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
199 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
200
201 static {
202 for (String name : Resources.getSystem().getStringArray(
203 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
204 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
205 }
206 for (String name : Resources.getSystem().getStringArray(
207 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
208 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
209 }
210 for (String name : Resources.getSystem().getStringArray(
211 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
212 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
213 }
214 }
215
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800216 // Changes to these global settings are synchronously persisted
217 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
218 static {
219 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
220 }
221
222 // Changes to these secure settings are synchronously persisted
223 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
224 static {
225 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
226 }
227
Svetoslav683914b2015-01-15 14:22:26 -0800228 // Per user secure settings that moved to the for all users global settings.
229 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
230 static {
231 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700232 }
233
Svetoslav683914b2015-01-15 14:22:26 -0800234 // Per user system settings that moved to the for all users global settings.
235 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
236 static {
237 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700238 }
239
Svetoslav683914b2015-01-15 14:22:26 -0800240 // Per user system settings that moved to the per user secure settings.
241 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
242 static {
243 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700244 }
245
Svetoslav683914b2015-01-15 14:22:26 -0800246 // Per all users global settings that moved to the per user secure settings.
247 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
248 static {
249 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700250 }
251
Svetoslav683914b2015-01-15 14:22:26 -0800252 // Per user secure settings that are cloned for the managed profiles of the user.
253 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
254 static {
255 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700256 }
257
Svetoslav683914b2015-01-15 14:22:26 -0800258 // Per user system settings that are cloned for the managed profiles of the user.
259 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
260 static {
261 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400262 }
263
Andre Lago3fa139c2016-08-04 13:53:44 +0100264 // Per user system settings that are cloned from the profile's parent when a dependency
265 // in {@link Settings.Secure} is set to "1".
266 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
267 static {
268 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
269 }
270
Svetoslav683914b2015-01-15 14:22:26 -0800271 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700272
Svetoslav683914b2015-01-15 14:22:26 -0800273 @GuardedBy("mLock")
274 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700275
Svet Ganova8f90262016-05-10 08:44:48 -0700276 @GuardedBy("mLock")
277 private HandlerThread mHandlerThread;
278
Makoto Onuki73360ab2017-03-17 11:50:13 -0700279 @GuardedBy("mLock")
280 private Handler mHandler;
281
Svetoslav7ec28e82015-05-20 17:01:10 -0700282 // We have to call in the user manager with no lock held,
283 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800284
yuemingw1d13eae2018-01-30 17:27:54 +0000285 private UserManagerInternal mUserManagerInternal;
286
Svetoslav7ec28e82015-05-20 17:01:10 -0700287 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700288 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700289
Svet Ganov53a441c2016-04-19 19:38:00 -0700290 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800291 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700292 }
293
294 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800295 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700296 }
297
298 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800299 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700300 }
301
302 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800303 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 }
305
306 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800307 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700308 }
309
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 @Override
311 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800312 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000313
314 // fail to boot if there're any backed up settings that don't have a non-null validator
315 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000316 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000317 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000318
Svetoslav683914b2015-01-15 14:22:26 -0800319 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700320 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000321 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700322 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700323 mHandlerThread = new HandlerThread(LOG_TAG,
324 Process.THREAD_PRIORITY_BACKGROUND);
325 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700326 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800327 mSettingsRegistry = new SettingsRegistry();
328 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700329 mHandler.post(() -> {
330 registerBroadcastReceivers();
331 startWatchingUserRestrictionChanges();
332 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700333 ServiceManager.addService("settings", new SettingsService(this));
Matt Papeabb67892018-12-07 09:13:26 -0800334 ServiceManager.addService("device_config", new DeviceConfigService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700335 return true;
336 }
337
Michal Karpinski2c37b082018-01-18 16:14:27 +0000338 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000339 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
340 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000341
342 failToBootIfOffendersPresent(offenders, "Settings.System");
343 }
344
345 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000346 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
347 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000348
349 failToBootIfOffendersPresent(offenders, "Settings.Global");
350 }
351
Michal Karpinski964943a2018-01-19 16:28:26 +0000352 private void ensureAllBackedUpSecureSettingsHaveValidators() {
353 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
354 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
355
356 failToBootIfOffendersPresent(offenders, "Settings.Secure");
357 }
358
Michal Karpinski5db1e432018-01-18 20:10:24 +0000359 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
360 if (offenders.length() > 0) {
361 throw new RuntimeException("All " + settingsType + " settings that are backed up"
362 + " have to have a non-null validator, but those don't: " + offenders);
363 }
364 }
365
366 private String getOffenders(String[] settingsToBackup, Map<String,
367 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000368 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000369 for (String setting : settingsToBackup) {
370 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000371 offenders.append(setting).append(" ");
372 }
373 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000374 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000375 }
376
Michal Karpinski964943a2018-01-19 16:28:26 +0000377 private final String[] concat(String[] first, String[] second) {
378 if (second == null || second.length == 0) {
379 return first;
380 }
381 final int firstLen = first.length;
382 final int secondLen = second.length;
383 String[] both = new String[firstLen + secondLen];
384 System.arraycopy(first, 0, both, 0, firstLen);
385 System.arraycopy(second, 0, both, firstLen, secondLen);
386 return both;
387 }
388
Svetoslav683914b2015-01-15 14:22:26 -0800389 @Override
390 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700391 final int requestingUserId = getRequestingUserId(args);
392 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700393 case Settings.CALL_METHOD_GET_CONFIG: {
394 Setting setting = getConfigSetting(name);
395 return packageValueForCallResult(setting, isTrackingGeneration(args));
396 }
397
Svetoslav7ec28e82015-05-20 17:01:10 -0700398 case Settings.CALL_METHOD_GET_GLOBAL: {
399 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700400 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800401 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700402
403 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800404 Setting setting = getSecureSetting(name, requestingUserId,
405 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700406 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700407 }
408
409 case Settings.CALL_METHOD_GET_SYSTEM: {
410 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700411 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700412 }
413
Matt Pape1b31a332018-10-17 09:58:28 -0700414 case Settings.CALL_METHOD_PUT_CONFIG: {
415 String value = getSettingValue(args);
Matt Pape1b31a332018-10-17 09:58:28 -0700416 final boolean makeDefault = getSettingMakeDefault(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800417 insertConfigSetting(name, value, makeDefault);
Matt Pape1b31a332018-10-17 09:58:28 -0700418 break;
419 }
420
Svetoslav7ec28e82015-05-20 17:01:10 -0700421 case Settings.CALL_METHOD_PUT_GLOBAL: {
422 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800423 String tag = getSettingTag(args);
424 final boolean makeDefault = getSettingMakeDefault(args);
425 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700426 break;
427 }
428
429 case Settings.CALL_METHOD_PUT_SECURE: {
430 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800431 String tag = getSettingTag(args);
432 final boolean makeDefault = getSettingMakeDefault(args);
433 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700434 break;
435 }
436
437 case Settings.CALL_METHOD_PUT_SYSTEM: {
438 String value = getSettingValue(args);
439 insertSystemSetting(name, value, requestingUserId);
440 break;
441 }
442
Matt Pape1b31a332018-10-17 09:58:28 -0700443 case Settings.CALL_METHOD_RESET_CONFIG: {
444 final int mode = getResetModeEnforcingPermission(args);
Matt Pape6bfc62e2018-11-28 13:16:03 -0800445 String prefix = getSettingPrefix(args);
Matt Papec1323dc2018-12-11 12:32:42 -0800446 resetConfigSetting(mode, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -0700447 break;
448 }
449
Svetoslav Ganove080da92016-12-21 17:10:35 -0800450 case Settings.CALL_METHOD_RESET_GLOBAL: {
451 final int mode = getResetModeEnforcingPermission(args);
452 String tag = getSettingTag(args);
453 resetGlobalSetting(requestingUserId, mode, tag);
454 break;
455 }
456
457 case Settings.CALL_METHOD_RESET_SECURE: {
458 final int mode = getResetModeEnforcingPermission(args);
459 String tag = getSettingTag(args);
460 resetSecureSetting(requestingUserId, mode, tag);
461 break;
462 }
463
Matt Pape6bfc62e2018-11-28 13:16:03 -0800464 case Settings.CALL_METHOD_DELETE_CONFIG: {
Matt Papec1323dc2018-12-11 12:32:42 -0800465 int rows = deleteConfigSetting(name) ? 1 : 0;
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800466 Bundle result = new Bundle();
467 result.putInt(RESULT_ROWS_DELETED, rows);
468 return result;
469 }
470
471 case Settings.CALL_METHOD_DELETE_GLOBAL: {
472 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
473 Bundle result = new Bundle();
474 result.putInt(RESULT_ROWS_DELETED, rows);
475 return result;
476 }
477
Matt Pape6bfc62e2018-11-28 13:16:03 -0800478 case Settings.CALL_METHOD_DELETE_SECURE: {
479 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
480 Bundle result = new Bundle();
481 result.putInt(RESULT_ROWS_DELETED, rows);
482 return result;
483 }
484
485 case Settings.CALL_METHOD_DELETE_SYSTEM: {
486 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
487 Bundle result = new Bundle();
488 result.putInt(RESULT_ROWS_DELETED, rows);
489 return result;
490 }
491
492 case Settings.CALL_METHOD_LIST_CONFIG: {
493 String prefix = getSettingPrefix(args);
494 Bundle result = new Bundle();
495 result.putSerializable(
496 Settings.NameValueTable.VALUE, (HashMap) getAllConfigFlags(prefix));
497 return result;
498 }
499
500 case Settings.CALL_METHOD_LIST_GLOBAL: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800501 Bundle result = new Bundle();
502 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800503 buildSettingsList(getAllGlobalSettings(null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800504 return result;
505 }
506
507 case Settings.CALL_METHOD_LIST_SECURE: {
508 Bundle result = new Bundle();
509 result.putStringArrayList(RESULT_SETTINGS_LIST,
510 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
511 return result;
512 }
513
Matt Pape6bfc62e2018-11-28 13:16:03 -0800514 case Settings.CALL_METHOD_LIST_SYSTEM: {
Nicholas Sauer72500532018-11-21 10:30:58 -0800515 Bundle result = new Bundle();
516 result.putStringArrayList(RESULT_SETTINGS_LIST,
Matt Pape6bfc62e2018-11-28 13:16:03 -0800517 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
Nicholas Sauer72500532018-11-21 10:30:58 -0800518 return result;
519 }
520
Svetoslav7ec28e82015-05-20 17:01:10 -0700521 default: {
522 Slog.w(LOG_TAG, "call() with invalid method: " + method);
523 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700524 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700525
Christopher Tate06efb532012-08-24 15:29:27 -0700526 return null;
527 }
528
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800529 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800530 public String getType(Uri uri) {
531 Arguments args = new Arguments(uri, null, null, true);
532 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700533 return "vnd.android.cursor.dir/" + args.table;
534 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700535 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536 }
537 }
538
539 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800540 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
541 String order) {
542 if (DEBUG) {
543 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544 }
545
Svetoslav683914b2015-01-15 14:22:26 -0800546 Arguments args = new Arguments(uri, where, whereArgs, true);
547 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700548
Svetoslav683914b2015-01-15 14:22:26 -0800549 // If a legacy table that is gone, done.
550 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
551 return new MatrixCursor(normalizedProjection, 0);
552 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700553
Svetoslav7ec28e82015-05-20 17:01:10 -0700554 switch (args.table) {
555 case TABLE_GLOBAL: {
556 if (args.name != null) {
557 Setting setting = getGlobalSetting(args.name);
558 return packageSettingForQuery(setting, normalizedProjection);
559 } else {
560 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700561 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700562 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700563
Svetoslav7ec28e82015-05-20 17:01:10 -0700564 case TABLE_SECURE: {
565 final int userId = UserHandle.getCallingUserId();
566 if (args.name != null) {
567 Setting setting = getSecureSetting(args.name, userId);
568 return packageSettingForQuery(setting, normalizedProjection);
569 } else {
570 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800571 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 }
Svetoslav683914b2015-01-15 14:22:26 -0800573
Svetoslav7ec28e82015-05-20 17:01:10 -0700574 case TABLE_SYSTEM: {
575 final int userId = UserHandle.getCallingUserId();
576 if (args.name != null) {
577 Setting setting = getSystemSetting(args.name, userId);
578 return packageSettingForQuery(setting, normalizedProjection);
579 } else {
580 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800581 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700582 }
Svetoslav683914b2015-01-15 14:22:26 -0800583
Svetoslav7ec28e82015-05-20 17:01:10 -0700584 default: {
585 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700586 }
587 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700588 }
589
Nicholas Sauer72500532018-11-21 10:30:58 -0800590 private ArrayList<String> buildSettingsList(Cursor cursor) {
591 final ArrayList<String> lines = new ArrayList<String>();
592 try {
593 while (cursor != null && cursor.moveToNext()) {
594 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
595 }
596 } finally {
597 if (cursor != null) {
598 cursor.close();
599 }
600 }
601 return lines;
602 }
603
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700604 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800605 public Uri insert(Uri uri, ContentValues values) {
606 if (DEBUG) {
607 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700608 }
609
Svetoslav683914b2015-01-15 14:22:26 -0800610 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700611
Svetoslav683914b2015-01-15 14:22:26 -0800612 // If a legacy table that is gone, done.
613 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 return null;
615 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700616
Svetoslav683914b2015-01-15 14:22:26 -0800617 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700618 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800619 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700620 }
621
Svetoslav683914b2015-01-15 14:22:26 -0800622 String value = values.getAsString(Settings.Secure.VALUE);
623
Svetoslav7ec28e82015-05-20 17:01:10 -0700624 switch (table) {
625 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800626 if (insertGlobalSetting(name, value, null, false,
627 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700628 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700629 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700630 } break;
631
632 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800633 if (insertSecureSetting(name, value, null, false,
634 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700635 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
636 }
637 } break;
638
639 case TABLE_SYSTEM: {
640 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
641 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
642 }
643 } break;
644
645 default: {
646 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700647 }
648 }
649
Svetoslav683914b2015-01-15 14:22:26 -0800650 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651 }
652
653 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800654 public int bulkInsert(Uri uri, ContentValues[] allValues) {
655 if (DEBUG) {
656 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700658
Svetoslav683914b2015-01-15 14:22:26 -0800659 int insertionCount = 0;
660 final int valuesCount = allValues.length;
661 for (int i = 0; i < valuesCount; i++) {
662 ContentValues values = allValues[i];
663 if (insert(uri, values) != null) {
664 insertionCount++;
665 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700666 }
Svetoslav683914b2015-01-15 14:22:26 -0800667
668 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700669 }
670
671 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800672 public int delete(Uri uri, String where, String[] whereArgs) {
673 if (DEBUG) {
674 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700676
Svetoslav683914b2015-01-15 14:22:26 -0800677 Arguments args = new Arguments(uri, where, whereArgs, false);
678
679 // If a legacy table that is gone, done.
680 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
681 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700682 }
Svetoslav683914b2015-01-15 14:22:26 -0800683
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700684 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800685 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700686 }
Svetoslav683914b2015-01-15 14:22:26 -0800687
Svetoslav7ec28e82015-05-20 17:01:10 -0700688 switch (args.table) {
689 case TABLE_GLOBAL: {
690 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700691 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700692 }
Svetoslav683914b2015-01-15 14:22:26 -0800693
Svetoslav7ec28e82015-05-20 17:01:10 -0700694 case TABLE_SECURE: {
695 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700696 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700697 }
Svetoslav683914b2015-01-15 14:22:26 -0800698
Svetoslav7ec28e82015-05-20 17:01:10 -0700699 case TABLE_SYSTEM: {
700 final int userId = UserHandle.getCallingUserId();
701 return deleteSystemSetting(args.name, userId) ? 1 : 0;
702 }
703
704 default: {
705 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800706 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700707 }
Svetoslav683914b2015-01-15 14:22:26 -0800708 }
709
710 @Override
711 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
712 if (DEBUG) {
713 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700714 }
Svetoslav683914b2015-01-15 14:22:26 -0800715
716 Arguments args = new Arguments(uri, where, whereArgs, false);
717
718 // If a legacy table that is gone, done.
719 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
720 return 0;
721 }
722
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700723 String name = values.getAsString(Settings.Secure.NAME);
724 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800725 return 0;
726 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700727 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800728
Svetoslav7ec28e82015-05-20 17:01:10 -0700729 switch (args.table) {
730 case TABLE_GLOBAL: {
731 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800732 return updateGlobalSetting(args.name, value, null, false,
733 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700734 }
Svetoslav683914b2015-01-15 14:22:26 -0800735
Svetoslav7ec28e82015-05-20 17:01:10 -0700736 case TABLE_SECURE: {
737 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800738 return updateSecureSetting(args.name, value, null, false,
739 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 }
Svetoslav683914b2015-01-15 14:22:26 -0800741
Svetoslav7ec28e82015-05-20 17:01:10 -0700742 case TABLE_SYSTEM: {
743 final int userId = UserHandle.getCallingUserId();
744 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
745 }
Svetoslav683914b2015-01-15 14:22:26 -0800746
Svetoslav7ec28e82015-05-20 17:01:10 -0700747 default: {
748 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800749 }
750 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700751 }
752
753 @Override
754 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100755 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
756 if (userId != UserHandle.getCallingUserId()) {
757 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
758 "Access files from the settings of another user");
759 }
760 uri = ContentProvider.getUriWithoutUserId(uri);
761
Andre Lago3fa139c2016-08-04 13:53:44 +0100762 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700763 final String cacheName;
764 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100765 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700766 cacheName = Settings.System.RINGTONE_CACHE;
767 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100768 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700769 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
770 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100771 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700772 cacheName = Settings.System.ALARM_ALERT_CACHE;
773 } else {
774 throw new FileNotFoundException("Direct file access no longer supported; "
775 + "ringtone playback is available through android.media.Ringtone");
776 }
777
Andre Lago3fa139c2016-08-04 13:53:44 +0100778 int actualCacheOwner;
779 // Redirect cache to parent if ringtone setting is owned by profile parent
780 synchronized (mLock) {
781 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
782 cacheRingtoneSetting);
783 }
784 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700785 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
786 }
787
788 private File getRingtoneCacheDir(int userId) {
789 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
790 cacheDir.mkdir();
791 SELinux.restorecon(cacheDir);
792 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700793 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800794
Eugene Suslad72c3972016-12-27 15:49:30 -0800795 /**
796 * Dump all settings as a proto buf.
797 *
798 * @param fd The file to dump to
799 */
800 void dumpProto(@NonNull FileDescriptor fd) {
801 ProtoOutputStream proto = new ProtoOutputStream(fd);
802
803 synchronized (mLock) {
804 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800805 }
806
807 proto.flush();
808 }
809
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700810 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800811 synchronized (mLock) {
812 final long identity = Binder.clearCallingIdentity();
813 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700814 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800815 final int userCount = users.size();
816 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700817 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800818 }
819 } finally {
820 Binder.restoreCallingIdentity(identity);
821 }
822 }
823 }
824
Andreas Gampeb58893072018-09-05 16:52:31 -0700825 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700826 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700827 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700828 pw.println("CONFIG SETTINGS (user " + userId + ")");
829 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
830 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
831 if (configSettings != null) {
832 dumpSettingsLocked(configSettings, pw);
833 pw.println();
834 configSettings.dumpHistoricalOperations(pw);
835 }
836
Svetoslavb505ccc2015-02-17 12:41:04 -0800837 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700838 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
839 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700840 if (globalSettings != null) {
841 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800842 pw.println();
843 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700844 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800845 }
846
847 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700848 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
849 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700850 if (secureSettings != null) {
851 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800852 pw.println();
853 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700854 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700855
Svetoslavb505ccc2015-02-17 12:41:04 -0800856 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700857 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
858 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700859 if (systemSettings != null) {
860 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800861 pw.println();
862 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700863 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800864 }
865
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700866 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
867 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800868
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700869 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800870
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700871 for (int i = 0; i < nameCount; i++) {
872 String name = names.get(i);
873 Setting setting = settingsState.getSettingLocked(name);
874 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
875 pw.print(" name:"); pw.print(toDumpString(name));
876 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800877 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700878 }
879 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800880 if (setting.getDefaultValue() != null) {
881 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800882 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800883 }
884 if (setting.getTag() != null) {
885 pw.print(" tag:"); pw.print(setting.getTag());
886 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800887 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700888 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800889 }
890
Svetoslav7e0683b2015-08-03 16:02:52 -0700891 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700892 if (s != null) {
893 return s;
894 }
895 return "{null}";
896 }
897
Svetoslav683914b2015-01-15 14:22:26 -0800898 private void registerBroadcastReceivers() {
899 IntentFilter userFilter = new IntentFilter();
900 userFilter.addAction(Intent.ACTION_USER_REMOVED);
901 userFilter.addAction(Intent.ACTION_USER_STOPPED);
902
903 getContext().registerReceiver(new BroadcastReceiver() {
904 @Override
905 public void onReceive(Context context, Intent intent) {
906 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700907 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800908
909 switch (intent.getAction()) {
910 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700911 synchronized (mLock) {
912 mSettingsRegistry.removeUserStateLocked(userId, true);
913 }
Svetoslav683914b2015-01-15 14:22:26 -0800914 } break;
915
916 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700917 synchronized (mLock) {
918 mSettingsRegistry.removeUserStateLocked(userId, false);
919 }
Svetoslav683914b2015-01-15 14:22:26 -0800920 } break;
921 }
922 }
923 }, userFilter);
924
925 PackageMonitor monitor = new PackageMonitor() {
926 @Override
927 public void onPackageRemoved(String packageName, int uid) {
928 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100929 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800930 UserHandle.getUserId(uid));
931 }
932 }
Mark Rathjend891f012017-01-19 04:10:37 +0000933
934 @Override
935 public void onUidRemoved(int uid) {
936 synchronized (mLock) {
937 mSettingsRegistry.onUidRemovedLocked(uid);
938 }
939 }
Zimuzoc56192c2018-07-25 10:40:01 +0100940
941 @Override
942 public void onPackageDataCleared(String packageName, int uid) {
943 synchronized (mLock) {
944 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
945 UserHandle.getUserId(uid));
946 }
947 }
Svetoslav683914b2015-01-15 14:22:26 -0800948 };
949
950 // package changes
951 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
952 UserHandle.ALL, true);
953 }
954
Svet Ganov53a441c2016-04-19 19:38:00 -0700955 private void startWatchingUserRestrictionChanges() {
956 // TODO: The current design of settings looking different based on user restrictions
957 // should be reworked to keep them separate and system code should check the setting
958 // first followed by checking the user restriction before performing an operation.
959 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
960 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
961 Bundle prevRestrictions) -> {
Irina Dumitrescue3696872019-01-09 16:07:59 +0000962 Set<String> changedRestrictions = getRestrictionDiff(prevRestrictions, newRestrictions);
Svet Ganov53a441c2016-04-19 19:38:00 -0700963 // We are changing the settings affected by restrictions to their current
964 // value with a forced update to ensure that all cross profile dependencies
965 // are taken into account. Also make sure the settings update to.. the same
966 // value passes the security checks, so clear binder calling id.
Irina Dumitrescue3696872019-01-09 16:07:59 +0000967 if (changedRestrictions.contains(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700968 final long identity = Binder.clearCallingIdentity();
969 try {
970 synchronized (mLock) {
971 Setting setting = getSecureSetting(
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -0800972 Settings.Secure.LOCATION_MODE, userId);
973 updateSecureSetting(Settings.Secure.LOCATION_MODE,
974 setting != null ? setting.getValue() : null, null,
975 true, userId, true);
976 setting = getSecureSetting(
Svet Ganov53a441c2016-04-19 19:38:00 -0700977 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
978 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800979 setting != null ? setting.getValue() : null, null,
980 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700981 }
982 } finally {
983 Binder.restoreCallingIdentity(identity);
984 }
985 }
Irina Dumitrescue3696872019-01-09 16:07:59 +0000986 if (changedRestrictions.contains(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
987 || changedRestrictions.contains(
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100988 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700989 final long identity = Binder.clearCallingIdentity();
990 try {
991 synchronized (mLock) {
992 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800993 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700994 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800995 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700996 }
997 } finally {
998 Binder.restoreCallingIdentity(identity);
999 }
1000 }
Irina Dumitrescue3696872019-01-09 16:07:59 +00001001 if (changedRestrictions.contains(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001002 final long identity = Binder.clearCallingIdentity();
1003 try {
1004 synchronized (mLock) {
1005 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001006 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001007 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001008 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001009 }
1010 } finally {
1011 Binder.restoreCallingIdentity(identity);
1012 }
1013 }
Irina Dumitrescue3696872019-01-09 16:07:59 +00001014 if (changedRestrictions.contains(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001015 final long identity = Binder.clearCallingIdentity();
1016 try {
1017 synchronized (mLock) {
1018 Setting enable = getGlobalSetting(
1019 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001020 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001021 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001022 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001023 Setting include = getGlobalSetting(
1024 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001025 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001026 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001027 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001028 }
1029 } finally {
1030 Binder.restoreCallingIdentity(identity);
1031 }
1032 }
Irina Dumitrescue3696872019-01-09 16:07:59 +00001033 if (changedRestrictions.contains(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001034 final long identity = Binder.clearCallingIdentity();
1035 try {
1036 synchronized (mLock) {
1037 Setting setting = getGlobalSetting(
1038 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001039 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001040 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001041 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001042 }
1043 } finally {
1044 Binder.restoreCallingIdentity(identity);
1045 }
1046 }
1047 });
1048 }
1049
Irina Dumitrescue3696872019-01-09 16:07:59 +00001050 private static Set<String> getRestrictionDiff(Bundle prevRestrictions, Bundle newRestrictions) {
1051 Set<String> restrictionNames = Sets.newArraySet();
1052 restrictionNames.addAll(prevRestrictions.keySet());
1053 restrictionNames.addAll(newRestrictions.keySet());
1054 Set<String> diff = Sets.newArraySet();
1055 for (String restrictionName : restrictionNames) {
1056 if (prevRestrictions.getBoolean(restrictionName) != newRestrictions.getBoolean(
1057 restrictionName)) {
1058 diff.add(restrictionName);
1059 }
1060 }
1061 return diff;
1062 }
1063
Matt Pape1b31a332018-10-17 09:58:28 -07001064 private Setting getConfigSetting(String name) {
1065 if (DEBUG) {
1066 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1067 }
1068
1069 // TODO(b/117663715): Ensure the caller can access the setting.
Stanislav Zholnin596437f2018-12-28 15:34:23 +00001070 // enforceReadPermission(READ_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001071
1072 // Get the value.
1073 synchronized (mLock) {
1074 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1075 UserHandle.USER_SYSTEM, name);
1076 }
1077 }
1078
Matt Papec1323dc2018-12-11 12:32:42 -08001079 private boolean insertConfigSetting(String name, String value, boolean makeDefault) {
Matt Pape1b31a332018-10-17 09:58:28 -07001080 if (DEBUG) {
1081 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
Matt Papec1323dc2018-12-11 12:32:42 -08001082 + makeDefault + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001083 }
Matt Papec1323dc2018-12-11 12:32:42 -08001084 return mutateConfigSetting(name, value, null, makeDefault,
1085 MUTATION_OPERATION_INSERT, 0);
Matt Pape1b31a332018-10-17 09:58:28 -07001086 }
1087
Matt Papec1323dc2018-12-11 12:32:42 -08001088 private boolean deleteConfigSetting(String name) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08001089 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001090 Slog.v(LOG_TAG, "deleteConfigSetting(" + name + ")");
Matt Pape6bfc62e2018-11-28 13:16:03 -08001091 }
Matt Papec1323dc2018-12-11 12:32:42 -08001092 return mutateConfigSetting(name, null, null, false,
1093 MUTATION_OPERATION_DELETE, 0);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001094 }
1095
Matt Papec1323dc2018-12-11 12:32:42 -08001096 private void resetConfigSetting(int mode, String prefix) {
Matt Pape1b31a332018-10-17 09:58:28 -07001097 if (DEBUG) {
Matt Papec1323dc2018-12-11 12:32:42 -08001098 Slog.v(LOG_TAG, "resetConfigSetting(" + mode + ", " + prefix + ")");
Matt Pape1b31a332018-10-17 09:58:28 -07001099 }
Matt Papec1323dc2018-12-11 12:32:42 -08001100 mutateConfigSetting(null, null, prefix, false,
1101 MUTATION_OPERATION_RESET, mode);
Matt Pape1b31a332018-10-17 09:58:28 -07001102 }
1103
Matt Pape6bfc62e2018-11-28 13:16:03 -08001104 private boolean mutateConfigSetting(String name, String value, String prefix,
Matt Papec1323dc2018-12-11 12:32:42 -08001105 boolean makeDefault, int operation, int mode) {
Stanislav Zholnin5a25a842019-03-13 14:43:26 +00001106 enforceWritePermission(Manifest.permission.WRITE_DEVICE_CONFIG);
Matt Pape1b31a332018-10-17 09:58:28 -07001107
Matt Pape1b31a332018-10-17 09:58:28 -07001108 // Perform the mutation.
1109 synchronized (mLock) {
1110 switch (operation) {
1111 case MUTATION_OPERATION_INSERT: {
1112 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001113 UserHandle.USER_SYSTEM, name, value, null, makeDefault, true,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001114 resolveCallingPackage(), false, null);
Matt Pape1b31a332018-10-17 09:58:28 -07001115 }
1116
Matt Pape6bfc62e2018-11-28 13:16:03 -08001117 case MUTATION_OPERATION_DELETE: {
1118 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_CONFIG,
Matt Papec1323dc2018-12-11 12:32:42 -08001119 UserHandle.USER_SYSTEM, name, false, null);
Matt Pape6bfc62e2018-11-28 13:16:03 -08001120 }
1121
Matt Pape1b31a332018-10-17 09:58:28 -07001122 case MUTATION_OPERATION_RESET: {
1123 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
Matt Pape7b1c6cd2019-01-04 08:10:41 -08001124 UserHandle.USER_SYSTEM, resolveCallingPackage(), mode, null, prefix);
Matt Pape1b31a332018-10-17 09:58:28 -07001125 } return true;
1126 }
1127 }
1128
1129 return false;
1130 }
1131
Matt Pape6bfc62e2018-11-28 13:16:03 -08001132 private Map<String, String> getAllConfigFlags(@Nullable String prefix) {
1133 if (DEBUG) {
1134 Slog.v(LOG_TAG, "getAllConfigFlags() for " + prefix);
1135 }
1136
1137 synchronized (mLock) {
1138 // Get the settings.
1139 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1140 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
1141
1142 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_CONFIG,
1143 UserHandle.USER_SYSTEM);
1144
1145 final int nameCount = names.size();
1146 Map<String, String> flagsToValues = new HashMap<>(names.size());
1147
1148 for (int i = 0; i < nameCount; i++) {
1149 String name = names.get(i);
1150 Setting setting = settingsState.getSettingLocked(name);
1151 if (prefix == null || setting.getName().startsWith(prefix)) {
1152 flagsToValues.put(setting.getName(), setting.getValue());
1153 }
1154 }
1155
1156 return flagsToValues;
1157 }
1158 }
1159
Svetoslav7ec28e82015-05-20 17:01:10 -07001160 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001161 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001162 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001163 }
1164
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 synchronized (mLock) {
1166 // Get the settings.
1167 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001168 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001169
Chad Brubaker97bccee2017-01-05 15:51:41 -08001170 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1171 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001172
Svetoslav7ec28e82015-05-20 17:01:10 -07001173 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001174
Svetoslav7ec28e82015-05-20 17:01:10 -07001175 String[] normalizedProjection = normalizeProjection(projection);
1176 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001177
Svetoslav7ec28e82015-05-20 17:01:10 -07001178 // Anyone can get the global settings, so no security checks.
1179 for (int i = 0; i < nameCount; i++) {
1180 String name = names.get(i);
1181 Setting setting = settingsState.getSettingLocked(name);
1182 appendSettingToCursor(result, setting);
1183 }
1184
1185 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001186 }
Svetoslav683914b2015-01-15 14:22:26 -08001187 }
1188
Svetoslav7ec28e82015-05-20 17:01:10 -07001189 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001190 if (DEBUG) {
1191 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1192 }
1193
Chad Brubakera6830e72017-04-28 17:34:36 -07001194 // Ensure the caller can access the setting.
1195 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1196
Svetoslav683914b2015-01-15 14:22:26 -08001197 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001198 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001199 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001200 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001201 }
Svetoslav683914b2015-01-15 14:22:26 -08001202 }
1203
Svetoslav Ganove080da92016-12-21 17:10:35 -08001204 private boolean updateGlobalSetting(String name, String value, String tag,
1205 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001206 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001207 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1208 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1209 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001210 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001211 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1212 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001213 }
1214
Svetoslav Ganove080da92016-12-21 17:10:35 -08001215 private boolean insertGlobalSetting(String name, String value, String tag,
1216 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001217 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001218 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1219 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1220 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001221 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001222 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1223 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001224 }
1225
Svet Ganov53a441c2016-04-19 19:38:00 -07001226 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001227 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001228 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1229 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001230 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001231 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1232 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001233 }
1234
Svetoslav Ganove080da92016-12-21 17:10:35 -08001235 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1236 if (DEBUG) {
1237 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1238 + mode + ", " + tag + ")");
1239 }
1240 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1241 MUTATION_OPERATION_RESET, false, mode);
1242 }
1243
1244 private boolean mutateGlobalSetting(String name, String value, String tag,
1245 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1246 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001247 // Make sure the caller can change the settings - treated as secure.
1248 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1249
Svetoslav683914b2015-01-15 14:22:26 -08001250 // Resolve the userId on whose behalf the call is made.
1251 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1252
Makoto Onuki28da2e32015-11-20 11:30:44 -08001253 // If this is a setting that is currently restricted for this user, do not allow
1254 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001255 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1256 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001257 return false;
1258 }
1259
1260 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001261 synchronized (mLock) {
1262 switch (operation) {
1263 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001264 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1265 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001266 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001267 }
Svetoslav683914b2015-01-15 14:22:26 -08001268
Svetoslav7ec28e82015-05-20 17:01:10 -07001269 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001270 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001271 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001272 }
Svetoslav683914b2015-01-15 14:22:26 -08001273
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001275 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1276 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001277 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001278 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001279
1280 case MUTATION_OPERATION_RESET: {
1281 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1282 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1283 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001284 }
1285 }
1286
1287 return false;
1288 }
1289
Christopher Tateb218e762017-04-05 16:34:07 -07001290 private PackageInfo getCallingPackageInfo(int userId) {
1291 try {
1292 return mPackageManager.getPackageInfo(getCallingPackage(),
1293 PackageManager.GET_SIGNATURES, userId);
1294 } catch (RemoteException e) {
1295 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1296 }
1297 }
1298
Svetoslav7ec28e82015-05-20 17:01:10 -07001299 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001300 if (DEBUG) {
1301 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1302 }
1303
1304 // Resolve the userId on whose behalf the call is made.
1305 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1306
Christopher Tateb218e762017-04-05 16:34:07 -07001307 // The relevant "calling package" userId will be the owning userId for some
1308 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1309 // up front who the effective "new SSAID" user ID for that settings name will be.
1310 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1311 Settings.Secure.ANDROID_ID);
1312 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1313
Svetoslav7ec28e82015-05-20 17:01:10 -07001314 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001315 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001316
Svetoslav7ec28e82015-05-20 17:01:10 -07001317 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001318
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 String[] normalizedProjection = normalizeProjection(projection);
1320 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001321
Svetoslav7ec28e82015-05-20 17:01:10 -07001322 for (int i = 0; i < nameCount; i++) {
1323 String name = names.get(i);
1324 // Determine the owning user as some profile settings are cloned from the parent.
1325 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1326 name);
Svetoslav683914b2015-01-15 14:22:26 -08001327
Alex Klyubin1991f572017-03-03 14:08:36 -08001328 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1329 // This caller is not permitted to access this setting. Pretend the setting
1330 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001331 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001332 }
Svetoslav683914b2015-01-15 14:22:26 -08001333
Mark Rathjen7599f132017-01-23 14:15:54 -08001334 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001335 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1336 final Setting setting;
1337 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001338 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001339 } else {
1340 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1341 name);
1342 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001343 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001344 }
1345
Svetoslav7ec28e82015-05-20 17:01:10 -07001346 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001347 }
Svetoslav683914b2015-01-15 14:22:26 -08001348 }
1349
Svetoslav7ec28e82015-05-20 17:01:10 -07001350 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001351 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1352 }
1353
1354 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001355 if (DEBUG) {
1356 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1357 }
1358
1359 // Resolve the userId on whose behalf the call is made.
1360 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1361
Chad Brubakera6830e72017-04-28 17:34:36 -07001362 // Ensure the caller can access the setting.
1363 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1364
Svetoslav683914b2015-01-15 14:22:26 -08001365 // Determine the owning user as some profile settings are cloned from the parent.
1366 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1367
Alex Klyubin1991f572017-03-03 14:08:36 -08001368 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1369 // This caller is not permitted to access this setting. Pretend the setting doesn't
1370 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001371 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1372 owningUserId);
1373 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001374 }
1375
Christopher Tateb218e762017-04-05 16:34:07 -07001376 // As of Android O, the SSAID is read from an app-specific entry in table
1377 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1378 if (isNewSsaidSetting(name)) {
1379 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1380 synchronized (mLock) {
1381 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001382 }
Christopher Tateb218e762017-04-05 16:34:07 -07001383 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001384 if (enableOverride) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001385 if (Secure.LOCATION_MODE.equals(name)) {
1386 final Setting overridden = getLocationModeSetting(owningUserId);
Makoto Onuki0000d322017-11-28 16:31:47 -08001387 if (overridden != null) {
1388 return overridden;
1389 }
1390 }
1391 }
Mark Rathjend891f012017-01-19 04:10:37 +00001392
Christopher Tateb218e762017-04-05 16:34:07 -07001393 // Not the SSAID; do a straight lookup
1394 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001395 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001396 owningUserId, name);
1397 }
Svetoslav683914b2015-01-15 14:22:26 -08001398 }
1399
Mark Rathjend891f012017-01-19 04:10:37 +00001400 private boolean isNewSsaidSetting(String name) {
1401 return Settings.Secure.ANDROID_ID.equals(name)
1402 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1403 }
1404
Andreas Gampeb58893072018-09-05 16:52:31 -07001405 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001406 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001407 // Get uid of caller (key) used to store ssaid value
1408 String name = Integer.toString(
1409 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1410
1411 if (DEBUG) {
1412 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1413 }
1414
1415 // Retrieve the ssaid from the table if present.
1416 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1417 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001418 // If the app is an Instant App use its stored SSAID instead of our own.
1419 final String instantSsaid;
1420 final long token = Binder.clearCallingIdentity();
1421 try {
1422 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1423 owningUserId);
1424 } catch (RemoteException e) {
1425 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1426 return null;
1427 } finally {
1428 Binder.restoreCallingIdentity(token);
1429 }
Svet Ganov96c99462017-05-05 14:27:13 -07001430
1431 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1432 SETTINGS_TYPE_SSAID, owningUserId);
1433
Chad Brubaker0d277a72017-04-12 16:56:53 -07001434 if (instantSsaid != null) {
1435 // Use the stored value if it is still valid.
1436 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001437 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001438 }
1439 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001440 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1441 true, callingPkg.packageName);
1442 if (!success) {
1443 throw new IllegalStateException("Failed to update instant app android id");
1444 }
Svet Ganov96c99462017-05-05 14:27:13 -07001445 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1446 owningUserId, name);
1447 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001448 }
Mark Rathjend891f012017-01-19 04:10:37 +00001449
1450 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001451 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001452 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1453 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001454 }
1455
Svet Ganov96c99462017-05-05 14:27:13 -07001456 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1457 }
1458
1459 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1460 // SSAID settings are located in a dedicated table for internal bookkeeping
1461 // but for the world they reside in the secure table, so adjust the key here.
1462 // We have a special name when looking it up but want the world to see it as
1463 // "android_id".
1464 if (ssaidSetting != null) {
1465 return settingsState.new Setting(ssaidSetting) {
1466 @Override
1467 public int getKey() {
1468 final int userId = getUserIdFromKey(super.getKey());
1469 return makeKey(SETTINGS_TYPE_SECURE, userId);
1470 }
1471
1472 @Override
1473 public String getName() {
1474 return Settings.Secure.ANDROID_ID;
1475 }
1476 };
1477 }
1478 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001479 }
1480
Kweku Adams5e0052b2019-02-22 15:17:52 -08001481 private Setting getLocationModeSetting(int owningUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001482 synchronized (mLock) {
1483 final Setting setting = getGlobalSetting(
1484 Global.LOCATION_GLOBAL_KILL_SWITCH);
1485 if (!"1".equals(setting.getValue())) {
1486 return null;
1487 }
1488 // Global kill-switch is enabled. Return an empty value.
1489 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1490 SETTINGS_TYPE_SECURE, owningUserId);
1491 return settingsState.new Setting(
Kweku Adams5e0052b2019-02-22 15:17:52 -08001492 Secure.LOCATION_MODE,
Makoto Onuki0000d322017-11-28 16:31:47 -08001493 "", // value
1494 "", // tag
1495 "", // default value
1496 "", // package name
1497 false, // from system
1498 "0" // id
1499 ) {
1500 @Override
1501 public boolean update(String value, boolean setDefault, String packageName,
1502 String tag, boolean forceNonSystemPackage) {
Kweku Adams5e0052b2019-02-22 15:17:52 -08001503 Slog.wtf(LOG_TAG, "update shouldn't be called on this instance.");
Makoto Onuki0000d322017-11-28 16:31:47 -08001504 return false;
1505 }
1506 };
1507 }
1508 }
1509
Svetoslav Ganove080da92016-12-21 17:10:35 -08001510 private boolean insertSecureSetting(String name, String value, String tag,
1511 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001512 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001513 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001514 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1515 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001516 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001517 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1518 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001519 }
1520
Svet Ganov53a441c2016-04-19 19:38:00 -07001521 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001522 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001523 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1524 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001525 }
1526
Svetoslav Ganove080da92016-12-21 17:10:35 -08001527 return mutateSecureSetting(name, null, null, false, requestingUserId,
1528 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001529 }
1530
Svetoslav Ganove080da92016-12-21 17:10:35 -08001531 private boolean updateSecureSetting(String name, String value, String tag,
1532 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001533 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001534 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001535 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1536 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001537 }
1538
Svetoslav Ganove080da92016-12-21 17:10:35 -08001539 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1540 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001541 }
1542
Svetoslav Ganove080da92016-12-21 17:10:35 -08001543 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1544 if (DEBUG) {
1545 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1546 + mode + ", " + tag + ")");
1547 }
1548
1549 mutateSecureSetting(null, null, tag, false, requestingUserId,
1550 MUTATION_OPERATION_RESET, false, mode);
1551 }
1552
1553 private boolean mutateSecureSetting(String name, String value, String tag,
1554 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1555 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001556 // Make sure the caller can change the settings.
1557 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1558
Svetoslav683914b2015-01-15 14:22:26 -08001559 // Resolve the userId on whose behalf the call is made.
1560 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1561
Makoto Onuki28da2e32015-11-20 11:30:44 -08001562 // If this is a setting that is currently restricted for this user, do not allow
1563 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001564 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1565 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001566 return false;
1567 }
1568
1569 // Determine the owning user as some profile settings are cloned from the parent.
1570 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1571
1572 // Only the owning user can change the setting.
1573 if (owningUserId != callingUserId) {
1574 return false;
1575 }
1576
1577 // Special cases for location providers (sigh).
1578 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001579 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1580 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001581 }
1582
1583 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001584 synchronized (mLock) {
1585 switch (operation) {
1586 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001587 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001588 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001589 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001590 }
Svetoslav683914b2015-01-15 14:22:26 -08001591
Svetoslav7ec28e82015-05-20 17:01:10 -07001592 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001593 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001594 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001595 }
Svetoslav683914b2015-01-15 14:22:26 -08001596
Svetoslav7ec28e82015-05-20 17:01:10 -07001597 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001598 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001599 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001600 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001601 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001602
1603 case MUTATION_OPERATION_RESET: {
1604 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1605 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1606 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001607 }
1608 }
1609
1610 return false;
1611 }
1612
Svetoslav7ec28e82015-05-20 17:01:10 -07001613 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001614 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001615 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001616 }
1617
1618 // Resolve the userId on whose behalf the call is made.
1619 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1620
Svetoslav7ec28e82015-05-20 17:01:10 -07001621 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001622 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001623
Svetoslav7ec28e82015-05-20 17:01:10 -07001624 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001625
Svetoslav7ec28e82015-05-20 17:01:10 -07001626 String[] normalizedProjection = normalizeProjection(projection);
1627 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001628
Svetoslav7ec28e82015-05-20 17:01:10 -07001629 for (int i = 0; i < nameCount; i++) {
1630 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001631
Svetoslav7ec28e82015-05-20 17:01:10 -07001632 // Determine the owning user as some profile settings are cloned from the parent.
1633 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1634 name);
Svetoslav683914b2015-01-15 14:22:26 -08001635
Svetoslav7ec28e82015-05-20 17:01:10 -07001636 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001637 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001638 appendSettingToCursor(result, setting);
1639 }
1640
1641 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001642 }
Svetoslav683914b2015-01-15 14:22:26 -08001643 }
1644
Svetoslav7ec28e82015-05-20 17:01:10 -07001645 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001646 if (DEBUG) {
1647 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1648 }
1649
1650 // Resolve the userId on whose behalf the call is made.
1651 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1652
Chad Brubakera6830e72017-04-28 17:34:36 -07001653 // Ensure the caller can access the setting.
1654 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001655
Svetoslav683914b2015-01-15 14:22:26 -08001656 // Determine the owning user as some profile settings are cloned from the parent.
1657 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1658
1659 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001660 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001661 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001662 }
Svetoslav683914b2015-01-15 14:22:26 -08001663 }
1664
Svetoslav7ec28e82015-05-20 17:01:10 -07001665 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001666 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001667 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001668 + requestingUserId + ")");
1669 }
1670
Svetoslav7ec28e82015-05-20 17:01:10 -07001671 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001672 }
1673
Svetoslav7ec28e82015-05-20 17:01:10 -07001674 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001675 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001676 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001677 }
1678
Svetoslav7ec28e82015-05-20 17:01:10 -07001679 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001680 }
1681
Svetoslav7ec28e82015-05-20 17:01:10 -07001682 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001683 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001684 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001685 + requestingUserId + ")");
1686 }
1687
Svetoslav7ec28e82015-05-20 17:01:10 -07001688 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001689 }
1690
Svetoslav7ec28e82015-05-20 17:01:10 -07001691 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001692 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001693 if (!hasWriteSecureSettingsPermission()) {
1694 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1695 // operation is allowed for the calling package through appops.
1696 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1697 Binder.getCallingUid(), getCallingPackage(), true)) {
1698 return false;
1699 }
Svetoslav683914b2015-01-15 14:22:26 -08001700 }
1701
Svetoslav683914b2015-01-15 14:22:26 -08001702 // Resolve the userId on whose behalf the call is made.
1703 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1704
yuemingw1d13eae2018-01-30 17:27:54 +00001705 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1706 name, callingUserId, value, Binder.getCallingUid())) {
1707 return false;
1708 }
1709
Svetoslavd8d25e02015-11-20 13:09:26 -08001710 // Enforce what the calling package can mutate the system settings.
1711 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1712
Svetoslav683914b2015-01-15 14:22:26 -08001713 // Determine the owning user as some profile settings are cloned from the parent.
1714 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1715
1716 // Only the owning user id can change the setting.
1717 if (owningUserId != callingUserId) {
1718 return false;
1719 }
1720
Jeff Sharkey413573a2016-02-22 17:52:45 -07001721 // Invalidate any relevant cache files
1722 String cacheName = null;
1723 if (Settings.System.RINGTONE.equals(name)) {
1724 cacheName = Settings.System.RINGTONE_CACHE;
1725 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1726 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1727 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1728 cacheName = Settings.System.ALARM_ALERT_CACHE;
1729 }
1730 if (cacheName != null) {
1731 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001732 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001733 cacheFile.delete();
1734 }
1735
Svetoslav683914b2015-01-15 14:22:26 -08001736 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001737 synchronized (mLock) {
1738 switch (operation) {
1739 case MUTATION_OPERATION_INSERT: {
1740 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001741 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001742 owningUserId, name, value, null, false, getCallingPackage(),
1743 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001744 }
1745
1746 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001747 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001748 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001749 }
1750
1751 case MUTATION_OPERATION_UPDATE: {
1752 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001753 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001754 owningUserId, name, value, null, false, getCallingPackage(),
1755 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001756 }
Svetoslav683914b2015-01-15 14:22:26 -08001757 }
1758
Svetoslav7ec28e82015-05-20 17:01:10 -07001759 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001760 }
Svetoslav683914b2015-01-15 14:22:26 -08001761 }
1762
Billy Lau6ad2d662015-07-18 00:26:58 +01001763 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001764 // Write secure settings is a more protected permission. If caller has it we are good.
1765 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1766 == PackageManager.PERMISSION_GRANTED) {
1767 return true;
1768 }
1769
Svetoslavf41334b2015-06-23 12:06:03 -07001770 return false;
1771 }
1772
Svetoslav683914b2015-01-15 14:22:26 -08001773 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001774 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001775 if (validator != null && !validator.validate(value)) {
1776 throw new IllegalArgumentException("Invalid value: " + value
1777 + " for setting: " + name);
1778 }
1779 }
1780
Alex Klyubin1991f572017-03-03 14:08:36 -08001781 /**
1782 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1783 */
1784 private boolean isSecureSettingAccessible(String name, int callingUserId,
1785 int owningUserId) {
1786 // Special case for location (sigh).
1787 // This check is not inside the name-based checks below because this method performs checks
1788 // only if the calling user ID is not the same as the owning user ID.
1789 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1790 return false;
1791 }
1792
1793 switch (name) {
1794 case "bluetooth_address":
1795 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1796 // address in this secure setting. Secure settings can normally be read by any app,
1797 // which thus enables them to bypass the recently introduced restrictions on access
1798 // to device identifiers.
1799 // To mitigate this we make this setting available only to callers privileged to see
1800 // this device's MAC addresses, same as through public API
1801 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1802 return getContext().checkCallingOrSelfPermission(
1803 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1804 default:
1805 return true;
1806 }
1807 }
1808
Svetoslav683914b2015-01-15 14:22:26 -08001809 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1810 int owningUserId) {
1811 // Optimization - location providers are restricted only for managed profiles.
1812 if (callingUserId == owningUserId) {
1813 return false;
1814 }
1815 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1816 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1817 new UserHandle(callingUserId))) {
1818 return true;
1819 }
1820 return false;
1821 }
1822
Svetoslav683914b2015-01-15 14:22:26 -08001823 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1824 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1825 }
1826
1827 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001828 final int parentId;
1829 // Resolves dependency if setting has a dependency and the calling user has a parent
1830 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1831 && (parentId = getGroupParentLocked(userId)) != userId) {
1832 // The setting has a dependency and the profile has a parent
1833 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001834 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1835 final long token = Binder.clearCallingIdentity();
1836 try {
1837 Setting settingObj = getSecureSetting(dependency, userId);
1838 if (settingObj != null && settingObj.getValue().equals("1")) {
1839 return parentId;
1840 }
1841 } finally {
1842 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001843 }
1844 }
Svetoslav683914b2015-01-15 14:22:26 -08001845 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1846 }
1847
1848 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1849 final int parentId = getGroupParentLocked(userId);
1850 if (parentId != userId && keys.contains(name)) {
1851 return parentId;
1852 }
1853 return userId;
1854 }
1855
Svetoslavf41334b2015-06-23 12:06:03 -07001856 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001857 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001858 // System/root/shell can mutate whatever secure settings they want.
1859 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001860 final int appId = UserHandle.getAppId(callingUid);
1861 if (appId == android.os.Process.SYSTEM_UID
1862 || appId == Process.SHELL_UID
1863 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001864 return;
1865 }
1866
1867 switch (operation) {
1868 case MUTATION_OPERATION_INSERT:
1869 // Insert updates.
1870 case MUTATION_OPERATION_UPDATE: {
1871 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1872 return;
1873 }
1874
1875 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001876 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001877
1878 // Privileged apps can do whatever they want.
1879 if ((packageInfo.applicationInfo.privateFlags
1880 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1881 return;
1882 }
1883
1884 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1885 packageInfo.applicationInfo.targetSdkVersion, name);
1886 } break;
1887
1888 case MUTATION_OPERATION_DELETE: {
1889 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1890 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1891 throw new IllegalArgumentException("You cannot delete system defined"
1892 + " secure settings.");
1893 }
1894
1895 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001896 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001897
1898 // Privileged apps can do whatever they want.
1899 if ((packageInfo.applicationInfo.privateFlags &
1900 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1901 return;
1902 }
1903
1904 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1905 packageInfo.applicationInfo.targetSdkVersion, name);
1906 } break;
1907 }
1908 }
1909
Todd Kennedybe0b8892017-02-15 14:13:52 -08001910 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001911 switch (settingsType) {
1912 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001913 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001914 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001915 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001916 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001917 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001918 default:
1919 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1920 }
1921 }
1922
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001923 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1924 switch (settingsType) {
1925 case SETTINGS_TYPE_GLOBAL:
1926 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1927 case SETTINGS_TYPE_SYSTEM:
1928 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1929 case SETTINGS_TYPE_SECURE:
1930 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1931 default:
1932 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1933 }
1934 }
1935
Andreas Gampeb58893072018-09-05 16:52:31 -07001936 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001937 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001938 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1939 // in the current form.
1940 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001941 }
1942
Chad Brubakera6830e72017-04-28 17:34:36 -07001943 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001944 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1945 return;
1946 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001947 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001948 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001949 return;
1950 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001951 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1952 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001953 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1954 // breakage in the current form.
1955 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1956 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001957 }
1958 }
1959
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001960 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1961 // We always use the callingUid for this lookup. This means that if hypothetically an
1962 // app was installed in user A with cross user and in user B as an Instant App
1963 // the app in A would be able to see all the settings in user B. However since cross
1964 // user is a system permission and the app must be uninstalled in B and then installed as
1965 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001966 ApplicationInfo ai = null;
1967 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001968 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1969 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001970 } catch (RemoteException ignored) {
1971 }
1972 if (ai == null) {
1973 throw new IllegalStateException("Failed to lookup info for package "
1974 + getCallingPackage());
1975 }
1976 return ai;
1977 }
1978
Xiaohui Chen43765b72015-08-31 10:57:33 -07001979 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001980 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001981 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1982 getCallingPackage(), 0, userId);
1983 if (packageInfo != null) {
1984 return packageInfo;
1985 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001986 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001987 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001988 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001989 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001990 }
1991
1992 private int getGroupParentLocked(int userId) {
1993 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001994 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001995 return userId;
1996 }
1997 // We are in the same process with the user manager and the returned
1998 // user info is a cached instance, so just look up instead of cache.
1999 final long identity = Binder.clearCallingIdentity();
2000 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07002001 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08002002 UserInfo userInfo = mUserManager.getProfileParent(userId);
2003 return (userInfo != null) ? userInfo.id : userId;
2004 } finally {
2005 Binder.restoreCallingIdentity(identity);
2006 }
2007 }
2008
Svetoslav683914b2015-01-15 14:22:26 -08002009 private void enforceWritePermission(String permission) {
2010 if (getContext().checkCallingOrSelfPermission(permission)
2011 != PackageManager.PERMISSION_GRANTED) {
2012 throw new SecurityException("Permission denial: writing to settings requires:"
2013 + permission);
2014 }
2015 }
2016
2017 /*
2018 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
2019 * This setting contains a list of the currently enabled location providers.
2020 * But helper functions in android.providers.Settings can enable or disable
2021 * a single provider by using a "+" or "-" prefix before the provider name.
2022 *
yuemingw1d13eae2018-01-30 17:27:54 +00002023 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
2024 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
2025 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08002026 *
Svetoslav683914b2015-01-15 14:22:26 -08002027 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002028 */
Andreas Gampeb58893072018-09-05 16:52:31 -07002029 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08002030 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
2031 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08002032 if (TextUtils.isEmpty(value)) {
2033 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002034 }
Maggie83e03f52018-03-16 12:22:20 -07002035 Setting oldSetting = getSecureSetting(
2036 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
2037 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08002038 return false;
2039 }
Maggie83e03f52018-03-16 12:22:20 -07002040 String oldProviders = oldSetting.getValue();
2041 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
2042 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
2043 Set<String> newProvidersSet = new ArraySet<>();
2044 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08002045
Maggie83e03f52018-03-16 12:22:20 -07002046 String[] providerUpdates = value.split(",");
2047 boolean inputError = false;
2048 for (String provider : providerUpdates) {
2049 // do not update location_providers_allowed when input is invalid
2050 if (TextUtils.isEmpty(provider)) {
2051 inputError = true;
2052 break;
Svetoslav683914b2015-01-15 14:22:26 -08002053 }
Maggie83e03f52018-03-16 12:22:20 -07002054 final char prefix = provider.charAt(0);
2055 // do not update location_providers_allowed when input is invalid
2056 if (prefix != '+' && prefix != '-') {
2057 inputError = true;
2058 break;
Svetoslav683914b2015-01-15 14:22:26 -08002059 }
Maggie83e03f52018-03-16 12:22:20 -07002060 // skip prefix
2061 provider = provider.substring(1);
2062 if (prefix == '+') {
2063 newProvidersSet.add(provider);
2064 } else if (prefix == '-') {
2065 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002066 }
Maggie83e03f52018-03-16 12:22:20 -07002067 }
2068 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2069 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002070 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002071 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002072 mSettingsRegistry.notifyForSettingsChange(
2073 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002074 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2075 }
Svetoslav683914b2015-01-15 14:22:26 -08002076 return false;
2077 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002078 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002079 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2080 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002081 }
2082
Svetoslav683914b2015-01-15 14:22:26 -08002083 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2084 int targetSdkVersion, String name) {
2085 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2086 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2087 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2088 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2089 + " This will soon become an error.");
2090 } else {
2091 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2092 + " This will soon become an error.");
2093 }
2094 } else {
2095 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2096 throw new IllegalArgumentException("You cannot change private secure settings.");
2097 } else {
2098 throw new IllegalArgumentException("You cannot keep your settings in"
2099 + " the secure settings.");
2100 }
2101 }
2102 }
2103
2104 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2105 if (requestingUserId == UserHandle.getCallingUserId()) {
2106 return requestingUserId;
2107 }
2108 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2109 Binder.getCallingUid(), requestingUserId, false, true,
2110 "get/set setting for user", null);
2111 }
2112
Svet Ganov53a441c2016-04-19 19:38:00 -07002113 private Bundle packageValueForCallResult(Setting setting,
2114 boolean trackingGeneration) {
2115 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002116 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002117 return NULL_SETTING_BUNDLE;
2118 }
2119 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002120 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002121 Bundle result = new Bundle();
2122 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002123 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002124
Svetoslav Ganove080da92016-12-21 17:10:35 -08002125 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002126 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002127 }
2128
2129 private static int getRequestingUserId(Bundle args) {
2130 final int callingUserId = UserHandle.getCallingUserId();
2131 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2132 : callingUserId;
2133 }
2134
Svet Ganov53a441c2016-04-19 19:38:00 -07002135 private boolean isTrackingGeneration(Bundle args) {
2136 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2137 }
2138
Svetoslav683914b2015-01-15 14:22:26 -08002139 private static String getSettingValue(Bundle args) {
2140 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2141 }
2142
Svetoslav Ganove080da92016-12-21 17:10:35 -08002143 private static String getSettingTag(Bundle args) {
2144 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2145 }
2146
Matt Pape6bfc62e2018-11-28 13:16:03 -08002147 private static String getSettingPrefix(Bundle args) {
2148 String prefix = (args != null) ? args.getString(Settings.CALL_METHOD_PREFIX_KEY) : null;
2149 // Append '/' to ensure we only match properties with this exact prefix.
2150 // i.e. "foo" should match "foo/property" but not "foobar/property"
2151 return prefix != null ? prefix + "/" : null;
2152 }
2153
Svetoslav Ganove080da92016-12-21 17:10:35 -08002154 private static boolean getSettingMakeDefault(Bundle args) {
2155 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2156 }
2157
2158 private static int getResetModeEnforcingPermission(Bundle args) {
2159 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2160 switch (mode) {
2161 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2162 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2163 throw new SecurityException("Only system, shell/root on a "
2164 + "debuggable build can reset to untrusted defaults");
2165 }
2166 return mode;
2167 }
2168 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2169 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2170 throw new SecurityException("Only system, shell/root on a "
2171 + "debuggable build can reset untrusted changes");
2172 }
2173 return mode;
2174 }
2175 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2176 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2177 throw new SecurityException("Only system, shell/root on a "
2178 + "debuggable build can reset to trusted defaults");
2179 }
2180 return mode;
2181 }
2182 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2183 return mode;
2184 }
2185 }
2186 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2187 }
2188
2189 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2190 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2191 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2192 && (appId == SHELL_UID || appId == ROOT_UID));
2193 }
2194
Svetoslav683914b2015-01-15 14:22:26 -08002195 private static String getValidTableOrThrow(Uri uri) {
2196 if (uri.getPathSegments().size() > 0) {
2197 String table = uri.getPathSegments().get(0);
2198 if (DatabaseHelper.isValidTable(table)) {
2199 return table;
2200 }
2201 throw new IllegalArgumentException("Bad root path: " + table);
2202 }
2203 throw new IllegalArgumentException("Invalid URI:" + uri);
2204 }
2205
2206 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002207 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002208 return new MatrixCursor(projection, 0);
2209 }
2210 MatrixCursor cursor = new MatrixCursor(projection, 1);
2211 appendSettingToCursor(cursor, setting);
2212 return cursor;
2213 }
2214
2215 private static String[] normalizeProjection(String[] projection) {
2216 if (projection == null) {
2217 return ALL_COLUMNS;
2218 }
2219
2220 final int columnCount = projection.length;
2221 for (int i = 0; i < columnCount; i++) {
2222 String column = projection[i];
2223 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2224 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002225 }
2226 }
2227
Svetoslav683914b2015-01-15 14:22:26 -08002228 return projection;
2229 }
2230
2231 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002232 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002233 return;
2234 }
Svetoslav683914b2015-01-15 14:22:26 -08002235 final int columnCount = cursor.getColumnCount();
2236
2237 String[] values = new String[columnCount];
2238
2239 for (int i = 0; i < columnCount; i++) {
2240 String column = cursor.getColumnName(i);
2241
2242 switch (column) {
2243 case Settings.NameValueTable._ID: {
2244 values[i] = setting.getId();
2245 } break;
2246
2247 case Settings.NameValueTable.NAME: {
2248 values[i] = setting.getName();
2249 } break;
2250
2251 case Settings.NameValueTable.VALUE: {
2252 values[i] = setting.getValue();
2253 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002254 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002255 }
2256
Svetoslav683914b2015-01-15 14:22:26 -08002257 cursor.addRow(values);
2258 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002259
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002260 private static boolean isKeyValid(String key) {
2261 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2262 }
2263
Matt Pape7b1c6cd2019-01-04 08:10:41 -08002264 private String resolveCallingPackage() {
2265 switch (Binder.getCallingUid()) {
2266 case Process.ROOT_UID: {
2267 return "root";
2268 }
2269
2270 case Process.SHELL_UID: {
2271 return "com.android.shell";
2272 }
2273
2274 default: {
2275 return getCallingPackage();
2276 }
2277 }
2278 }
2279
Svetoslav683914b2015-01-15 14:22:26 -08002280 private static final class Arguments {
2281 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2282 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2283
2284 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2285 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2286
2287 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2288 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2289
2290 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2291 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2292
2293 public final String table;
2294 public final String name;
2295
2296 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2297 final int segmentSize = uri.getPathSegments().size();
2298 switch (segmentSize) {
2299 case 1: {
2300 if (where != null
2301 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2302 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2303 && whereArgs.length == 1) {
2304 name = whereArgs[0];
2305 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002306 return;
Svetoslav683914b2015-01-15 14:22:26 -08002307 } else if (where != null
2308 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2309 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2310 final int startIndex = Math.max(where.indexOf("'"),
2311 where.indexOf("\"")) + 1;
2312 final int endIndex = Math.max(where.lastIndexOf("'"),
2313 where.lastIndexOf("\""));
2314 name = where.substring(startIndex, endIndex);
2315 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002316 return;
Svetoslav683914b2015-01-15 14:22:26 -08002317 } else if (supportAll && where == null && whereArgs == null) {
2318 name = null;
2319 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002320 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002321 }
Svetoslav683914b2015-01-15 14:22:26 -08002322 } break;
2323
Svetoslav28494652015-02-12 14:11:42 -08002324 case 2: {
2325 if (where == null && whereArgs == null) {
2326 name = uri.getPathSegments().get(1);
2327 table = computeTableForSetting(uri, name);
2328 return;
2329 }
2330 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002331 }
Svetoslav28494652015-02-12 14:11:42 -08002332
2333 EventLogTags.writeUnsupportedSettingsQuery(
2334 uri.toSafeString(), where, Arrays.toString(whereArgs));
2335 String message = String.format( "Supported SQL:\n"
2336 + " uri content://some_table/some_property with null where and where args\n"
2337 + " uri content://some_table with query name=? and single name as arg\n"
2338 + " uri content://some_table with query name=some_name and null args\n"
2339 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2340 Arrays.toString(whereArgs));
2341 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002342 }
2343
Svetoslav28494652015-02-12 14:11:42 -08002344 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002345 String table = getValidTableOrThrow(uri);
2346
2347 if (name != null) {
2348 if (sSystemMovedToSecureSettings.contains(name)) {
2349 table = TABLE_SECURE;
2350 }
2351
2352 if (sSystemMovedToGlobalSettings.contains(name)) {
2353 table = TABLE_GLOBAL;
2354 }
2355
2356 if (sSecureMovedToGlobalSettings.contains(name)) {
2357 table = TABLE_GLOBAL;
2358 }
2359
2360 if (sGlobalMovedToSecureSettings.contains(name)) {
2361 table = TABLE_SECURE;
2362 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002363 }
Svetoslav683914b2015-01-15 14:22:26 -08002364
2365 return table;
2366 }
2367 }
2368
2369 final class SettingsRegistry {
2370 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2371
Svetoslav683914b2015-01-15 14:22:26 -08002372 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2373 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2374 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002375 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002376 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002377
2378 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002379
2380 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2381
Svet Ganov53a441c2016-04-19 19:38:00 -07002382 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002383
Svetoslav7e0683b2015-08-03 16:02:52 -07002384 private final Handler mHandler;
2385
Svet Ganov53a441c2016-04-19 19:38:00 -07002386 private final BackupManager mBackupManager;
2387
Amith Yamasani39452022017-03-21 15:23:47 -07002388 private String mSettingsCreationBuildId;
2389
Svetoslav683914b2015-01-15 14:22:26 -08002390 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002391 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002392 mGenerationRegistry = new GenerationRegistry(mLock);
2393 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002394 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002395 syncSsaidTableOnStart();
2396 }
2397
2398 private void generateUserKeyLocked(int userId) {
2399 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002400 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002401 final SecureRandom rand = new SecureRandom();
2402 rand.nextBytes(keyBytes);
2403
2404 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002405 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002406
2407 // Store the key in the ssaid table.
2408 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2409 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2410 true, SettingsState.SYSTEM_PACKAGE_NAME);
2411
2412 if (!success) {
2413 throw new IllegalStateException("Ssaid settings not accessible");
2414 }
2415 }
2416
Mark Rathjen7599f132017-01-23 14:15:54 -08002417 private byte[] getLengthPrefix(byte[] data) {
2418 return ByteBuffer.allocate(4).putInt(data.length).array();
2419 }
2420
Christopher Tateb218e762017-04-05 16:34:07 -07002421 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002422 // Read the user's key from the ssaid table.
2423 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002424 if (userKeySetting == null || userKeySetting.isNull()
2425 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002426 // Lazy initialize and store the user key.
2427 generateUserKeyLocked(userId);
2428 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002429 if (userKeySetting == null || userKeySetting.isNull()
2430 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002431 throw new IllegalStateException("User key not accessible");
2432 }
2433 }
2434 final String userKey = userKeySetting.getValue();
2435
2436 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002437 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2438
2439 // Validate that the key is of expected length.
2440 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2441 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002442 throw new IllegalStateException("User key invalid");
2443 }
2444
Mark Rathjen7599f132017-01-23 14:15:54 -08002445 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002446 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002447 m = Mac.getInstance("HmacSHA256");
2448 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002449 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002450 throw new IllegalStateException("HmacSHA256 is not available", e);
2451 } catch (InvalidKeyException e) {
2452 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002453 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002454
Mark Rathjenf42dd912017-06-05 19:04:34 -07002455 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002456 for (int i = 0; i < callingPkg.signatures.length; i++) {
2457 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002458 m.update(getLengthPrefix(sig), 0, 4);
2459 m.update(sig);
2460 }
Mark Rathjend891f012017-01-19 04:10:37 +00002461
2462 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002463 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2464 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002465
2466 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002467 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002468 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2469 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002470 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002471
2472 if (!success) {
2473 throw new IllegalStateException("Ssaid settings not accessible");
2474 }
2475
2476 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2477 }
2478
2479 public void syncSsaidTableOnStart() {
2480 synchronized (mLock) {
2481 // Verify that each user's packages and ssaid's are in sync.
2482 for (UserInfo user : mUserManager.getUsers(true)) {
2483 // Get all uids for the user's packages.
2484 final List<PackageInfo> packages;
2485 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002486 packages = mPackageManager.getInstalledPackages(
2487 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2488 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002489 } catch (RemoteException e) {
2490 throw new IllegalStateException("Package manager not available");
2491 }
2492 final Set<String> appUids = new HashSet<>();
2493 for (PackageInfo info : packages) {
2494 appUids.add(Integer.toString(info.applicationInfo.uid));
2495 }
2496
2497 // Get all uids currently stored in the user's ssaid table.
2498 final Set<String> ssaidUids = new HashSet<>(
2499 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2500 ssaidUids.remove(SSAID_USER_KEY);
2501
2502 // Perform a set difference for the appUids and ssaidUids.
2503 ssaidUids.removeAll(appUids);
2504
2505 // If there are ssaidUids left over they need to be removed from the table.
2506 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2507 user.id);
2508 for (String uid : ssaidUids) {
2509 ssaidSettings.deleteSettingLocked(uid);
2510 }
2511 }
2512 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002513 }
2514
Svetoslav683914b2015-01-15 14:22:26 -08002515 public List<String> getSettingsNamesLocked(int type, int userId) {
2516 final int key = makeKey(type, userId);
2517 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002518 if (settingsState == null) {
2519 return new ArrayList<String>();
2520 }
Svetoslav683914b2015-01-15 14:22:26 -08002521 return settingsState.getSettingNamesLocked();
2522 }
2523
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002524 public SparseBooleanArray getKnownUsersLocked() {
2525 SparseBooleanArray users = new SparseBooleanArray();
2526 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2527 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2528 }
2529 return users;
2530 }
2531
Kweku Adamsb0886f32017-10-31 15:32:09 -07002532 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002533 public SettingsState getSettingsLocked(int type, int userId) {
2534 final int key = makeKey(type, userId);
2535 return peekSettingsStateLocked(key);
2536 }
2537
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002538 public boolean ensureSettingsForUserLocked(int userId) {
2539 // First make sure this user actually exists.
2540 if (mUserManager.getUserInfo(userId) == null) {
2541 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2542 return false;
2543 }
2544
Svetoslav683914b2015-01-15 14:22:26 -08002545 // Migrate the setting for this user if needed.
2546 migrateLegacySettingsForUserIfNeededLocked(userId);
2547
Matt Pape1b31a332018-10-17 09:58:28 -07002548 // Ensure config settings loaded if owner.
2549 if (userId == UserHandle.USER_SYSTEM) {
2550 final int configKey
2551 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2552 ensureSettingsStateLocked(configKey);
2553 }
2554
Svetoslav683914b2015-01-15 14:22:26 -08002555 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002556 if (userId == UserHandle.USER_SYSTEM) {
2557 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002558 ensureSettingsStateLocked(globalKey);
2559 }
2560
2561 // Ensure secure settings loaded.
2562 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2563 ensureSettingsStateLocked(secureKey);
2564
2565 // Make sure the secure settings have an Android id set.
2566 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2567 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2568
2569 // Ensure system settings loaded.
2570 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2571 ensureSettingsStateLocked(systemKey);
2572
Mark Rathjend891f012017-01-19 04:10:37 +00002573 // Ensure secure settings loaded.
2574 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2575 ensureSettingsStateLocked(ssaidKey);
2576
Svetoslav683914b2015-01-15 14:22:26 -08002577 // Upgrade the settings to the latest version.
2578 UpgradeController upgrader = new UpgradeController(userId);
2579 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002580 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002581 }
2582
2583 private void ensureSettingsStateLocked(int key) {
2584 if (mSettingsStates.get(key) == null) {
2585 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002586 SettingsState settingsState = new SettingsState(getContext(), mLock,
2587 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002588 mSettingsStates.put(key, settingsState);
2589 }
2590 }
2591
2592 public void removeUserStateLocked(int userId, boolean permanently) {
2593 // We always keep the global settings in memory.
2594
2595 // Nuke system settings.
2596 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2597 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2598 if (systemSettingsState != null) {
2599 if (permanently) {
2600 mSettingsStates.remove(systemKey);
2601 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002602 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002603 systemSettingsState.destroyLocked(new Runnable() {
2604 @Override
2605 public void run() {
2606 mSettingsStates.remove(systemKey);
2607 }
2608 });
2609 }
2610 }
2611
2612 // Nuke secure settings.
2613 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2614 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2615 if (secureSettingsState != null) {
2616 if (permanently) {
2617 mSettingsStates.remove(secureKey);
2618 secureSettingsState.destroyLocked(null);
2619 } else {
2620 secureSettingsState.destroyLocked(new Runnable() {
2621 @Override
2622 public void run() {
2623 mSettingsStates.remove(secureKey);
2624 }
2625 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002626 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002627 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002628
Mark Rathjend891f012017-01-19 04:10:37 +00002629 // Nuke ssaid settings.
2630 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2631 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2632 if (ssaidSettingsState != null) {
2633 if (permanently) {
2634 mSettingsStates.remove(ssaidKey);
2635 ssaidSettingsState.destroyLocked(null);
2636 } else {
2637 ssaidSettingsState.destroyLocked(new Runnable() {
2638 @Override
2639 public void run() {
2640 mSettingsStates.remove(ssaidKey);
2641 }
2642 });
2643 }
2644 }
2645
Svet Ganov53a441c2016-04-19 19:38:00 -07002646 // Nuke generation tracking data
2647 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002648 }
2649
Svetoslav683914b2015-01-15 14:22:26 -08002650 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002651 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2652 Set<String> criticalSettings) {
Matt Papec1323dc2018-12-11 12:32:42 -08002653 return insertSettingLocked(type, userId, name, value, tag, makeDefault, false,
2654 packageName, forceNotify, criticalSettings);
2655 }
2656
2657 public boolean insertSettingLocked(int type, int userId, String name, String value,
2658 String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
2659 boolean forceNotify, Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002660 final int key = makeKey(type, userId);
2661
Svetoslav Ganove080da92016-12-21 17:10:35 -08002662 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002663 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002664 if (settingsState != null) {
2665 success = settingsState.insertSettingLocked(name, value,
Matt Papec1323dc2018-12-11 12:32:42 -08002666 tag, makeDefault, forceNonSystemPackage, packageName);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002667 }
Svetoslav683914b2015-01-15 14:22:26 -08002668
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002669 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2670 settingsState.persistSyncLocked();
2671 }
2672
Svet Ganov53a441c2016-04-19 19:38:00 -07002673 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002674 notifyForSettingsChange(key, name);
2675 }
2676 return success;
2677 }
2678
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002679 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2680 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002681 final int key = makeKey(type, userId);
2682
Svetoslav Ganove080da92016-12-21 17:10:35 -08002683 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002684 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002685 if (settingsState != null) {
2686 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002687 }
Svetoslav683914b2015-01-15 14:22:26 -08002688
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002689 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2690 settingsState.persistSyncLocked();
2691 }
2692
Svet Ganov53a441c2016-04-19 19:38:00 -07002693 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002694 notifyForSettingsChange(key, name);
2695 }
2696 return success;
2697 }
2698
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002699 public boolean updateSettingLocked(int type, int userId, String name, String value,
2700 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2701 Set<String> criticalSettings) {
2702 final int key = makeKey(type, userId);
2703
2704 boolean success = false;
2705 SettingsState settingsState = peekSettingsStateLocked(key);
2706 if (settingsState != null) {
2707 success = settingsState.updateSettingLocked(name, value, tag,
2708 makeDefault, packageName);
2709 }
2710
2711 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2712 settingsState.persistSyncLocked();
2713 }
2714
2715 if (forceNotify || success) {
2716 notifyForSettingsChange(key, name);
2717 }
2718
2719 return success;
2720 }
2721
Svetoslav683914b2015-01-15 14:22:26 -08002722 public Setting getSettingLocked(int type, int userId, String name) {
2723 final int key = makeKey(type, userId);
2724
2725 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002726 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002727 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002728 }
Mark Rathjend891f012017-01-19 04:10:37 +00002729
2730 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002731 return settingsState.getSettingLocked(name);
2732 }
2733
Svetoslav Ganove080da92016-12-21 17:10:35 -08002734 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2735 String tag) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002736 resetSettingsLocked(type, userId, packageName, mode, tag, null);
2737 }
2738
2739 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2740 String tag, @Nullable String prefix) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002741 final int key = makeKey(type, userId);
2742 SettingsState settingsState = peekSettingsStateLocked(key);
2743 if (settingsState == null) {
2744 return;
2745 }
2746
2747 switch (mode) {
2748 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2749 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002750 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002751 Setting setting = settingsState.getSettingLocked(name);
2752 if (packageName.equals(setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002753 if ((tag != null && !tag.equals(setting.getTag()))
2754 || (prefix != null && !setting.getName().startsWith(prefix))) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08002755 continue;
2756 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002757 if (settingsState.resetSettingLocked(name)) {
2758 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002759 notifyForSettingsChange(key, name);
2760 }
2761 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002762 if (someSettingChanged) {
2763 settingsState.persistSyncLocked();
2764 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002765 }
2766 } break;
2767
2768 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2769 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002770 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002771 Setting setting = settingsState.getSettingLocked(name);
2772 if (!SettingsState.isSystemPackage(getContext(),
2773 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002774 if (prefix != null && !setting.getName().startsWith(prefix)) {
2775 continue;
2776 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002777 if (settingsState.resetSettingLocked(name)) {
2778 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002779 notifyForSettingsChange(key, name);
2780 }
2781 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002782 if (someSettingChanged) {
2783 settingsState.persistSyncLocked();
2784 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002785 }
2786 } break;
2787
2788 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2789 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002790 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002791 Setting setting = settingsState.getSettingLocked(name);
2792 if (!SettingsState.isSystemPackage(getContext(),
2793 setting.getPackageName())) {
Matt Pape6bfc62e2018-11-28 13:16:03 -08002794 if (prefix != null && !setting.getName().startsWith(prefix)) {
2795 continue;
2796 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002797 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002798 if (settingsState.resetSettingLocked(name)) {
2799 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002800 notifyForSettingsChange(key, name);
2801 }
2802 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002803 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002804 notifyForSettingsChange(key, name);
2805 }
2806 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002807 if (someSettingChanged) {
2808 settingsState.persistSyncLocked();
2809 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002810 }
2811 } break;
2812
2813 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2814 for (String name : settingsState.getSettingNamesLocked()) {
2815 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002816 boolean someSettingChanged = false;
Matt Pape6bfc62e2018-11-28 13:16:03 -08002817 if (prefix != null && !setting.getName().startsWith(prefix)) {
2818 continue;
2819 }
Eugene Suslad72c3972016-12-27 15:49:30 -08002820 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002821 if (settingsState.resetSettingLocked(name)) {
2822 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002823 notifyForSettingsChange(key, name);
2824 }
2825 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002826 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002827 notifyForSettingsChange(key, name);
2828 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002829 if (someSettingChanged) {
2830 settingsState.persistSyncLocked();
2831 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002832 }
2833 } break;
2834 }
2835 }
2836
Zimuzoc56192c2018-07-25 10:40:01 +01002837 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002838 // Global and secure settings are signature protected. Apps signed
2839 // by the platform certificate are generally not uninstalled and
2840 // the main exception is tests. We trust components signed
2841 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002842
2843 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2844 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002845 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002846 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002847 }
Svetoslav683914b2015-01-15 14:22:26 -08002848 }
2849
Mark Rathjend891f012017-01-19 04:10:37 +00002850 public void onUidRemovedLocked(int uid) {
2851 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2852 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002853 if (ssaidSettings != null) {
2854 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2855 }
Mark Rathjend891f012017-01-19 04:10:37 +00002856 }
2857
Kweku Adamsb0886f32017-10-31 15:32:09 -07002858 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002859 private SettingsState peekSettingsStateLocked(int key) {
2860 SettingsState settingsState = mSettingsStates.get(key);
2861 if (settingsState != null) {
2862 return settingsState;
2863 }
2864
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002865 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2866 return null;
2867 }
Svetoslav683914b2015-01-15 14:22:26 -08002868 return mSettingsStates.get(key);
2869 }
2870
2871 private void migrateAllLegacySettingsIfNeeded() {
2872 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002873 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002874 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002875 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002876 return;
2877 }
2878
Amith Yamasani39452022017-03-21 15:23:47 -07002879 mSettingsCreationBuildId = Build.ID;
2880
Svetoslav683914b2015-01-15 14:22:26 -08002881 final long identity = Binder.clearCallingIdentity();
2882 try {
2883 List<UserInfo> users = mUserManager.getUsers(true);
2884
2885 final int userCount = users.size();
2886 for (int i = 0; i < userCount; i++) {
2887 final int userId = users.get(i).id;
2888
2889 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2890 SQLiteDatabase database = dbHelper.getWritableDatabase();
2891 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2892
2893 // Upgrade to the latest version.
2894 UpgradeController upgrader = new UpgradeController(userId);
2895 upgrader.upgradeIfNeededLocked();
2896
2897 // Drop from memory if not a running user.
2898 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2899 removeUserStateLocked(userId, false);
2900 }
2901 }
2902 } finally {
2903 Binder.restoreCallingIdentity(identity);
2904 }
2905 }
2906 }
2907
2908 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2909 // Every user has secure settings and if no file we need to migrate.
2910 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2911 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002912 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002913 return;
2914 }
2915
2916 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2917 SQLiteDatabase database = dbHelper.getWritableDatabase();
2918
2919 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2920 }
2921
2922 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2923 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002924 // Move over the system settings.
2925 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2926 ensureSettingsStateLocked(systemKey);
2927 SettingsState systemSettings = mSettingsStates.get(systemKey);
2928 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2929 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002930
2931 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002932 // Do this after System settings, since this is the first thing we check when deciding
2933 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002934 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2935 ensureSettingsStateLocked(secureKey);
2936 SettingsState secureSettings = mSettingsStates.get(secureKey);
2937 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2938 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2939 secureSettings.persistSyncLocked();
2940
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002941 // Move over the global settings if owner.
2942 // Do this last, since this is the first thing we check when deciding
2943 // to skip over migration from db to xml for owner user.
2944 if (userId == UserHandle.USER_SYSTEM) {
2945 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2946 ensureSettingsStateLocked(globalKey);
2947 SettingsState globalSettings = mSettingsStates.get(globalKey);
2948 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002949 // If this was just created
2950 if (mSettingsCreationBuildId != null) {
2951 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2952 mSettingsCreationBuildId, null, true,
2953 SettingsState.SYSTEM_PACKAGE_NAME);
2954 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002955 globalSettings.persistSyncLocked();
2956 }
Svetoslav683914b2015-01-15 14:22:26 -08002957
2958 // Drop the database as now all is moved and persisted.
2959 if (DROP_DATABASE_ON_MIGRATION) {
2960 dbHelper.dropDatabase();
2961 } else {
2962 dbHelper.backupDatabase();
2963 }
2964 }
2965
2966 private void migrateLegacySettingsLocked(SettingsState settingsState,
2967 SQLiteDatabase database, String table) {
2968 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2969 queryBuilder.setTables(table);
2970
2971 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2972 null, null, null, null, null);
2973
2974 if (cursor == null) {
2975 return;
2976 }
2977
2978 try {
2979 if (!cursor.moveToFirst()) {
2980 return;
2981 }
2982
2983 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2984 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2985
2986 settingsState.setVersionLocked(database.getVersion());
2987
2988 while (!cursor.isAfterLast()) {
2989 String name = cursor.getString(nameColumnIdx);
2990 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002991 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002992 SettingsState.SYSTEM_PACKAGE_NAME);
2993 cursor.moveToNext();
2994 }
2995 } finally {
2996 cursor.close();
2997 }
2998 }
2999
Andreas Gampeb58893072018-09-05 16:52:31 -07003000 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08003001 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
3002 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
3003
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003004 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08003005 return;
3006 }
3007
3008 final int userId = getUserIdFromKey(secureSettings.mKey);
3009
3010 final UserInfo user;
3011 final long identity = Binder.clearCallingIdentity();
3012 try {
3013 user = mUserManager.getUserInfo(userId);
3014 } finally {
3015 Binder.restoreCallingIdentity(identity);
3016 }
3017 if (user == null) {
3018 // Can happen due to races when deleting users - treat as benign.
3019 return;
3020 }
3021
3022 String androidId = Long.toHexString(new SecureRandom().nextLong());
3023 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003024 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003025
3026 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
3027 + "] for user " + userId);
3028
3029 // Write a drop box entry if it's a restricted profile
3030 if (user.isRestricted()) {
3031 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
3032 Context.DROPBOX_SERVICE);
3033 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
3034 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
3035 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
3036 }
3037 }
3038 }
3039
3040 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07003041 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07003042 mGenerationRegistry.incrementGeneration(key);
3043
Svet Ganov945864c2018-03-22 21:49:10 -07003044 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06003045 final long token = Binder.clearCallingIdentity();
3046 try {
3047 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
3048 // When the global kill switch is updated, send the
3049 // change notification for the location setting.
3050 notifyLocationChangeForRunningUsers();
3051 }
3052 notifyGlobalSettingChangeForRunningUsers(key, name);
3053 } finally {
3054 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07003055 }
Svet Ganov945864c2018-03-22 21:49:10 -07003056 } else {
3057 final int userId = getUserIdFromKey(key);
3058 final Uri uri = getNotificationUriFor(key, name);
3059 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3060 userId, 0, uri).sendToTarget();
3061 if (isSecureSettingsKey(key)) {
3062 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3063 sSecureCloneToManagedSettings);
3064 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
3065 sSystemCloneFromParentOnDependency.values());
3066 } else if (isSystemSettingsKey(key)) {
3067 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
3068 sSystemCloneToManagedSettings);
3069 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003070 }
Svet Ganov53a441c2016-04-19 19:38:00 -07003071
Svet Ganov945864c2018-03-22 21:49:10 -07003072 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07003073 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003074 }
3075
Svet Ganov53a441c2016-04-19 19:38:00 -07003076 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00003077 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003078 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003079 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003080 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003081 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07003082 final int key = makeKey(type, profileId);
3083 // Increment the generation first, so observers always see the new value
3084 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07003085 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07003086 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01003087 }
3088 }
3089 }
Svetoslav683914b2015-01-15 14:22:26 -08003090 }
3091
Svet Ganov945864c2018-03-22 21:49:10 -07003092 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
3093 // Important: No need to update generation for each user as there
3094 // is a singleton generation entry for the global settings which
3095 // is already incremented be the caller.
3096 final Uri uri = getNotificationUriFor(key, name);
3097 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
3098 for (int i = 0; i < users.size(); i++) {
3099 final int userId = users.get(i).id;
3100 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
3101 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3102 userId, 0, uri).sendToTarget();
3103 }
3104 }
3105 }
3106
Makoto Onuki0000d322017-11-28 16:31:47 -08003107 private void notifyLocationChangeForRunningUsers() {
3108 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3109
3110 for (int i = 0; i < users.size(); i++) {
3111 final int userId = users.get(i).id;
3112
3113 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3114 continue;
3115 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003116
Svet Ganov945864c2018-03-22 21:49:10 -07003117 // Increment the generation first, so observers always see the new value
3118 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3119 mGenerationRegistry.incrementGeneration(key);
3120
Kweku Adams5e0052b2019-02-22 15:17:52 -08003121 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_MODE);
Makoto Onuki0000d322017-11-28 16:31:47 -08003122 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3123 userId, 0, uri).sendToTarget();
3124 }
3125 }
3126
Matt Pape1b31a332018-10-17 09:58:28 -07003127 private boolean isConfigSettingsKey(int key) {
3128 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3129 }
3130
Svetoslav683914b2015-01-15 14:22:26 -08003131 private boolean isGlobalSettingsKey(int key) {
3132 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3133 }
3134
3135 private boolean isSystemSettingsKey(int key) {
3136 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3137 }
3138
3139 private boolean isSecureSettingsKey(int key) {
3140 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3141 }
3142
Mark Rathjend891f012017-01-19 04:10:37 +00003143 private boolean isSsaidSettingsKey(int key) {
3144 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3145 }
3146
Svetoslav683914b2015-01-15 14:22:26 -08003147 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003148 if (isConfigSettingsKey(key)) {
3149 final int userId = getUserIdFromKey(key);
3150 return new File(Environment.getUserSystemDirectory(userId),
3151 SETTINGS_FILE_CONFIG);
3152 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003153 final int userId = getUserIdFromKey(key);
3154 return new File(Environment.getUserSystemDirectory(userId),
3155 SETTINGS_FILE_GLOBAL);
3156 } else if (isSystemSettingsKey(key)) {
3157 final int userId = getUserIdFromKey(key);
3158 return new File(Environment.getUserSystemDirectory(userId),
3159 SETTINGS_FILE_SYSTEM);
3160 } else if (isSecureSettingsKey(key)) {
3161 final int userId = getUserIdFromKey(key);
3162 return new File(Environment.getUserSystemDirectory(userId),
3163 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003164 } else if (isSsaidSettingsKey(key)) {
3165 final int userId = getUserIdFromKey(key);
3166 return new File(Environment.getUserSystemDirectory(userId),
3167 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003168 } else {
3169 throw new IllegalArgumentException("Invalid settings key:" + key);
3170 }
3171 }
3172
3173 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003174 if (isConfigSettingsKey(key)) {
Matt Pape1278d1c2018-12-11 13:03:49 -08003175 return (name != null) ? Uri.withAppendedPath(DeviceConfig.CONTENT_URI, name)
3176 : DeviceConfig.CONTENT_URI;
Matt Pape1b31a332018-10-17 09:58:28 -07003177 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003178 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3179 : Settings.Global.CONTENT_URI;
3180 } else if (isSecureSettingsKey(key)) {
3181 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3182 : Settings.Secure.CONTENT_URI;
3183 } else if (isSystemSettingsKey(key)) {
3184 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3185 : Settings.System.CONTENT_URI;
3186 } else {
3187 throw new IllegalArgumentException("Invalid settings key:" + key);
3188 }
3189 }
3190
3191 private int getMaxBytesPerPackageForType(int type) {
3192 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003193 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003194 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003195 case SETTINGS_TYPE_SECURE:
3196 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003197 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3198 }
3199
3200 default: {
3201 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3202 }
3203 }
3204 }
3205
Svetoslav7e0683b2015-08-03 16:02:52 -07003206 private final class MyHandler extends Handler {
3207 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3208 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3209
3210 public MyHandler(Looper looper) {
3211 super(looper);
3212 }
3213
3214 @Override
3215 public void handleMessage(Message msg) {
3216 switch (msg.what) {
3217 case MSG_NOTIFY_URI_CHANGED: {
3218 final int userId = msg.arg1;
3219 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003220 try {
3221 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3222 } catch (SecurityException e) {
3223 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3224 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003225 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003226 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3227 }
3228 } break;
3229
3230 case MSG_NOTIFY_DATA_CHANGED: {
3231 mBackupManager.dataChanged();
3232 } break;
3233 }
3234 }
3235 }
3236
Svetoslav683914b2015-01-15 14:22:26 -08003237 private final class UpgradeController {
wilsonshih5d999e22019-03-20 11:50:42 +08003238 private static final int SETTINGS_VERSION = 176;
Svetoslav683914b2015-01-15 14:22:26 -08003239
3240 private final int mUserId;
3241
3242 public UpgradeController(int userId) {
3243 mUserId = userId;
3244 }
3245
3246 public void upgradeIfNeededLocked() {
3247 // The version of all settings for a user is the same (all users have secure).
3248 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003249 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003250
3251 // Try an update from the current state.
3252 final int oldVersion = secureSettings.getVersionLocked();
3253 final int newVersion = SETTINGS_VERSION;
3254
Svet Ganovc9755bc2015-03-28 13:21:22 -07003255 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003256 if (oldVersion == newVersion) {
3257 return;
3258 }
3259
3260 // Try to upgrade.
3261 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3262
3263 // If upgrade failed start from scratch and upgrade.
3264 if (curVersion != newVersion) {
3265 // Drop state we have for this user.
3266 removeUserStateLocked(mUserId, true);
3267
3268 // Recreate the database.
3269 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3270 SQLiteDatabase database = dbHelper.getWritableDatabase();
3271 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3272
3273 // Migrate the settings for this user.
3274 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3275
3276 // Now upgrade should work fine.
3277 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003278
3279 // Make a note what happened, so we don't wonder why data was lost
3280 String reason = "Settings rebuilt! Current version: "
3281 + curVersion + " while expected: " + newVersion;
3282 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003283 Settings.Global.DATABASE_DOWNGRADE_REASON,
3284 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003285 }
3286
3287 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003288 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003289 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003290 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003291 globalSettings.setVersionLocked(newVersion);
3292 }
3293
3294 // Set the secure settings version.
3295 secureSettings.setVersionLocked(newVersion);
3296
3297 // Set the system settings version.
3298 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003299 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003300 systemSettings.setVersionLocked(newVersion);
3301 }
3302
3303 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003304 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003305 }
3306
3307 private SettingsState getSecureSettingsLocked(int userId) {
3308 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3309 }
3310
Mark Rathjend891f012017-01-19 04:10:37 +00003311 private SettingsState getSsaidSettingsLocked(int userId) {
3312 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3313 }
3314
Svetoslav683914b2015-01-15 14:22:26 -08003315 private SettingsState getSystemSettingsLocked(int userId) {
3316 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3317 }
3318
Jeff Brown503cffc2015-03-26 18:08:51 -07003319 /**
3320 * You must perform all necessary mutations to bring the settings
3321 * for this user from the old to the new version. When you add a new
3322 * upgrade step you *must* update SETTINGS_VERSION.
3323 *
3324 * This is an example of moving a setting from secure to global.
3325 *
3326 * // v119: Example settings changes.
3327 * if (currentVersion == 118) {
3328 * if (userId == UserHandle.USER_OWNER) {
3329 * // Remove from the secure settings.
3330 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3331 * String name = "example_setting_to_move";
3332 * String value = secureSettings.getSetting(name);
3333 * secureSettings.deleteSetting(name);
3334 *
3335 * // Add to the global settings.
3336 * SettingsState globalSettings = getGlobalSettingsLocked();
3337 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3338 * }
3339 *
3340 * // Update the current version.
3341 * currentVersion = 119;
3342 * }
3343 */
Svetoslav683914b2015-01-15 14:22:26 -08003344 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3345 if (DEBUG) {
3346 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3347 + oldVersion + " to version: " + newVersion);
3348 }
3349
Jeff Brown503cffc2015-03-26 18:08:51 -07003350 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003351
John Spurlocke11ae112015-05-11 16:09:03 -04003352 // v119: Reset zen + ringer mode.
3353 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003354 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003355 final SettingsState globalSettings = getGlobalSettingsLocked();
3356 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003357 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3358 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003359 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003360 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3361 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003362 }
3363 currentVersion = 119;
3364 }
3365
Jason Monk27bbb2d2015-03-31 16:46:39 -04003366 // v120: Add double tap to wake setting.
3367 if (currentVersion == 119) {
3368 SettingsState secureSettings = getSecureSettingsLocked(userId);
3369 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3370 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003371 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003372 SettingsState.SYSTEM_PACKAGE_NAME);
3373
3374 currentVersion = 120;
3375 }
3376
Svetoslav7e0683b2015-08-03 16:02:52 -07003377 if (currentVersion == 120) {
3378 // Before 121, we used a different string encoding logic. We just bump the
3379 // version here; SettingsState knows how to handle pre-version 120 files.
3380 currentVersion = 121;
3381 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003382
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003383 if (currentVersion == 121) {
3384 // Version 122: allow OEMs to set a default payment component in resources.
3385 // Note that we only write the default if no default has been set;
3386 // if there is, we just leave the default at whatever it currently is.
3387 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3388 String defaultComponent = (getContext().getResources().getString(
3389 R.string.def_nfc_payment_component));
3390 Setting currentSetting = secureSettings.getSettingLocked(
3391 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3392 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003393 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003394 secureSettings.insertSettingLocked(
3395 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003396 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003397 }
3398 currentVersion = 122;
3399 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003400
3401 if (currentVersion == 122) {
3402 // Version 123: Adding a default value for the ability to add a user from
3403 // the lock screen.
3404 if (userId == UserHandle.USER_SYSTEM) {
3405 final SettingsState globalSettings = getGlobalSettingsLocked();
3406 Setting currentSetting = globalSettings.getSettingLocked(
3407 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003408 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003409 globalSettings.insertSettingLocked(
3410 Settings.Global.ADD_USERS_WHEN_LOCKED,
3411 getContext().getResources().getBoolean(
3412 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003413 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003414 }
3415 }
3416 currentVersion = 123;
3417 }
Bryce Leebd179282015-12-17 19:01:37 -08003418
3419 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003420 final SettingsState globalSettings = getGlobalSettingsLocked();
3421 String defaultDisabledProfiles = (getContext().getResources().getString(
3422 R.string.def_bluetooth_disabled_profiles));
3423 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003424 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003425 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003426 }
3427
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003428 if (currentVersion == 124) {
3429 // Version 124: allow OEMs to set a default value for whether IME should be
3430 // shown when a physical keyboard is connected.
3431 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3432 Setting currentSetting = secureSettings.getSettingLocked(
3433 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003434 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003435 secureSettings.insertSettingLocked(
3436 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3437 getContext().getResources().getBoolean(
3438 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003439 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003440 }
3441 currentVersion = 125;
3442 }
3443
Ruben Brunk98576cf2016-03-07 18:54:28 -08003444 if (currentVersion == 125) {
3445 // Version 125: Allow OEMs to set the default VR service.
3446 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3447
3448 Setting currentSetting = secureSettings.getSettingLocked(
3449 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003450 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003451 ArraySet<ComponentName> l =
3452 SystemConfig.getInstance().getDefaultVrComponents();
3453
3454 if (l != null && !l.isEmpty()) {
3455 StringBuilder b = new StringBuilder();
3456 boolean start = true;
3457 for (ComponentName c : l) {
3458 if (!start) {
3459 b.append(':');
3460 }
3461 b.append(c.flattenToString());
3462 start = false;
3463 }
3464 secureSettings.insertSettingLocked(
3465 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003466 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003467 }
3468
3469 }
3470 currentVersion = 126;
3471 }
3472
Daniel U02ba6122016-04-01 18:41:42 +01003473 if (currentVersion == 126) {
3474 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3475 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3476 if (mUserManager.isManagedProfile(userId)) {
3477 final SettingsState systemSecureSettings =
3478 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3479
3480 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3481 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003482 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003483 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3484 secureSettings.insertSettingLocked(
3485 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003486 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003487 SettingsState.SYSTEM_PACKAGE_NAME);
3488 }
3489
3490 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3491 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003492 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003493 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3494 secureSettings.insertSettingLocked(
3495 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003496 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003497 SettingsState.SYSTEM_PACKAGE_NAME);
3498 }
3499 }
3500 currentVersion = 127;
3501 }
3502
Steven Ngdc20ba62016-04-26 18:19:04 +01003503 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003504 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003505 currentVersion = 128;
3506 }
3507
Julia Reynolds1f721e12016-07-11 08:50:58 -04003508 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003509 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003510 currentVersion = 129;
3511 }
3512
Dan Sandler71f85e92016-07-20 13:46:05 -04003513 if (currentVersion == 129) {
3514 // default longpress timeout changed from 500 to 400. If unchanged from the old
3515 // default, update to the new default.
3516 final SettingsState systemSecureSettings =
3517 getSecureSettingsLocked(userId);
3518 final String oldValue = systemSecureSettings.getSettingLocked(
3519 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3520 if (TextUtils.equals("500", oldValue)) {
3521 systemSecureSettings.insertSettingLocked(
3522 Settings.Secure.LONG_PRESS_TIMEOUT,
3523 String.valueOf(getContext().getResources().getInteger(
3524 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003525 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003526 }
3527 currentVersion = 130;
3528 }
3529
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003530 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003531 // Split Ambient settings
3532 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3533 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3534 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3535
3536 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003537 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003538 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003539 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003540 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003541 }
3542 currentVersion = 131;
3543 }
3544
3545 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003546 // Initialize new multi-press timeout to default value
3547 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3548 final String oldValue = systemSecureSettings.getSettingLocked(
3549 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3550 if (TextUtils.equals(null, oldValue)) {
3551 systemSecureSettings.insertSettingLocked(
3552 Settings.Secure.MULTI_PRESS_TIMEOUT,
3553 String.valueOf(getContext().getResources().getInteger(
3554 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003555 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003556 }
3557
Adrian Roos69741a22016-10-21 14:49:17 -07003558 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003559 }
3560
Adrian Roos69741a22016-10-21 14:49:17 -07003561 if (currentVersion == 132) {
3562 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003563 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3564 String defaultSyncParentSounds = (getContext().getResources()
3565 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3566 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003567 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3568 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003569 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003570 }
3571
Adrian Roos69741a22016-10-21 14:49:17 -07003572 if (currentVersion == 133) {
3573 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003574 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003575 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3576 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003577 String defaultEndButtonBehavior = Integer.toString(getContext()
3578 .getResources().getInteger(R.integer.def_end_button_behavior));
3579 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003580 defaultEndButtonBehavior, null, true,
3581 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003582 }
Adrian Roos69741a22016-10-21 14:49:17 -07003583 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003584 }
3585
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003586 if (currentVersion == 134) {
3587 // Remove setting that specifies if magnification values should be preserved.
3588 // This setting defaulted to true and never has a UI.
3589 getSecureSettingsLocked(userId).deleteSettingLocked(
3590 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3591 currentVersion = 135;
3592 }
3593
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003594 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003595 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003596 currentVersion = 136;
3597 }
3598
Mark Rathjend891f012017-01-19 04:10:37 +00003599 if (currentVersion == 136) {
3600 // Version 136: Store legacy SSAID for all apps currently installed on the
3601 // device as first step in migrating SSAID to be unique per application.
3602
3603 final boolean isUpgrade;
3604 try {
3605 isUpgrade = mPackageManager.isUpgrade();
3606 } catch (RemoteException e) {
3607 throw new IllegalStateException("Package manager not available");
3608 }
3609 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3610 // user data or first boot on a new device should use new ssaid generation.
3611 if (isUpgrade) {
3612 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003613 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3614 userId, Settings.Secure.ANDROID_ID);
3615 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3616 || legacySsaidSetting.getValue() == null) {
3617 throw new IllegalStateException("Legacy ssaid not accessible");
3618 }
3619 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003620
3621 // Fill each uid with the legacy ssaid to be backwards compatible.
3622 final List<PackageInfo> packages;
3623 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003624 packages = mPackageManager.getInstalledPackages(
3625 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3626 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003627 } catch (RemoteException e) {
3628 throw new IllegalStateException("Package manager not available");
3629 }
3630
3631 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3632 for (PackageInfo info : packages) {
3633 // Check if the UID already has an entry in the table.
3634 final String uid = Integer.toString(info.applicationInfo.uid);
3635 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3636
3637 if (ssaid.isNull() || ssaid.getValue() == null) {
3638 // Android Id doesn't exist for this package so create it.
3639 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3640 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003641 if (DEBUG) {
3642 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3643 }
Mark Rathjend891f012017-01-19 04:10:37 +00003644 }
3645 }
3646 }
3647
3648 currentVersion = 137;
3649 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003650 if (currentVersion == 137) {
3651 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3652 // default value set to 1. The user can no longer change the value of this
3653 // setting through the UI.
3654 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3655 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003656 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3657 && secureSetting.getSettingLocked(
3658 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3659
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003660 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3661 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003662 // For managed profiles with profile owners, DevicePolicyManagerService
3663 // may want to set the user restriction in this case
3664 secureSetting.insertSettingLocked(
3665 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3666 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003667 }
3668 currentVersion = 138;
3669 }
Mark Rathjend891f012017-01-19 04:10:37 +00003670
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003671 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003672 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003673 currentVersion = 139;
3674 }
3675
Phil Weaver385912e2017-02-10 10:06:56 -08003676 if (currentVersion == 139) {
3677 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3678 // the user can no longer change the value of this setting through the UI.
3679 // Force to true.
3680 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3681 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3682 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3683 currentVersion = 140;
3684 }
3685
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003686 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003687 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003688 currentVersion = 141;
3689 }
3690
Svet Ganov13701552017-02-23 12:45:17 -08003691 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003692 // This implementation was incorrectly setting the current value of
3693 // settings changed by non-system packages as the default which default
3694 // is set by the system. We add a new upgrade step at the end to properly
3695 // handle this case which would also fix incorrect changes made by the
3696 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003697 currentVersion = 142;
3698 }
3699
Stephen Chen5d0922f2017-03-27 10:28:04 -07003700 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003701 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003702 if (userId == UserHandle.USER_SYSTEM) {
3703 final SettingsState globalSettings = getGlobalSettingsLocked();
3704 Setting currentSetting = globalSettings.getSettingLocked(
3705 Settings.Global.WIFI_WAKEUP_ENABLED);
3706 if (currentSetting.isNull()) {
3707 globalSettings.insertSettingLocked(
3708 Settings.Global.WIFI_WAKEUP_ENABLED,
3709 getContext().getResources().getBoolean(
3710 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3711 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3712 }
3713 }
3714
3715 currentVersion = 143;
3716 }
3717
Felipe Lemeff355092017-04-03 12:55:02 -07003718 if (currentVersion == 143) {
3719 // Version 144: Set a default value for Autofill service.
3720 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3721 final Setting currentSetting = secureSettings
3722 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3723 if (currentSetting.isNull()) {
3724 final String defaultValue = getContext().getResources().getString(
3725 com.android.internal.R.string.config_defaultAutofillService);
3726 if (defaultValue != null) {
3727 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3728 + "for user " + userId);
3729 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3730 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3731 }
3732 }
3733
3734 currentVersion = 144;
3735 }
3736
Jeremy Joslin45caa252017-05-04 11:22:46 -07003737 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003738 // Version 145: Removed
3739 currentVersion = 145;
3740 }
3741
3742 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003743 // Version 146: In step 142 we had a bug where incorrectly
3744 // some settings were considered system set and as a result
3745 // made the default and marked as the default being set by
3746 // the system. Here reevaluate the default and default system
3747 // set flags. This would both fix corruption by the old impl
3748 // of step 142 and also properly handle devices which never
3749 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003750 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003751 SettingsState globalSettings = getGlobalSettingsLocked();
3752 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3753 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003754 }
3755
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003756 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3757 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3758 secureSettings.persistSyncLocked();
3759
3760 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3761 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3762 systemSettings.persistSyncLocked();
3763
Amin Shaikh86367962017-06-07 08:58:22 -07003764 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003765 }
3766
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003767 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003768 // Version 147: Removed. (This version previously allowed showing the
3769 // "wifi_wakeup_available" setting).
3770 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003771 currentVersion = 147;
3772 }
3773
3774 if (currentVersion == 147) {
3775 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003776 if (userId == UserHandle.USER_SYSTEM) {
3777 final SettingsState globalSettings = getGlobalSettingsLocked();
3778 final Setting currentSetting = globalSettings.getSettingLocked(
3779 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3780 if (currentSetting.isNull()) {
3781 globalSettings.insertSettingLocked(
3782 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3783 getContext().getResources().getBoolean(
3784 R.bool.def_restrict_background_data) ? "1" : "0",
3785 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3786 }
3787 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003788 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003789 }
3790
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003791 if (currentVersion == 148) {
3792 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3793 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3794 final String oldValue = systemSecureSettings.getSettingLocked(
3795 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3796 if (TextUtils.equals(null, oldValue)) {
3797 final String defaultValue = getContext().getResources().getString(
3798 R.string.def_backup_manager_constants);
3799 if (!TextUtils.isEmpty(defaultValue)) {
3800 systemSecureSettings.insertSettingLocked(
3801 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3802 true, SettingsState.SYSTEM_PACKAGE_NAME);
3803 }
3804 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003805 currentVersion = 149;
3806 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003807
3808 if (currentVersion == 149) {
3809 // Version 150: Set a default value for mobile data always on
3810 final SettingsState globalSettings = getGlobalSettingsLocked();
3811 final Setting currentSetting = globalSettings.getSettingLocked(
3812 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3813 if (currentSetting.isNull()) {
3814 globalSettings.insertSettingLocked(
3815 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3816 getContext().getResources().getBoolean(
3817 R.bool.def_mobile_data_always_on) ? "1" : "0",
3818 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3819 }
3820
3821 currentVersion = 150;
3822 }
3823
Mike Digman4af4a6f2018-01-16 14:49:38 -08003824 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003825 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003826 currentVersion = 151;
3827 }
3828
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003829 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003830 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3831 // by default but it is now no longer configurable).
3832 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003833 currentVersion = 152;
3834 }
3835
Joe LaPenna250d7842018-01-25 10:19:42 -08003836 if (currentVersion == 152) {
3837 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3838 currentVersion = 153;
3839 }
3840
Ben Linb4df8bc2018-01-29 11:48:20 -08003841 if (currentVersion == 153) {
3842 // Version 154: Read notification badge configuration from config.
3843 // If user has already set the value, don't do anything.
3844 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3845 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3846 Settings.Secure.NOTIFICATION_BADGING);
3847 if (showNotificationBadges.isNull()) {
3848 final boolean defaultValue = getContext().getResources().getBoolean(
3849 com.android.internal.R.bool.config_notificationBadging);
3850 systemSecureSettings.insertSettingLocked(
3851 Secure.NOTIFICATION_BADGING,
3852 defaultValue ? "1" : "0",
3853 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3854 }
3855 currentVersion = 154;
3856 }
3857
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003858 if (currentVersion == 154) {
3859 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3860 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3861 final String oldValue = systemSecureSettings.getSettingLocked(
3862 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3863 if (TextUtils.equals(null, oldValue)) {
3864 final String defaultValue = getContext().getResources().getString(
3865 R.string.def_backup_local_transport_parameters);
3866 if (!TextUtils.isEmpty(defaultValue)) {
3867 systemSecureSettings.insertSettingLocked(
3868 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3869 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3870 }
3871
3872 }
3873 currentVersion = 155;
3874 }
3875
Beverlyda904812018-03-02 09:55:30 -05003876 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003877 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003878 final SettingsState globalSettings = getGlobalSettingsLocked();
3879 final String oldValue = globalSettings.getSettingLocked(
3880 Global.CHARGING_STARTED_SOUND).getValue();
3881 final String oldDefault = getContext().getResources().getString(
3882 R.string.def_wireless_charging_started_sound);
3883 if (TextUtils.equals(null, oldValue)
3884 || TextUtils.equals(oldValue, oldDefault)) {
3885 final String defaultValue = getContext().getResources().getString(
3886 R.string.def_charging_started_sound);
3887 if (!TextUtils.isEmpty(defaultValue)) {
3888 globalSettings.insertSettingLocked(
3889 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3890 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3891 }
3892
3893 }
3894 currentVersion = 156;
3895 }
3896
Beverly09da25f2018-02-26 09:17:07 -05003897 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003898 // Version 157: Set a default value for zen duration,
3899 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003900 final SettingsState globalSettings = getGlobalSettingsLocked();
3901 final Setting currentSetting = globalSettings.getSettingLocked(
3902 Global.ZEN_DURATION);
3903 if (currentSetting.isNull()) {
3904 String defaultZenDuration = Integer.toString(getContext()
3905 .getResources().getInteger(R.integer.def_zen_duration));
3906 globalSettings.insertSettingLocked(
3907 Global.ZEN_DURATION, defaultZenDuration,
3908 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3909 }
Beverly09da25f2018-02-26 09:17:07 -05003910 currentVersion = 157;
3911 }
Annie Mengd069a882018-03-13 15:31:40 +00003912
3913 if (currentVersion == 157) {
3914 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3915 final SettingsState globalSettings = getGlobalSettingsLocked();
3916 final String oldValue = globalSettings.getSettingLocked(
3917 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3918 if (TextUtils.equals(null, oldValue)) {
3919 final String defaultValue = getContext().getResources().getString(
3920 R.string.def_backup_agent_timeout_parameters);
3921 if (!TextUtils.isEmpty(defaultValue)) {
3922 globalSettings.insertSettingLocked(
3923 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3924 null, true,
3925 SettingsState.SYSTEM_PACKAGE_NAME);
3926 }
3927 }
3928 currentVersion = 158;
3929 }
Roshan Pius9c396672018-03-02 14:54:13 -08003930
3931 if (currentVersion == 158) {
3932 // Remove setting that specifies wifi bgscan throttling params
3933 getGlobalSettingsLocked().deleteSettingLocked(
3934 "wifi_scan_background_throttle_interval_ms");
3935 getGlobalSettingsLocked().deleteSettingLocked(
3936 "wifi_scan_background_throttle_package_whitelist");
3937 currentVersion = 159;
3938 }
3939
Pavel Grafovc5c97302018-03-19 13:37:15 +00003940 if (currentVersion == 159) {
3941 // Version 160: Hiding notifications from the lockscreen is only available as
3942 // primary user option, profiles can only make them redacted. If a profile was
3943 // configured to not show lockscreen notifications, ensure that at the very
3944 // least these will be come hidden.
3945 if (mUserManager.isManagedProfile(userId)) {
3946 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3947 Setting showNotifications = secureSettings.getSettingLocked(
3948 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3949 // The default value is "1", check if user has turned it off.
3950 if ("0".equals(showNotifications.getValue())) {
3951 secureSettings.insertSettingLocked(
3952 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3953 null /* tag */, false /* makeDefault */,
3954 SettingsState.SYSTEM_PACKAGE_NAME);
3955 }
3956 // The setting is no longer valid for managed profiles, it should be
3957 // treated as if it was set to "1".
3958 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3959 }
3960 currentVersion = 160;
3961 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003962
3963 if (currentVersion == 160) {
3964 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003965 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003966 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3967 final SettingsState globalSettings = getGlobalSettingsLocked();
3968
3969 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003970 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3971 if (TextUtils.equals(null, oldValue)) {
3972 globalSettings.insertSettingLocked(
3973 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3974 Integer.toString(getContext().getResources().getInteger(
3975 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3976 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3977 }
3978
3979 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003980 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3981 if (TextUtils.equals(null, oldValue)) {
3982 globalSettings.insertSettingLocked(
3983 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3984 Integer.toString(getContext().getResources().getInteger(
3985 R.integer.def_sound_trigger_detection_service_op_timeout)),
3986 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3987 }
3988 currentVersion = 161;
3989 }
3990
Mike Digman55272862018-02-20 14:35:17 -08003991 if (currentVersion == 161) {
3992 // Version 161: Add a gesture for silencing phones
3993 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3994 final Setting currentSetting = secureSettings.getSettingLocked(
3995 Secure.VOLUME_HUSH_GESTURE);
3996 if (currentSetting.isNull()) {
3997 secureSettings.insertSettingLocked(
3998 Secure.VOLUME_HUSH_GESTURE,
3999 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
4000 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4001 }
4002
4003 currentVersion = 162;
4004 }
4005
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04004006 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04004007 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04004008 currentVersion = 163;
4009 }
4010
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07004011 if (currentVersion == 163) {
4012 // Version 163: Update default value of
4013 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
4014 final SettingsState settings = getGlobalSettingsLocked();
4015 final Setting currentSetting = settings.getSettingLocked(
4016 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
4017 if (currentSetting.isDefaultFromSystem()) {
4018 settings.insertSettingLocked(
4019 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
4020 Integer.toString(getContext().getResources().getInteger(
4021 R.integer
4022 .def_max_sound_trigger_detection_service_ops_per_day)),
4023 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4024 }
4025
4026 currentVersion = 164;
4027 }
4028
Julia Reynolds76bfa602018-04-23 09:38:47 -04004029 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04004030 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04004031 currentVersion = 165;
4032 }
4033
Beverly301e92a2018-04-27 09:43:05 -04004034 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04004035 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
4036 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04004037 currentVersion = 166;
4038 }
4039
Beverly38fcfd02018-05-18 17:33:40 -04004040 if (currentVersion == 166) {
4041 // Version 166: add default values for hush gesture used and manual ringer
4042 // toggle
4043 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4044 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
4045 Secure.HUSH_GESTURE_USED);
4046 if (currentHushUsedSetting.isNull()) {
4047 secureSettings.insertSettingLocked(
4048 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
4049 SettingsState.SYSTEM_PACKAGE_NAME);
4050 }
4051
4052 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
4053 Secure.MANUAL_RINGER_TOGGLE_COUNT);
4054 if (currentRingerToggleCountSetting.isNull()) {
4055 secureSettings.insertSettingLocked(
4056 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
4057 SettingsState.SYSTEM_PACKAGE_NAME);
4058 }
4059 currentVersion = 167;
4060 }
4061
Beverly155c9d22018-05-23 18:03:23 -04004062 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04004063 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
4064 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04004065 currentVersion = 168;
4066 }
4067
Michael Wright0e9eeee2018-05-26 00:31:20 +01004068 if (currentVersion == 168) {
4069 // Version 168: by default, vibrate for phone calls
4070 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4071 final Setting currentSetting = systemSettings.getSettingLocked(
4072 Settings.System.VIBRATE_WHEN_RINGING);
4073 if (currentSetting.isNull()) {
4074 systemSettings.insertSettingLocked(
4075 Settings.System.VIBRATE_WHEN_RINGING,
4076 getContext().getResources().getBoolean(
4077 R.bool.def_vibrate_when_ringing) ? "1" : "0",
4078 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4079 }
4080 currentVersion = 169;
4081 }
4082
Nadav Barf9f115d2018-06-24 10:06:50 +03004083 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04004084 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
4085 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
4086 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03004087
Beverly91d0a632018-07-02 16:45:00 -04004088 final SettingsState globalSettings = getGlobalSettingsLocked();
4089 final Setting globalZenDuration = globalSettings.getSettingLocked(
4090 Global.ZEN_DURATION);
4091
4092 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4093 final Setting secureZenDuration = secureSettings.getSettingLocked(
4094 Secure.ZEN_DURATION);
4095
4096 // ZEN_DURATION
4097 if (!globalZenDuration.isNull()) {
4098 secureSettings.insertSettingLocked(
4099 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
4100 SettingsState.SYSTEM_PACKAGE_NAME);
4101
4102 // set global zen duration setting to null since it's deprecated
4103 globalSettings.insertSettingLocked(
4104 Global.ZEN_DURATION, null, null, true,
4105 SettingsState.SYSTEM_PACKAGE_NAME);
4106 } else if (secureZenDuration.isNull()) {
4107 String defaultZenDuration = Integer.toString(getContext()
4108 .getResources().getInteger(R.integer.def_zen_duration));
4109 secureSettings.insertSettingLocked(
4110 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4111 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004112 }
Beverly91d0a632018-07-02 16:45:00 -04004113
4114 // SHOW_ZEN_SETTINGS_SUGGESTION
4115 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4116 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4117 if (currentShowZenSettingSuggestion.isNull()) {
4118 secureSettings.insertSettingLocked(
4119 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4120 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4121 }
4122
4123 // ZEN_SETTINGS_UPDATED
4124 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4125 Secure.ZEN_SETTINGS_UPDATED);
4126 if (currentUpdatedSetting.isNull()) {
4127 secureSettings.insertSettingLocked(
4128 Secure.ZEN_SETTINGS_UPDATED, "0",
4129 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4130 }
4131
4132 // ZEN_SETTINGS_SUGGESTION_VIEWED
4133 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4134 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4135 if (currentSettingSuggestionViewed.isNull()) {
4136 secureSettings.insertSettingLocked(
4137 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4138 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4139 }
4140
Nadav Barf9f115d2018-06-24 10:06:50 +03004141 currentVersion = 170;
4142 }
4143
Beverly91d0a632018-07-02 16:45:00 -04004144 if (currentVersion == 170) {
4145 // Version 170: Set the default value for Secure Settings:
4146 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4147
4148 final SettingsState globalSettings = getGlobalSettingsLocked();
4149 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4150
4151 // CHARGING_SOUNDS_ENABLED
4152 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4153 Global.CHARGING_SOUNDS_ENABLED);
4154 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4155 Secure.CHARGING_SOUNDS_ENABLED);
4156
4157 if (!globalChargingSoundEnabled.isNull()) {
Beverlyff9c5872019-01-02 15:44:00 -05004158 if (secureChargingSoundsEnabled.isNull()) {
4159 secureSettings.insertSettingLocked(
4160 Secure.CHARGING_SOUNDS_ENABLED,
4161 globalChargingSoundEnabled.getValue(), null, false,
4162 SettingsState.SYSTEM_PACKAGE_NAME);
4163 }
Beverly91d0a632018-07-02 16:45:00 -04004164
4165 // set global charging_sounds_enabled setting to null since it's deprecated
4166 globalSettings.insertSettingLocked(
4167 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4168 SettingsState.SYSTEM_PACKAGE_NAME);
4169 } else if (secureChargingSoundsEnabled.isNull()) {
4170 String defChargingSoundsEnabled = getContext().getResources()
4171 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4172 secureSettings.insertSettingLocked(
4173 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4174 true, SettingsState.SYSTEM_PACKAGE_NAME);
4175 }
4176
4177 // CHARGING_VIBRATION_ENABLED
4178 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4179 Secure.CHARGING_VIBRATION_ENABLED);
4180
4181 if (secureChargingVibrationEnabled.isNull()) {
4182 String defChargingVibrationEnabled = getContext().getResources()
4183 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4184 secureSettings.insertSettingLocked(
4185 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4186 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4187 }
4188
4189 currentVersion = 171;
4190 }
4191
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004192 if (currentVersion == 171) {
4193 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4194 // be muted.
4195 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4196 final Setting currentSetting = systemSettings.getSettingLocked(
4197 Settings.System.MUTE_STREAMS_AFFECTED);
4198 if (!currentSetting.isNull()) {
4199 try {
4200 int currentSettingIntegerValue = Integer.parseInt(
4201 currentSetting.getValue());
4202 if ((currentSettingIntegerValue
4203 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4204 systemSettings.insertSettingLocked(
4205 Settings.System.MUTE_STREAMS_AFFECTED,
4206 Integer.toString(
4207 currentSettingIntegerValue
4208 | (1 << AudioManager.STREAM_VOICE_CALL)),
4209 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4210 }
4211 } catch (NumberFormatException e) {
4212 // remove the setting in case it is not a valid integer
4213 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4214 + "setting, removing setting", e);
4215 systemSettings.deleteSettingLocked(
4216 Settings.System.MUTE_STREAMS_AFFECTED);
4217 }
4218
4219 }
4220 currentVersion = 172;
4221 }
4222
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004223 if (currentVersion == 172) {
4224 // Version 172: Set the default value for Secure Settings: LOCATION_MODE
4225
4226 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4227
4228 final Setting locationMode = secureSettings.getSettingLocked(
4229 Secure.LOCATION_MODE);
4230
4231 if (locationMode.isNull()) {
4232 final Setting locationProvidersAllowed = secureSettings.getSettingLocked(
4233 Secure.LOCATION_PROVIDERS_ALLOWED);
4234
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004235 final int defLocationMode;
4236 if (locationProvidersAllowed.isNull()) {
4237 defLocationMode = getContext().getResources().getInteger(
4238 R.integer.def_location_mode);
4239 } else {
4240 defLocationMode =
4241 !TextUtils.isEmpty(locationProvidersAllowed.getValue())
4242 ? Secure.LOCATION_MODE_ON
4243 : Secure.LOCATION_MODE_OFF;
4244 }
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004245 secureSettings.insertSettingLocked(
Soonil Nagarkar4ee3ac22019-02-08 19:19:24 -08004246 Secure.LOCATION_MODE, Integer.toString(defLocationMode),
Soonil Nagarkar42da1b12019-01-22 11:29:27 -08004247 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4248 }
4249
4250 currentVersion = 173;
4251 }
4252
Beverly4179f992019-02-08 11:34:16 -05004253 if (currentVersion == 173) {
4254 // Version 173: Set the default value for Secure Settings: NOTIFICATION_BUBBLES
4255
4256 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4257
4258 final Setting bubblesSetting = secureSettings.getSettingLocked(
4259 Secure.NOTIFICATION_BUBBLES);
4260
4261 if (bubblesSetting.isNull()) {
4262 secureSettings.insertSettingLocked(Secure.NOTIFICATION_BUBBLES,
4263 getContext().getResources().getBoolean(
4264 R.bool.def_notification_bubbles) ? "1" : "0", null,
4265 true, SettingsState.SYSTEM_PACKAGE_NAME);
4266 }
4267
4268 currentVersion = 174;
4269 }
4270
Yiwen Chen0305b572019-03-05 11:26:59 -08004271 if (currentVersion == 174) {
4272 // Version 174: Set the default value for Global Settings: APPLY_RAMPING_RINGER
4273
4274 final SettingsState globalSettings = getGlobalSettingsLocked();
4275
4276 Setting currentRampingRingerSetting = globalSettings.getSettingLocked(
4277 Settings.Global.APPLY_RAMPING_RINGER);
4278 if (currentRampingRingerSetting.isNull()) {
4279 globalSettings.insertSettingLocked(
4280 Settings.Global.APPLY_RAMPING_RINGER,
4281 getContext().getResources().getBoolean(
4282 R.bool.def_apply_ramping_ringer) ? "1" : "0", null,
4283 true, SettingsState.SYSTEM_PACKAGE_NAME);
4284 }
4285
4286 currentVersion = 175;
4287 }
4288
wilsonshih5d999e22019-03-20 11:50:42 +08004289 if (currentVersion == 175) {
4290 // Version 175: Set the default value for System Settings:
4291 // RING_VIBRATION_INTENSITY. If the notification vibration intensity has been
4292 // set and ring vibration intensity hasn't, the ring vibration intensity should
4293 // followed notification vibration intensity.
4294
4295 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4296
4297 Setting notificationVibrationIntensity = systemSettings.getSettingLocked(
4298 Settings.System.NOTIFICATION_VIBRATION_INTENSITY);
4299
4300 Setting ringVibrationIntensity = systemSettings.getSettingLocked(
4301 Settings.System.RING_VIBRATION_INTENSITY);
4302
4303 if (!notificationVibrationIntensity.isNull()
4304 && ringVibrationIntensity.isNull()) {
4305 systemSettings.insertSettingLocked(
4306 Settings.System.RING_VIBRATION_INTENSITY,
4307 notificationVibrationIntensity.getValue(),
4308 null , true, SettingsState.SYSTEM_PACKAGE_NAME);
4309 }
4310
4311 currentVersion = 176;
4312 }
4313
Felipe Lemeff355092017-04-03 12:55:02 -07004314 // vXXX: Add new settings above this point.
4315
Dan Sandler71f85e92016-07-20 13:46:05 -04004316 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004317 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004318 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004319 + currentVersion +
4320 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4321 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004322 if (DEBUG) {
4323 throw new RuntimeException("db upgrade error");
4324 }
4325 }
4326
Jeff Brown503cffc2015-03-26 18:08:51 -07004327 // Return the current version.
4328 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004329 }
4330 }
Svet Ganov13701552017-02-23 12:45:17 -08004331
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004332 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4333 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004334 List<String> names = settings.getSettingNamesLocked();
4335 final int nameCount = names.size();
4336 for (int i = 0; i < nameCount; i++) {
4337 String name = names.get(i);
4338 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004339
4340 // In the upgrade case we pretend the call is made from the app
4341 // that made the last change to the setting to properly determine
4342 // whether the call has been made by a system component.
4343 int callingUid = -1;
4344 try {
4345 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4346 } catch (RemoteException e) {
4347 /* ignore - handled below */
4348 }
4349 if (callingUid < 0) {
4350 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4351 continue;
4352 }
4353 try {
4354 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4355 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004356 if (systemSet) {
4357 settings.insertSettingLocked(name, setting.getValue(),
4358 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004359 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4360 // We had a bug where changes by non-system packages were marked
4361 // as system made and as a result set as the default. Therefore, if
4362 // the package changed the setting last is not a system one but the
4363 // setting is marked as its default coming from the system we clear
4364 // the default and clear the system set flag.
4365 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004366 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004367 } catch (IllegalStateException e) {
4368 // If the package goes over its quota during the upgrade, don't
4369 // crash but just log the error as the system does the upgrade.
4370 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4371
Svet Ganov13701552017-02-23 12:45:17 -08004372 }
4373 }
4374 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004375 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004376}