blob: 2227642f1d283550e1605616b260d0801e38eb3d [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010067import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080068import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000069import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010071import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080072import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000073import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070076import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080077import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import com.android.internal.annotations.GuardedBy;
80import com.android.internal.content.PackageMonitor;
81import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080082import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070083import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080084import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040085
Svetoslav683914b2015-01-15 14:22:26 -080086import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080087import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080089import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080090import java.nio.ByteBuffer;
91import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070094import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000096import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000097import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080098import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100100import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800101import java.util.Set;
102import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000103
Mark Rathjen7599f132017-01-23 14:15:54 -0800104import javax.crypto.Mac;
105import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
Svetoslav Ganove080da92016-12-21 17:10:35 -0800107
Svetoslav683914b2015-01-15 14:22:26 -0800108/**
109 * <p>
110 * This class is a content provider that publishes the system settings.
111 * It can be accessed via the content provider APIs or via custom call
112 * commands. The latter is a bit faster and is the preferred way to access
113 * the platform settings.
114 * </p>
115 * <p>
116 * There are three settings types, global (with signature level protection
117 * and shared across users), secure (with signature permission level
118 * protection and per user), and system (with dangerous permission level
119 * protection and per user). Global settings are stored under the device owner.
120 * Each of these settings is represented by a {@link
121 * com.android.providers.settings.SettingsState} object mapped to an integer
122 * key derived from the setting type in the most significant bits and user
123 * id in the least significant bits. Settings are synchronously loaded on
124 * instantiation of a SettingsState and asynchronously persisted on mutation.
125 * Settings are stored in the user specific system directory.
126 * </p>
127 * <p>
128 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
129 * and get a warning. Targeting higher API version prohibits this as the
130 * system settings are not a place for apps to save their state. When a package
131 * is removed the settings it added are deleted. Apps cannot delete system
132 * settings added by the platform. System settings values are validated to
133 * ensure the clients do not put bad values. Global and secure settings are
134 * changed only by trusted parties, therefore no validation is performed. Also
135 * there is a limit on the amount of app specific settings that can be added
136 * to prevent unlimited growth of the system process memory footprint.
137 * </p>
138 */
139@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700141 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700143 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800144
145 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700146
Christopher Tate06efb532012-08-24 15:29:27 -0700147 private static final String TABLE_SYSTEM = "system";
148 private static final String TABLE_SECURE = "secure";
149 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800150
151 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final String TABLE_FAVORITES = "favorites";
153 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800154 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
155 private static final String TABLE_BOOKMARKS = "bookmarks";
156 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Svetoslav683914b2015-01-15 14:22:26 -0800158 // The set of removed legacy tables.
159 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700160 static {
Svetoslav683914b2015-01-15 14:22:26 -0800161 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
162 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
163 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
164 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
165 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
166 }
Christopher Tate06efb532012-08-24 15:29:27 -0700167
Svetoslav683914b2015-01-15 14:22:26 -0800168 private static final int MUTATION_OPERATION_INSERT = 1;
169 private static final int MUTATION_OPERATION_DELETE = 2;
170 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800171 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400172
Svetoslav683914b2015-01-15 14:22:26 -0800173 private static final String[] ALL_COLUMNS = new String[] {
174 Settings.NameValueTable._ID,
175 Settings.NameValueTable.NAME,
176 Settings.NameValueTable.VALUE
177 };
178
Makoto Onuki53f0e022017-11-29 13:51:01 -0800179 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
180 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
181 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
182 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700183 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700184
185 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
186 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700187
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800188 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
189
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700190 // Overlay specified settings whitelisted for Instant Apps
191 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
192 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
193 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
194
Matt Pape1b31a332018-10-17 09:58:28 -0700195 /**
196 * TODO(b/113100523): Move this to DeviceConfig.java when it is added, and expose it as a System
197 * API.
198 */
199 private static final Uri CONFIG_CONTENT_URI =
200 Uri.parse("content://" + Settings.AUTHORITY + "/config");
201
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700202 static {
203 for (String name : Resources.getSystem().getStringArray(
204 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
205 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
206 }
207 for (String name : Resources.getSystem().getStringArray(
208 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
209 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
210 }
211 for (String name : Resources.getSystem().getStringArray(
212 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
213 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
214 }
215 }
216
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800217 // Changes to these global settings are synchronously persisted
218 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
219 static {
220 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
221 }
222
223 // Changes to these secure settings are synchronously persisted
224 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
225 static {
226 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
227 }
228
Svetoslav683914b2015-01-15 14:22:26 -0800229 // Per user secure settings that moved to the for all users global settings.
230 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
231 static {
232 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700233 }
234
Svetoslav683914b2015-01-15 14:22:26 -0800235 // Per user system settings that moved to the for all users global settings.
236 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
237 static {
238 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700239 }
240
Svetoslav683914b2015-01-15 14:22:26 -0800241 // Per user system settings that moved to the per user secure settings.
242 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
243 static {
244 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700245 }
246
Svetoslav683914b2015-01-15 14:22:26 -0800247 // Per all users global settings that moved to the per user secure settings.
248 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
249 static {
250 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700251 }
252
Svetoslav683914b2015-01-15 14:22:26 -0800253 // Per user secure settings that are cloned for the managed profiles of the user.
254 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
255 static {
256 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700257 }
258
Svetoslav683914b2015-01-15 14:22:26 -0800259 // Per user system settings that are cloned for the managed profiles of the user.
260 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
261 static {
262 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400263 }
264
Andre Lago3fa139c2016-08-04 13:53:44 +0100265 // Per user system settings that are cloned from the profile's parent when a dependency
266 // in {@link Settings.Secure} is set to "1".
267 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
268 static {
269 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
270 }
271
Svetoslav683914b2015-01-15 14:22:26 -0800272 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700273
Svetoslav683914b2015-01-15 14:22:26 -0800274 @GuardedBy("mLock")
275 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700276
Svet Ganova8f90262016-05-10 08:44:48 -0700277 @GuardedBy("mLock")
278 private HandlerThread mHandlerThread;
279
Makoto Onuki73360ab2017-03-17 11:50:13 -0700280 @GuardedBy("mLock")
281 private Handler mHandler;
282
Svetoslav7ec28e82015-05-20 17:01:10 -0700283 // We have to call in the user manager with no lock held,
284 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800285
yuemingw1d13eae2018-01-30 17:27:54 +0000286 private UserManagerInternal mUserManagerInternal;
287
Svetoslav7ec28e82015-05-20 17:01:10 -0700288 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700289 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700290
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800292 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700293 }
294
295 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800296 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700297 }
298
299 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800300 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700301 }
302
303 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800304 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700305 }
306
307 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800308 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700309 }
310
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311 @Override
312 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800313 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000314
315 // fail to boot if there're any backed up settings that don't have a non-null validator
316 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000317 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000318 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000319
Svetoslav683914b2015-01-15 14:22:26 -0800320 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700321 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000322 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700323 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700324 mHandlerThread = new HandlerThread(LOG_TAG,
325 Process.THREAD_PRIORITY_BACKGROUND);
326 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700327 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800328 mSettingsRegistry = new SettingsRegistry();
329 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700330 mHandler.post(() -> {
331 registerBroadcastReceivers();
332 startWatchingUserRestrictionChanges();
333 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700334 ServiceManager.addService("settings", new SettingsService(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);
416 String tag = getSettingTag(args);
417 final boolean makeDefault = getSettingMakeDefault(args);
418 insertConfigSetting(name, value, tag, makeDefault, requestingUserId, false);
419 break;
420 }
421
Svetoslav7ec28e82015-05-20 17:01:10 -0700422 case Settings.CALL_METHOD_PUT_GLOBAL: {
423 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800424 String tag = getSettingTag(args);
425 final boolean makeDefault = getSettingMakeDefault(args);
426 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700427 break;
428 }
429
430 case Settings.CALL_METHOD_PUT_SECURE: {
431 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800432 String tag = getSettingTag(args);
433 final boolean makeDefault = getSettingMakeDefault(args);
434 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700435 break;
436 }
437
438 case Settings.CALL_METHOD_PUT_SYSTEM: {
439 String value = getSettingValue(args);
440 insertSystemSetting(name, value, requestingUserId);
441 break;
442 }
443
Matt Pape1b31a332018-10-17 09:58:28 -0700444 case Settings.CALL_METHOD_RESET_CONFIG: {
445 final int mode = getResetModeEnforcingPermission(args);
446 String tag = getSettingTag(args);
447 resetConfigSetting(requestingUserId, mode, tag);
448 break;
449 }
450
Svetoslav Ganove080da92016-12-21 17:10:35 -0800451 case Settings.CALL_METHOD_RESET_GLOBAL: {
452 final int mode = getResetModeEnforcingPermission(args);
453 String tag = getSettingTag(args);
454 resetGlobalSetting(requestingUserId, mode, tag);
455 break;
456 }
457
458 case Settings.CALL_METHOD_RESET_SECURE: {
459 final int mode = getResetModeEnforcingPermission(args);
460 String tag = getSettingTag(args);
461 resetSecureSetting(requestingUserId, mode, tag);
462 break;
463 }
464
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800465 case Settings.CALL_METHOD_DELETE_SYSTEM: {
466 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
467 Bundle result = new Bundle();
468 result.putInt(RESULT_ROWS_DELETED, rows);
469 return result;
470 }
471
472 case Settings.CALL_METHOD_DELETE_SECURE: {
473 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
474 Bundle result = new Bundle();
475 result.putInt(RESULT_ROWS_DELETED, rows);
476 return result;
477 }
478
479 case Settings.CALL_METHOD_DELETE_GLOBAL: {
480 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
481 Bundle result = new Bundle();
482 result.putInt(RESULT_ROWS_DELETED, rows);
483 return result;
484 }
485
Svetoslav7ec28e82015-05-20 17:01:10 -0700486 default: {
487 Slog.w(LOG_TAG, "call() with invalid method: " + method);
488 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700489 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700490
Christopher Tate06efb532012-08-24 15:29:27 -0700491 return null;
492 }
493
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800494 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800495 public String getType(Uri uri) {
496 Arguments args = new Arguments(uri, null, null, true);
497 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700498 return "vnd.android.cursor.dir/" + args.table;
499 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700500 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700501 }
502 }
503
504 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800505 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
506 String order) {
507 if (DEBUG) {
508 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700509 }
510
Svetoslav683914b2015-01-15 14:22:26 -0800511 Arguments args = new Arguments(uri, where, whereArgs, true);
512 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513
Svetoslav683914b2015-01-15 14:22:26 -0800514 // If a legacy table that is gone, done.
515 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
516 return new MatrixCursor(normalizedProjection, 0);
517 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700518
Svetoslav7ec28e82015-05-20 17:01:10 -0700519 switch (args.table) {
520 case TABLE_GLOBAL: {
521 if (args.name != null) {
522 Setting setting = getGlobalSetting(args.name);
523 return packageSettingForQuery(setting, normalizedProjection);
524 } else {
525 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700526 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700527 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700528
Svetoslav7ec28e82015-05-20 17:01:10 -0700529 case TABLE_SECURE: {
530 final int userId = UserHandle.getCallingUserId();
531 if (args.name != null) {
532 Setting setting = getSecureSetting(args.name, userId);
533 return packageSettingForQuery(setting, normalizedProjection);
534 } else {
535 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800536 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700537 }
Svetoslav683914b2015-01-15 14:22:26 -0800538
Svetoslav7ec28e82015-05-20 17:01:10 -0700539 case TABLE_SYSTEM: {
540 final int userId = UserHandle.getCallingUserId();
541 if (args.name != null) {
542 Setting setting = getSystemSetting(args.name, userId);
543 return packageSettingForQuery(setting, normalizedProjection);
544 } else {
545 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800546 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700547 }
Svetoslav683914b2015-01-15 14:22:26 -0800548
Svetoslav7ec28e82015-05-20 17:01:10 -0700549 default: {
550 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700551 }
552 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700553 }
554
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800556 public Uri insert(Uri uri, ContentValues values) {
557 if (DEBUG) {
558 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700559 }
560
Svetoslav683914b2015-01-15 14:22:26 -0800561 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700562
Svetoslav683914b2015-01-15 14:22:26 -0800563 // If a legacy table that is gone, done.
564 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 return null;
566 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700567
Svetoslav683914b2015-01-15 14:22:26 -0800568 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700569 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800570 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700571 }
572
Svetoslav683914b2015-01-15 14:22:26 -0800573 String value = values.getAsString(Settings.Secure.VALUE);
574
Svetoslav7ec28e82015-05-20 17:01:10 -0700575 switch (table) {
576 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800577 if (insertGlobalSetting(name, value, null, false,
578 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700579 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700580 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700581 } break;
582
583 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800584 if (insertSecureSetting(name, value, null, false,
585 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700586 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
587 }
588 } break;
589
590 case TABLE_SYSTEM: {
591 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
592 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
593 }
594 } break;
595
596 default: {
597 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700598 }
599 }
600
Svetoslav683914b2015-01-15 14:22:26 -0800601 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700602 }
603
604 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800605 public int bulkInsert(Uri uri, ContentValues[] allValues) {
606 if (DEBUG) {
607 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700609
Svetoslav683914b2015-01-15 14:22:26 -0800610 int insertionCount = 0;
611 final int valuesCount = allValues.length;
612 for (int i = 0; i < valuesCount; i++) {
613 ContentValues values = allValues[i];
614 if (insert(uri, values) != null) {
615 insertionCount++;
616 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700617 }
Svetoslav683914b2015-01-15 14:22:26 -0800618
619 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700620 }
621
622 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800623 public int delete(Uri uri, String where, String[] whereArgs) {
624 if (DEBUG) {
625 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700627
Svetoslav683914b2015-01-15 14:22:26 -0800628 Arguments args = new Arguments(uri, where, whereArgs, false);
629
630 // If a legacy table that is gone, done.
631 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
632 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700633 }
Svetoslav683914b2015-01-15 14:22:26 -0800634
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700635 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800636 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700637 }
Svetoslav683914b2015-01-15 14:22:26 -0800638
Svetoslav7ec28e82015-05-20 17:01:10 -0700639 switch (args.table) {
640 case TABLE_GLOBAL: {
641 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700642 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700643 }
Svetoslav683914b2015-01-15 14:22:26 -0800644
Svetoslav7ec28e82015-05-20 17:01:10 -0700645 case TABLE_SECURE: {
646 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700647 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700648 }
Svetoslav683914b2015-01-15 14:22:26 -0800649
Svetoslav7ec28e82015-05-20 17:01:10 -0700650 case TABLE_SYSTEM: {
651 final int userId = UserHandle.getCallingUserId();
652 return deleteSystemSetting(args.name, userId) ? 1 : 0;
653 }
654
655 default: {
656 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800657 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700658 }
Svetoslav683914b2015-01-15 14:22:26 -0800659 }
660
661 @Override
662 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
663 if (DEBUG) {
664 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700665 }
Svetoslav683914b2015-01-15 14:22:26 -0800666
667 Arguments args = new Arguments(uri, where, whereArgs, false);
668
669 // If a legacy table that is gone, done.
670 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
671 return 0;
672 }
673
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700674 String name = values.getAsString(Settings.Secure.NAME);
675 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800676 return 0;
677 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700678 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800679
Svetoslav7ec28e82015-05-20 17:01:10 -0700680 switch (args.table) {
681 case TABLE_GLOBAL: {
682 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800683 return updateGlobalSetting(args.name, value, null, false,
684 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700685 }
Svetoslav683914b2015-01-15 14:22:26 -0800686
Svetoslav7ec28e82015-05-20 17:01:10 -0700687 case TABLE_SECURE: {
688 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800689 return updateSecureSetting(args.name, value, null, false,
690 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700691 }
Svetoslav683914b2015-01-15 14:22:26 -0800692
Svetoslav7ec28e82015-05-20 17:01:10 -0700693 case TABLE_SYSTEM: {
694 final int userId = UserHandle.getCallingUserId();
695 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
696 }
Svetoslav683914b2015-01-15 14:22:26 -0800697
Svetoslav7ec28e82015-05-20 17:01:10 -0700698 default: {
699 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800700 }
701 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700702 }
703
704 @Override
705 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100706 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
707 if (userId != UserHandle.getCallingUserId()) {
708 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
709 "Access files from the settings of another user");
710 }
711 uri = ContentProvider.getUriWithoutUserId(uri);
712
Andre Lago3fa139c2016-08-04 13:53:44 +0100713 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700714 final String cacheName;
715 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100716 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700717 cacheName = Settings.System.RINGTONE_CACHE;
718 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100719 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700720 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
721 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100722 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700723 cacheName = Settings.System.ALARM_ALERT_CACHE;
724 } else {
725 throw new FileNotFoundException("Direct file access no longer supported; "
726 + "ringtone playback is available through android.media.Ringtone");
727 }
728
Andre Lago3fa139c2016-08-04 13:53:44 +0100729 int actualCacheOwner;
730 // Redirect cache to parent if ringtone setting is owned by profile parent
731 synchronized (mLock) {
732 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
733 cacheRingtoneSetting);
734 }
735 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700736 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
737 }
738
739 private File getRingtoneCacheDir(int userId) {
740 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
741 cacheDir.mkdir();
742 SELinux.restorecon(cacheDir);
743 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700744 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800745
Eugene Suslad72c3972016-12-27 15:49:30 -0800746 /**
747 * Dump all settings as a proto buf.
748 *
749 * @param fd The file to dump to
750 */
751 void dumpProto(@NonNull FileDescriptor fd) {
752 ProtoOutputStream proto = new ProtoOutputStream(fd);
753
754 synchronized (mLock) {
755 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800756 }
757
758 proto.flush();
759 }
760
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700761 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800762 synchronized (mLock) {
763 final long identity = Binder.clearCallingIdentity();
764 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700765 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800766 final int userCount = users.size();
767 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700768 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800769 }
770 } finally {
771 Binder.restoreCallingIdentity(identity);
772 }
773 }
774 }
775
Andreas Gampeb58893072018-09-05 16:52:31 -0700776 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700777 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700778 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700779 pw.println("CONFIG SETTINGS (user " + userId + ")");
780 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
781 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
782 if (configSettings != null) {
783 dumpSettingsLocked(configSettings, pw);
784 pw.println();
785 configSettings.dumpHistoricalOperations(pw);
786 }
787
Svetoslavb505ccc2015-02-17 12:41:04 -0800788 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700789 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
790 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700791 if (globalSettings != null) {
792 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800793 pw.println();
794 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700795 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800796 }
797
798 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700799 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
800 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700801 if (secureSettings != null) {
802 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800803 pw.println();
804 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700805 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700806
Svetoslavb505ccc2015-02-17 12:41:04 -0800807 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700808 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
809 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700810 if (systemSettings != null) {
811 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800812 pw.println();
813 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700814 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800815 }
816
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700817 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
818 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800819
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700820 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800821
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700822 for (int i = 0; i < nameCount; i++) {
823 String name = names.get(i);
824 Setting setting = settingsState.getSettingLocked(name);
825 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
826 pw.print(" name:"); pw.print(toDumpString(name));
827 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800828 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700829 }
830 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800831 if (setting.getDefaultValue() != null) {
832 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800833 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800834 }
835 if (setting.getTag() != null) {
836 pw.print(" tag:"); pw.print(setting.getTag());
837 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800838 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700839 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800840 }
841
Svetoslav7e0683b2015-08-03 16:02:52 -0700842 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700843 if (s != null) {
844 return s;
845 }
846 return "{null}";
847 }
848
Svetoslav683914b2015-01-15 14:22:26 -0800849 private void registerBroadcastReceivers() {
850 IntentFilter userFilter = new IntentFilter();
851 userFilter.addAction(Intent.ACTION_USER_REMOVED);
852 userFilter.addAction(Intent.ACTION_USER_STOPPED);
853
854 getContext().registerReceiver(new BroadcastReceiver() {
855 @Override
856 public void onReceive(Context context, Intent intent) {
857 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700858 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800859
860 switch (intent.getAction()) {
861 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700862 synchronized (mLock) {
863 mSettingsRegistry.removeUserStateLocked(userId, true);
864 }
Svetoslav683914b2015-01-15 14:22:26 -0800865 } break;
866
867 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700868 synchronized (mLock) {
869 mSettingsRegistry.removeUserStateLocked(userId, false);
870 }
Svetoslav683914b2015-01-15 14:22:26 -0800871 } break;
872 }
873 }
874 }, userFilter);
875
876 PackageMonitor monitor = new PackageMonitor() {
877 @Override
878 public void onPackageRemoved(String packageName, int uid) {
879 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100880 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800881 UserHandle.getUserId(uid));
882 }
883 }
Mark Rathjend891f012017-01-19 04:10:37 +0000884
885 @Override
886 public void onUidRemoved(int uid) {
887 synchronized (mLock) {
888 mSettingsRegistry.onUidRemovedLocked(uid);
889 }
890 }
Zimuzoc56192c2018-07-25 10:40:01 +0100891
892 @Override
893 public void onPackageDataCleared(String packageName, int uid) {
894 synchronized (mLock) {
895 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
896 UserHandle.getUserId(uid));
897 }
898 }
Svetoslav683914b2015-01-15 14:22:26 -0800899 };
900
901 // package changes
902 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
903 UserHandle.ALL, true);
904 }
905
Svet Ganov53a441c2016-04-19 19:38:00 -0700906 private void startWatchingUserRestrictionChanges() {
907 // TODO: The current design of settings looking different based on user restrictions
908 // should be reworked to keep them separate and system code should check the setting
909 // first followed by checking the user restriction before performing an operation.
910 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
911 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
912 Bundle prevRestrictions) -> {
913 // We are changing the settings affected by restrictions to their current
914 // value with a forced update to ensure that all cross profile dependencies
915 // are taken into account. Also make sure the settings update to.. the same
916 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800917 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
918 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700919 final long identity = Binder.clearCallingIdentity();
920 try {
921 synchronized (mLock) {
922 Setting setting = getSecureSetting(
923 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
924 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800925 setting != null ? setting.getValue() : null, null,
926 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700927 }
928 } finally {
929 Binder.restoreCallingIdentity(identity);
930 }
931 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800932 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100933 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
934 newRestrictions.getBoolean(
935 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
936 != prevRestrictions.getBoolean(
937 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700938 final long identity = Binder.clearCallingIdentity();
939 try {
940 synchronized (mLock) {
941 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800942 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700943 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800944 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700945 }
946 } finally {
947 Binder.restoreCallingIdentity(identity);
948 }
949 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800950 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
951 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700952 final long identity = Binder.clearCallingIdentity();
953 try {
954 synchronized (mLock) {
955 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800956 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700957 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800958 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700959 }
960 } finally {
961 Binder.restoreCallingIdentity(identity);
962 }
963 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800964 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
965 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700966 final long identity = Binder.clearCallingIdentity();
967 try {
968 synchronized (mLock) {
969 Setting enable = getGlobalSetting(
970 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800971 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700972 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800973 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700974 Setting include = getGlobalSetting(
975 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800976 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700977 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800978 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700979 }
980 } finally {
981 Binder.restoreCallingIdentity(identity);
982 }
983 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800984 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
985 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700986 final long identity = Binder.clearCallingIdentity();
987 try {
988 synchronized (mLock) {
989 Setting setting = getGlobalSetting(
990 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800991 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700992 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800993 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700994 }
995 } finally {
996 Binder.restoreCallingIdentity(identity);
997 }
998 }
999 });
1000 }
1001
Matt Pape1b31a332018-10-17 09:58:28 -07001002 private Setting getConfigSetting(String name) {
1003 if (DEBUG) {
1004 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1005 }
1006
1007 // TODO(b/117663715): Ensure the caller can access the setting.
1008 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1009
1010 // Get the value.
1011 synchronized (mLock) {
1012 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1013 UserHandle.USER_SYSTEM, name);
1014 }
1015 }
1016
1017 private boolean insertConfigSetting(String name, String value, String tag,
1018 boolean makeDefault, int requestingUserId, boolean forceNotify) {
1019 if (DEBUG) {
1020 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
1021 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1022 + ", " + forceNotify + ")");
1023 }
1024 return mutateConfigSetting(name, value, tag, makeDefault, requestingUserId,
1025 MUTATION_OPERATION_INSERT, forceNotify, 0);
1026 }
1027
1028 private void resetConfigSetting(int requestingUserId, int mode, String tag) {
1029 if (DEBUG) {
1030 Slog.v(LOG_TAG, "resetConfigSetting(" + requestingUserId + ", "
1031 + mode + ", " + tag + ")");
1032 }
1033 mutateConfigSetting(null, null, tag, false, requestingUserId,
1034 MUTATION_OPERATION_RESET, false, mode);
1035 }
1036
1037 private boolean mutateConfigSetting(String name, String value, String tag,
1038 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1039 int mode) {
1040 // TODO(b/117663715): check the new permission when it's added.
1041 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1042
1043 // Resolve the userId on whose behalf the call is made.
1044 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1045
1046 // Perform the mutation.
1047 synchronized (mLock) {
1048 switch (operation) {
1049 case MUTATION_OPERATION_INSERT: {
1050 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
1051 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
1052 getCallingPackage(), forceNotify, null);
1053 }
1054
1055 case MUTATION_OPERATION_RESET: {
1056 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
1057 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1058 } return true;
1059 }
1060 }
1061
1062 return false;
1063 }
1064
Svetoslav7ec28e82015-05-20 17:01:10 -07001065 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001066 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001067 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001068 }
1069
Svetoslav7ec28e82015-05-20 17:01:10 -07001070 synchronized (mLock) {
1071 // Get the settings.
1072 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001073 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001074
Chad Brubaker97bccee2017-01-05 15:51:41 -08001075 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1076 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001077
Svetoslav7ec28e82015-05-20 17:01:10 -07001078 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001079
Svetoslav7ec28e82015-05-20 17:01:10 -07001080 String[] normalizedProjection = normalizeProjection(projection);
1081 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001082
Svetoslav7ec28e82015-05-20 17:01:10 -07001083 // Anyone can get the global settings, so no security checks.
1084 for (int i = 0; i < nameCount; i++) {
1085 String name = names.get(i);
1086 Setting setting = settingsState.getSettingLocked(name);
1087 appendSettingToCursor(result, setting);
1088 }
1089
1090 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001091 }
Svetoslav683914b2015-01-15 14:22:26 -08001092 }
1093
Svetoslav7ec28e82015-05-20 17:01:10 -07001094 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001095 if (DEBUG) {
1096 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1097 }
1098
Chad Brubakera6830e72017-04-28 17:34:36 -07001099 // Ensure the caller can access the setting.
1100 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1101
Svetoslav683914b2015-01-15 14:22:26 -08001102 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001103 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001104 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001105 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001106 }
Svetoslav683914b2015-01-15 14:22:26 -08001107 }
1108
Svetoslav Ganove080da92016-12-21 17:10:35 -08001109 private boolean updateGlobalSetting(String name, String value, String tag,
1110 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001111 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001112 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1113 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1114 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001115 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001116 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1117 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001118 }
1119
Svetoslav Ganove080da92016-12-21 17:10:35 -08001120 private boolean insertGlobalSetting(String name, String value, String tag,
1121 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001122 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001123 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1124 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1125 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001126 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001127 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1128 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001129 }
1130
Svet Ganov53a441c2016-04-19 19:38:00 -07001131 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001132 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001133 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1134 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001135 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001136 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1137 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001138 }
1139
Svetoslav Ganove080da92016-12-21 17:10:35 -08001140 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1141 if (DEBUG) {
1142 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1143 + mode + ", " + tag + ")");
1144 }
1145 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1146 MUTATION_OPERATION_RESET, false, mode);
1147 }
1148
1149 private boolean mutateGlobalSetting(String name, String value, String tag,
1150 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1151 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001152 // Make sure the caller can change the settings - treated as secure.
1153 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1154
Svetoslav683914b2015-01-15 14:22:26 -08001155 // Resolve the userId on whose behalf the call is made.
1156 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1157
Makoto Onuki28da2e32015-11-20 11:30:44 -08001158 // If this is a setting that is currently restricted for this user, do not allow
1159 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001160 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1161 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001162 return false;
1163 }
1164
1165 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001166 synchronized (mLock) {
1167 switch (operation) {
1168 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001169 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1170 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001171 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001172 }
Svetoslav683914b2015-01-15 14:22:26 -08001173
Svetoslav7ec28e82015-05-20 17:01:10 -07001174 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001175 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001176 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001177 }
Svetoslav683914b2015-01-15 14:22:26 -08001178
Svetoslav7ec28e82015-05-20 17:01:10 -07001179 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001180 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1181 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001182 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001183 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001184
1185 case MUTATION_OPERATION_RESET: {
1186 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1187 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1188 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001189 }
1190 }
1191
1192 return false;
1193 }
1194
Christopher Tateb218e762017-04-05 16:34:07 -07001195 private PackageInfo getCallingPackageInfo(int userId) {
1196 try {
1197 return mPackageManager.getPackageInfo(getCallingPackage(),
1198 PackageManager.GET_SIGNATURES, userId);
1199 } catch (RemoteException e) {
1200 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1201 }
1202 }
1203
Svetoslav7ec28e82015-05-20 17:01:10 -07001204 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001205 if (DEBUG) {
1206 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1207 }
1208
1209 // Resolve the userId on whose behalf the call is made.
1210 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1211
Christopher Tateb218e762017-04-05 16:34:07 -07001212 // The relevant "calling package" userId will be the owning userId for some
1213 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1214 // up front who the effective "new SSAID" user ID for that settings name will be.
1215 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1216 Settings.Secure.ANDROID_ID);
1217 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1218
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001220 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001221
Svetoslav7ec28e82015-05-20 17:01:10 -07001222 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001223
Svetoslav7ec28e82015-05-20 17:01:10 -07001224 String[] normalizedProjection = normalizeProjection(projection);
1225 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001226
Svetoslav7ec28e82015-05-20 17:01:10 -07001227 for (int i = 0; i < nameCount; i++) {
1228 String name = names.get(i);
1229 // Determine the owning user as some profile settings are cloned from the parent.
1230 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1231 name);
Svetoslav683914b2015-01-15 14:22:26 -08001232
Alex Klyubin1991f572017-03-03 14:08:36 -08001233 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1234 // This caller is not permitted to access this setting. Pretend the setting
1235 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001236 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001237 }
Svetoslav683914b2015-01-15 14:22:26 -08001238
Mark Rathjen7599f132017-01-23 14:15:54 -08001239 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001240 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1241 final Setting setting;
1242 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001243 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001244 } else {
1245 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1246 name);
1247 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001248 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001249 }
1250
Svetoslav7ec28e82015-05-20 17:01:10 -07001251 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001252 }
Svetoslav683914b2015-01-15 14:22:26 -08001253 }
1254
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001256 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1257 }
1258
1259 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001260 if (DEBUG) {
1261 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1262 }
1263
1264 // Resolve the userId on whose behalf the call is made.
1265 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1266
Chad Brubakera6830e72017-04-28 17:34:36 -07001267 // Ensure the caller can access the setting.
1268 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1269
Svetoslav683914b2015-01-15 14:22:26 -08001270 // Determine the owning user as some profile settings are cloned from the parent.
1271 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1272
Alex Klyubin1991f572017-03-03 14:08:36 -08001273 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1274 // This caller is not permitted to access this setting. Pretend the setting doesn't
1275 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001276 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1277 owningUserId);
1278 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001279 }
1280
Christopher Tateb218e762017-04-05 16:34:07 -07001281 // As of Android O, the SSAID is read from an app-specific entry in table
1282 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1283 if (isNewSsaidSetting(name)) {
1284 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1285 synchronized (mLock) {
1286 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001287 }
Christopher Tateb218e762017-04-05 16:34:07 -07001288 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001289 if (enableOverride) {
1290 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1291 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1292 if (overridden != null) {
1293 return overridden;
1294 }
1295 }
1296 }
Mark Rathjend891f012017-01-19 04:10:37 +00001297
Christopher Tateb218e762017-04-05 16:34:07 -07001298 // Not the SSAID; do a straight lookup
1299 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001300 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001301 owningUserId, name);
1302 }
Svetoslav683914b2015-01-15 14:22:26 -08001303 }
1304
Mark Rathjend891f012017-01-19 04:10:37 +00001305 private boolean isNewSsaidSetting(String name) {
1306 return Settings.Secure.ANDROID_ID.equals(name)
1307 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1308 }
1309
Andreas Gampeb58893072018-09-05 16:52:31 -07001310 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001311 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001312 // Get uid of caller (key) used to store ssaid value
1313 String name = Integer.toString(
1314 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1315
1316 if (DEBUG) {
1317 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1318 }
1319
1320 // Retrieve the ssaid from the table if present.
1321 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1322 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001323 // If the app is an Instant App use its stored SSAID instead of our own.
1324 final String instantSsaid;
1325 final long token = Binder.clearCallingIdentity();
1326 try {
1327 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1328 owningUserId);
1329 } catch (RemoteException e) {
1330 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1331 return null;
1332 } finally {
1333 Binder.restoreCallingIdentity(token);
1334 }
Svet Ganov96c99462017-05-05 14:27:13 -07001335
1336 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1337 SETTINGS_TYPE_SSAID, owningUserId);
1338
Chad Brubaker0d277a72017-04-12 16:56:53 -07001339 if (instantSsaid != null) {
1340 // Use the stored value if it is still valid.
1341 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001342 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001343 }
1344 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001345 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1346 true, callingPkg.packageName);
1347 if (!success) {
1348 throw new IllegalStateException("Failed to update instant app android id");
1349 }
Svet Ganov96c99462017-05-05 14:27:13 -07001350 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1351 owningUserId, name);
1352 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001353 }
Mark Rathjend891f012017-01-19 04:10:37 +00001354
1355 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001356 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001357 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1358 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001359 }
1360
Svet Ganov96c99462017-05-05 14:27:13 -07001361 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1362 }
1363
1364 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1365 // SSAID settings are located in a dedicated table for internal bookkeeping
1366 // but for the world they reside in the secure table, so adjust the key here.
1367 // We have a special name when looking it up but want the world to see it as
1368 // "android_id".
1369 if (ssaidSetting != null) {
1370 return settingsState.new Setting(ssaidSetting) {
1371 @Override
1372 public int getKey() {
1373 final int userId = getUserIdFromKey(super.getKey());
1374 return makeKey(SETTINGS_TYPE_SECURE, userId);
1375 }
1376
1377 @Override
1378 public String getName() {
1379 return Settings.Secure.ANDROID_ID;
1380 }
1381 };
1382 }
1383 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001384 }
1385
Makoto Onuki0000d322017-11-28 16:31:47 -08001386 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1387 synchronized (mLock) {
1388 final Setting setting = getGlobalSetting(
1389 Global.LOCATION_GLOBAL_KILL_SWITCH);
1390 if (!"1".equals(setting.getValue())) {
1391 return null;
1392 }
1393 // Global kill-switch is enabled. Return an empty value.
1394 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1395 SETTINGS_TYPE_SECURE, owningUserId);
1396 return settingsState.new Setting(
1397 Secure.LOCATION_PROVIDERS_ALLOWED,
1398 "", // value
1399 "", // tag
1400 "", // default value
1401 "", // package name
1402 false, // from system
1403 "0" // id
1404 ) {
1405 @Override
1406 public boolean update(String value, boolean setDefault, String packageName,
1407 String tag, boolean forceNonSystemPackage) {
1408 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1409 return false;
1410 }
1411 };
1412 }
1413 }
1414
Svetoslav Ganove080da92016-12-21 17:10:35 -08001415 private boolean insertSecureSetting(String name, String value, String tag,
1416 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001417 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001418 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001419 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1420 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001421 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001422 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1423 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001424 }
1425
Svet Ganov53a441c2016-04-19 19:38:00 -07001426 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001427 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001428 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1429 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001430 }
1431
Svetoslav Ganove080da92016-12-21 17:10:35 -08001432 return mutateSecureSetting(name, null, null, false, requestingUserId,
1433 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001434 }
1435
Svetoslav Ganove080da92016-12-21 17:10:35 -08001436 private boolean updateSecureSetting(String name, String value, String tag,
1437 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001438 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001439 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001440 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1441 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001442 }
1443
Svetoslav Ganove080da92016-12-21 17:10:35 -08001444 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1445 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001446 }
1447
Svetoslav Ganove080da92016-12-21 17:10:35 -08001448 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1449 if (DEBUG) {
1450 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1451 + mode + ", " + tag + ")");
1452 }
1453
1454 mutateSecureSetting(null, null, tag, false, requestingUserId,
1455 MUTATION_OPERATION_RESET, false, mode);
1456 }
1457
1458 private boolean mutateSecureSetting(String name, String value, String tag,
1459 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1460 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001461 // Make sure the caller can change the settings.
1462 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1463
Svetoslav683914b2015-01-15 14:22:26 -08001464 // Resolve the userId on whose behalf the call is made.
1465 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1466
Makoto Onuki28da2e32015-11-20 11:30:44 -08001467 // If this is a setting that is currently restricted for this user, do not allow
1468 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001469 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1470 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001471 return false;
1472 }
1473
1474 // Determine the owning user as some profile settings are cloned from the parent.
1475 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1476
1477 // Only the owning user can change the setting.
1478 if (owningUserId != callingUserId) {
1479 return false;
1480 }
1481
1482 // Special cases for location providers (sigh).
1483 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001484 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1485 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001486 }
1487
1488 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001489 synchronized (mLock) {
1490 switch (operation) {
1491 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001492 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001493 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001494 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001495 }
Svetoslav683914b2015-01-15 14:22:26 -08001496
Svetoslav7ec28e82015-05-20 17:01:10 -07001497 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001498 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001499 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001500 }
Svetoslav683914b2015-01-15 14:22:26 -08001501
Svetoslav7ec28e82015-05-20 17:01:10 -07001502 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001503 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001504 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001505 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001506 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001507
1508 case MUTATION_OPERATION_RESET: {
1509 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1510 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1511 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001512 }
1513 }
1514
1515 return false;
1516 }
1517
Svetoslav7ec28e82015-05-20 17:01:10 -07001518 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001519 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001520 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001521 }
1522
1523 // Resolve the userId on whose behalf the call is made.
1524 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1525
Svetoslav7ec28e82015-05-20 17:01:10 -07001526 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001527 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001528
Svetoslav7ec28e82015-05-20 17:01:10 -07001529 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001530
Svetoslav7ec28e82015-05-20 17:01:10 -07001531 String[] normalizedProjection = normalizeProjection(projection);
1532 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001533
Svetoslav7ec28e82015-05-20 17:01:10 -07001534 for (int i = 0; i < nameCount; i++) {
1535 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001536
Svetoslav7ec28e82015-05-20 17:01:10 -07001537 // Determine the owning user as some profile settings are cloned from the parent.
1538 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1539 name);
Svetoslav683914b2015-01-15 14:22:26 -08001540
Svetoslav7ec28e82015-05-20 17:01:10 -07001541 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001542 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001543 appendSettingToCursor(result, setting);
1544 }
1545
1546 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001547 }
Svetoslav683914b2015-01-15 14:22:26 -08001548 }
1549
Svetoslav7ec28e82015-05-20 17:01:10 -07001550 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001551 if (DEBUG) {
1552 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1553 }
1554
1555 // Resolve the userId on whose behalf the call is made.
1556 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1557
Chad Brubakera6830e72017-04-28 17:34:36 -07001558 // Ensure the caller can access the setting.
1559 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001560
Svetoslav683914b2015-01-15 14:22:26 -08001561 // Determine the owning user as some profile settings are cloned from the parent.
1562 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1563
1564 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001565 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001566 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001567 }
Svetoslav683914b2015-01-15 14:22:26 -08001568 }
1569
Svetoslav7ec28e82015-05-20 17:01:10 -07001570 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001571 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001572 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001573 + requestingUserId + ")");
1574 }
1575
Svetoslav7ec28e82015-05-20 17:01:10 -07001576 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001577 }
1578
Svetoslav7ec28e82015-05-20 17:01:10 -07001579 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001580 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001581 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001582 }
1583
Svetoslav7ec28e82015-05-20 17:01:10 -07001584 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001585 }
1586
Svetoslav7ec28e82015-05-20 17:01:10 -07001587 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001588 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001589 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001590 + requestingUserId + ")");
1591 }
1592
Svetoslav7ec28e82015-05-20 17:01:10 -07001593 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001594 }
1595
Svetoslav7ec28e82015-05-20 17:01:10 -07001596 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001597 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001598 if (!hasWriteSecureSettingsPermission()) {
1599 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1600 // operation is allowed for the calling package through appops.
1601 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1602 Binder.getCallingUid(), getCallingPackage(), true)) {
1603 return false;
1604 }
Svetoslav683914b2015-01-15 14:22:26 -08001605 }
1606
Svetoslav683914b2015-01-15 14:22:26 -08001607 // Resolve the userId on whose behalf the call is made.
1608 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1609
yuemingw1d13eae2018-01-30 17:27:54 +00001610 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1611 name, callingUserId, value, Binder.getCallingUid())) {
1612 return false;
1613 }
1614
Svetoslavd8d25e02015-11-20 13:09:26 -08001615 // Enforce what the calling package can mutate the system settings.
1616 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1617
Svetoslav683914b2015-01-15 14:22:26 -08001618 // Determine the owning user as some profile settings are cloned from the parent.
1619 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1620
1621 // Only the owning user id can change the setting.
1622 if (owningUserId != callingUserId) {
1623 return false;
1624 }
1625
Jeff Sharkey413573a2016-02-22 17:52:45 -07001626 // Invalidate any relevant cache files
1627 String cacheName = null;
1628 if (Settings.System.RINGTONE.equals(name)) {
1629 cacheName = Settings.System.RINGTONE_CACHE;
1630 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1631 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1632 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1633 cacheName = Settings.System.ALARM_ALERT_CACHE;
1634 }
1635 if (cacheName != null) {
1636 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001637 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001638 cacheFile.delete();
1639 }
1640
Svetoslav683914b2015-01-15 14:22:26 -08001641 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001642 synchronized (mLock) {
1643 switch (operation) {
1644 case MUTATION_OPERATION_INSERT: {
1645 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001646 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001647 owningUserId, name, value, null, false, getCallingPackage(),
1648 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001649 }
1650
1651 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001652 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001653 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001654 }
1655
1656 case MUTATION_OPERATION_UPDATE: {
1657 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001658 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001659 owningUserId, name, value, null, false, getCallingPackage(),
1660 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001661 }
Svetoslav683914b2015-01-15 14:22:26 -08001662 }
1663
Svetoslav7ec28e82015-05-20 17:01:10 -07001664 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001665 }
Svetoslav683914b2015-01-15 14:22:26 -08001666 }
1667
Billy Lau6ad2d662015-07-18 00:26:58 +01001668 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001669 // Write secure settings is a more protected permission. If caller has it we are good.
1670 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1671 == PackageManager.PERMISSION_GRANTED) {
1672 return true;
1673 }
1674
Svetoslavf41334b2015-06-23 12:06:03 -07001675 return false;
1676 }
1677
Svetoslav683914b2015-01-15 14:22:26 -08001678 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001679 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001680 if (validator != null && !validator.validate(value)) {
1681 throw new IllegalArgumentException("Invalid value: " + value
1682 + " for setting: " + name);
1683 }
1684 }
1685
Alex Klyubin1991f572017-03-03 14:08:36 -08001686 /**
1687 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1688 */
1689 private boolean isSecureSettingAccessible(String name, int callingUserId,
1690 int owningUserId) {
1691 // Special case for location (sigh).
1692 // This check is not inside the name-based checks below because this method performs checks
1693 // only if the calling user ID is not the same as the owning user ID.
1694 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1695 return false;
1696 }
1697
1698 switch (name) {
1699 case "bluetooth_address":
1700 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1701 // address in this secure setting. Secure settings can normally be read by any app,
1702 // which thus enables them to bypass the recently introduced restrictions on access
1703 // to device identifiers.
1704 // To mitigate this we make this setting available only to callers privileged to see
1705 // this device's MAC addresses, same as through public API
1706 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1707 return getContext().checkCallingOrSelfPermission(
1708 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1709 default:
1710 return true;
1711 }
1712 }
1713
Svetoslav683914b2015-01-15 14:22:26 -08001714 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1715 int owningUserId) {
1716 // Optimization - location providers are restricted only for managed profiles.
1717 if (callingUserId == owningUserId) {
1718 return false;
1719 }
1720 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1721 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1722 new UserHandle(callingUserId))) {
1723 return true;
1724 }
1725 return false;
1726 }
1727
Svetoslav683914b2015-01-15 14:22:26 -08001728 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1729 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1730 }
1731
1732 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001733 final int parentId;
1734 // Resolves dependency if setting has a dependency and the calling user has a parent
1735 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1736 && (parentId = getGroupParentLocked(userId)) != userId) {
1737 // The setting has a dependency and the profile has a parent
1738 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001739 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1740 final long token = Binder.clearCallingIdentity();
1741 try {
1742 Setting settingObj = getSecureSetting(dependency, userId);
1743 if (settingObj != null && settingObj.getValue().equals("1")) {
1744 return parentId;
1745 }
1746 } finally {
1747 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001748 }
1749 }
Svetoslav683914b2015-01-15 14:22:26 -08001750 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1751 }
1752
1753 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1754 final int parentId = getGroupParentLocked(userId);
1755 if (parentId != userId && keys.contains(name)) {
1756 return parentId;
1757 }
1758 return userId;
1759 }
1760
Svetoslavf41334b2015-06-23 12:06:03 -07001761 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001762 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001763 // System/root/shell can mutate whatever secure settings they want.
1764 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001765 final int appId = UserHandle.getAppId(callingUid);
1766 if (appId == android.os.Process.SYSTEM_UID
1767 || appId == Process.SHELL_UID
1768 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001769 return;
1770 }
1771
1772 switch (operation) {
1773 case MUTATION_OPERATION_INSERT:
1774 // Insert updates.
1775 case MUTATION_OPERATION_UPDATE: {
1776 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1777 return;
1778 }
1779
1780 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001781 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001782
1783 // Privileged apps can do whatever they want.
1784 if ((packageInfo.applicationInfo.privateFlags
1785 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1786 return;
1787 }
1788
1789 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1790 packageInfo.applicationInfo.targetSdkVersion, name);
1791 } break;
1792
1793 case MUTATION_OPERATION_DELETE: {
1794 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1795 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1796 throw new IllegalArgumentException("You cannot delete system defined"
1797 + " secure settings.");
1798 }
1799
1800 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001801 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001802
1803 // Privileged apps can do whatever they want.
1804 if ((packageInfo.applicationInfo.privateFlags &
1805 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1806 return;
1807 }
1808
1809 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1810 packageInfo.applicationInfo.targetSdkVersion, name);
1811 } break;
1812 }
1813 }
1814
Todd Kennedybe0b8892017-02-15 14:13:52 -08001815 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001816 switch (settingsType) {
1817 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001818 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001819 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001820 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001821 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001822 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001823 default:
1824 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1825 }
1826 }
1827
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001828 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1829 switch (settingsType) {
1830 case SETTINGS_TYPE_GLOBAL:
1831 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1832 case SETTINGS_TYPE_SYSTEM:
1833 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1834 case SETTINGS_TYPE_SECURE:
1835 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1836 default:
1837 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1838 }
1839 }
1840
Andreas Gampeb58893072018-09-05 16:52:31 -07001841 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001842 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001843 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1844 // in the current form.
1845 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001846 }
1847
Chad Brubakera6830e72017-04-28 17:34:36 -07001848 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001849 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1850 return;
1851 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001852 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001853 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001854 return;
1855 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001856 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1857 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001858 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1859 // breakage in the current form.
1860 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1861 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001862 }
1863 }
1864
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001865 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1866 // We always use the callingUid for this lookup. This means that if hypothetically an
1867 // app was installed in user A with cross user and in user B as an Instant App
1868 // the app in A would be able to see all the settings in user B. However since cross
1869 // user is a system permission and the app must be uninstalled in B and then installed as
1870 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001871 ApplicationInfo ai = null;
1872 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001873 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1874 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001875 } catch (RemoteException ignored) {
1876 }
1877 if (ai == null) {
1878 throw new IllegalStateException("Failed to lookup info for package "
1879 + getCallingPackage());
1880 }
1881 return ai;
1882 }
1883
Xiaohui Chen43765b72015-08-31 10:57:33 -07001884 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001885 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001886 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1887 getCallingPackage(), 0, userId);
1888 if (packageInfo != null) {
1889 return packageInfo;
1890 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001891 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001892 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001893 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001894 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001895 }
1896
1897 private int getGroupParentLocked(int userId) {
1898 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001899 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001900 return userId;
1901 }
1902 // We are in the same process with the user manager and the returned
1903 // user info is a cached instance, so just look up instead of cache.
1904 final long identity = Binder.clearCallingIdentity();
1905 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001906 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001907 UserInfo userInfo = mUserManager.getProfileParent(userId);
1908 return (userInfo != null) ? userInfo.id : userId;
1909 } finally {
1910 Binder.restoreCallingIdentity(identity);
1911 }
1912 }
1913
Svetoslav683914b2015-01-15 14:22:26 -08001914 private void enforceWritePermission(String permission) {
1915 if (getContext().checkCallingOrSelfPermission(permission)
1916 != PackageManager.PERMISSION_GRANTED) {
1917 throw new SecurityException("Permission denial: writing to settings requires:"
1918 + permission);
1919 }
1920 }
1921
1922 /*
1923 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1924 * This setting contains a list of the currently enabled location providers.
1925 * But helper functions in android.providers.Settings can enable or disable
1926 * a single provider by using a "+" or "-" prefix before the provider name.
1927 *
yuemingw1d13eae2018-01-30 17:27:54 +00001928 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1929 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1930 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001931 *
Svetoslav683914b2015-01-15 14:22:26 -08001932 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001933 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001934 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001935 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1936 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001937 if (TextUtils.isEmpty(value)) {
1938 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001939 }
Maggie83e03f52018-03-16 12:22:20 -07001940 Setting oldSetting = getSecureSetting(
1941 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1942 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001943 return false;
1944 }
Maggie83e03f52018-03-16 12:22:20 -07001945 String oldProviders = oldSetting.getValue();
1946 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1947 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1948 Set<String> newProvidersSet = new ArraySet<>();
1949 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08001950
Maggie83e03f52018-03-16 12:22:20 -07001951 String[] providerUpdates = value.split(",");
1952 boolean inputError = false;
1953 for (String provider : providerUpdates) {
1954 // do not update location_providers_allowed when input is invalid
1955 if (TextUtils.isEmpty(provider)) {
1956 inputError = true;
1957 break;
Svetoslav683914b2015-01-15 14:22:26 -08001958 }
Maggie83e03f52018-03-16 12:22:20 -07001959 final char prefix = provider.charAt(0);
1960 // do not update location_providers_allowed when input is invalid
1961 if (prefix != '+' && prefix != '-') {
1962 inputError = true;
1963 break;
Svetoslav683914b2015-01-15 14:22:26 -08001964 }
Maggie83e03f52018-03-16 12:22:20 -07001965 // skip prefix
1966 provider = provider.substring(1);
1967 if (prefix == '+') {
1968 newProvidersSet.add(provider);
1969 } else if (prefix == '-') {
1970 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08001971 }
Maggie83e03f52018-03-16 12:22:20 -07001972 }
1973 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
1974 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08001975 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001976 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07001977 mSettingsRegistry.notifyForSettingsChange(
1978 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07001979 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1980 }
Svetoslav683914b2015-01-15 14:22:26 -08001981 return false;
1982 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001983 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07001984 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
1985 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001986 }
1987
Svetoslav683914b2015-01-15 14:22:26 -08001988 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1989 int targetSdkVersion, String name) {
1990 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1991 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1992 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1993 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1994 + " This will soon become an error.");
1995 } else {
1996 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1997 + " This will soon become an error.");
1998 }
1999 } else {
2000 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2001 throw new IllegalArgumentException("You cannot change private secure settings.");
2002 } else {
2003 throw new IllegalArgumentException("You cannot keep your settings in"
2004 + " the secure settings.");
2005 }
2006 }
2007 }
2008
2009 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2010 if (requestingUserId == UserHandle.getCallingUserId()) {
2011 return requestingUserId;
2012 }
2013 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2014 Binder.getCallingUid(), requestingUserId, false, true,
2015 "get/set setting for user", null);
2016 }
2017
Svet Ganov53a441c2016-04-19 19:38:00 -07002018 private Bundle packageValueForCallResult(Setting setting,
2019 boolean trackingGeneration) {
2020 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002021 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002022 return NULL_SETTING_BUNDLE;
2023 }
2024 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002025 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002026 Bundle result = new Bundle();
2027 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002028 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002029
Svetoslav Ganove080da92016-12-21 17:10:35 -08002030 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002031 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002032 }
2033
2034 private static int getRequestingUserId(Bundle args) {
2035 final int callingUserId = UserHandle.getCallingUserId();
2036 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2037 : callingUserId;
2038 }
2039
Svet Ganov53a441c2016-04-19 19:38:00 -07002040 private boolean isTrackingGeneration(Bundle args) {
2041 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2042 }
2043
Svetoslav683914b2015-01-15 14:22:26 -08002044 private static String getSettingValue(Bundle args) {
2045 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2046 }
2047
Svetoslav Ganove080da92016-12-21 17:10:35 -08002048 private static String getSettingTag(Bundle args) {
2049 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2050 }
2051
2052 private static boolean getSettingMakeDefault(Bundle args) {
2053 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2054 }
2055
2056 private static int getResetModeEnforcingPermission(Bundle args) {
2057 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2058 switch (mode) {
2059 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2060 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2061 throw new SecurityException("Only system, shell/root on a "
2062 + "debuggable build can reset to untrusted defaults");
2063 }
2064 return mode;
2065 }
2066 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2067 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2068 throw new SecurityException("Only system, shell/root on a "
2069 + "debuggable build can reset untrusted changes");
2070 }
2071 return mode;
2072 }
2073 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2074 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2075 throw new SecurityException("Only system, shell/root on a "
2076 + "debuggable build can reset to trusted defaults");
2077 }
2078 return mode;
2079 }
2080 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2081 return mode;
2082 }
2083 }
2084 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2085 }
2086
2087 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2088 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2089 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2090 && (appId == SHELL_UID || appId == ROOT_UID));
2091 }
2092
Svetoslav683914b2015-01-15 14:22:26 -08002093 private static String getValidTableOrThrow(Uri uri) {
2094 if (uri.getPathSegments().size() > 0) {
2095 String table = uri.getPathSegments().get(0);
2096 if (DatabaseHelper.isValidTable(table)) {
2097 return table;
2098 }
2099 throw new IllegalArgumentException("Bad root path: " + table);
2100 }
2101 throw new IllegalArgumentException("Invalid URI:" + uri);
2102 }
2103
2104 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002105 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002106 return new MatrixCursor(projection, 0);
2107 }
2108 MatrixCursor cursor = new MatrixCursor(projection, 1);
2109 appendSettingToCursor(cursor, setting);
2110 return cursor;
2111 }
2112
2113 private static String[] normalizeProjection(String[] projection) {
2114 if (projection == null) {
2115 return ALL_COLUMNS;
2116 }
2117
2118 final int columnCount = projection.length;
2119 for (int i = 0; i < columnCount; i++) {
2120 String column = projection[i];
2121 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2122 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002123 }
2124 }
2125
Svetoslav683914b2015-01-15 14:22:26 -08002126 return projection;
2127 }
2128
2129 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002130 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002131 return;
2132 }
Svetoslav683914b2015-01-15 14:22:26 -08002133 final int columnCount = cursor.getColumnCount();
2134
2135 String[] values = new String[columnCount];
2136
2137 for (int i = 0; i < columnCount; i++) {
2138 String column = cursor.getColumnName(i);
2139
2140 switch (column) {
2141 case Settings.NameValueTable._ID: {
2142 values[i] = setting.getId();
2143 } break;
2144
2145 case Settings.NameValueTable.NAME: {
2146 values[i] = setting.getName();
2147 } break;
2148
2149 case Settings.NameValueTable.VALUE: {
2150 values[i] = setting.getValue();
2151 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002152 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002153 }
2154
Svetoslav683914b2015-01-15 14:22:26 -08002155 cursor.addRow(values);
2156 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002157
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002158 private static boolean isKeyValid(String key) {
2159 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2160 }
2161
Svetoslav683914b2015-01-15 14:22:26 -08002162 private static final class Arguments {
2163 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2164 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2165
2166 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2167 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2168
2169 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2170 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2171
2172 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2173 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2174
2175 public final String table;
2176 public final String name;
2177
2178 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2179 final int segmentSize = uri.getPathSegments().size();
2180 switch (segmentSize) {
2181 case 1: {
2182 if (where != null
2183 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2184 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2185 && whereArgs.length == 1) {
2186 name = whereArgs[0];
2187 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002188 return;
Svetoslav683914b2015-01-15 14:22:26 -08002189 } else if (where != null
2190 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2191 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2192 final int startIndex = Math.max(where.indexOf("'"),
2193 where.indexOf("\"")) + 1;
2194 final int endIndex = Math.max(where.lastIndexOf("'"),
2195 where.lastIndexOf("\""));
2196 name = where.substring(startIndex, endIndex);
2197 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002198 return;
Svetoslav683914b2015-01-15 14:22:26 -08002199 } else if (supportAll && where == null && whereArgs == null) {
2200 name = null;
2201 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002202 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002203 }
Svetoslav683914b2015-01-15 14:22:26 -08002204 } break;
2205
Svetoslav28494652015-02-12 14:11:42 -08002206 case 2: {
2207 if (where == null && whereArgs == null) {
2208 name = uri.getPathSegments().get(1);
2209 table = computeTableForSetting(uri, name);
2210 return;
2211 }
2212 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002213 }
Svetoslav28494652015-02-12 14:11:42 -08002214
2215 EventLogTags.writeUnsupportedSettingsQuery(
2216 uri.toSafeString(), where, Arrays.toString(whereArgs));
2217 String message = String.format( "Supported SQL:\n"
2218 + " uri content://some_table/some_property with null where and where args\n"
2219 + " uri content://some_table with query name=? and single name as arg\n"
2220 + " uri content://some_table with query name=some_name and null args\n"
2221 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2222 Arrays.toString(whereArgs));
2223 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002224 }
2225
Svetoslav28494652015-02-12 14:11:42 -08002226 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002227 String table = getValidTableOrThrow(uri);
2228
2229 if (name != null) {
2230 if (sSystemMovedToSecureSettings.contains(name)) {
2231 table = TABLE_SECURE;
2232 }
2233
2234 if (sSystemMovedToGlobalSettings.contains(name)) {
2235 table = TABLE_GLOBAL;
2236 }
2237
2238 if (sSecureMovedToGlobalSettings.contains(name)) {
2239 table = TABLE_GLOBAL;
2240 }
2241
2242 if (sGlobalMovedToSecureSettings.contains(name)) {
2243 table = TABLE_SECURE;
2244 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002245 }
Svetoslav683914b2015-01-15 14:22:26 -08002246
2247 return table;
2248 }
2249 }
2250
2251 final class SettingsRegistry {
2252 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2253
Svetoslav683914b2015-01-15 14:22:26 -08002254 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2255 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2256 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002257 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002258 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002259
2260 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002261
2262 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2263
Svet Ganov53a441c2016-04-19 19:38:00 -07002264 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002265
Svetoslav7e0683b2015-08-03 16:02:52 -07002266 private final Handler mHandler;
2267
Svet Ganov53a441c2016-04-19 19:38:00 -07002268 private final BackupManager mBackupManager;
2269
Amith Yamasani39452022017-03-21 15:23:47 -07002270 private String mSettingsCreationBuildId;
2271
Svetoslav683914b2015-01-15 14:22:26 -08002272 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002273 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002274 mGenerationRegistry = new GenerationRegistry(mLock);
2275 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002276 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002277 syncSsaidTableOnStart();
2278 }
2279
2280 private void generateUserKeyLocked(int userId) {
2281 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002282 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002283 final SecureRandom rand = new SecureRandom();
2284 rand.nextBytes(keyBytes);
2285
2286 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002287 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002288
2289 // Store the key in the ssaid table.
2290 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2291 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2292 true, SettingsState.SYSTEM_PACKAGE_NAME);
2293
2294 if (!success) {
2295 throw new IllegalStateException("Ssaid settings not accessible");
2296 }
2297 }
2298
Mark Rathjen7599f132017-01-23 14:15:54 -08002299 private byte[] getLengthPrefix(byte[] data) {
2300 return ByteBuffer.allocate(4).putInt(data.length).array();
2301 }
2302
Christopher Tateb218e762017-04-05 16:34:07 -07002303 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002304 // Read the user's key from the ssaid table.
2305 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002306 if (userKeySetting == null || userKeySetting.isNull()
2307 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002308 // Lazy initialize and store the user key.
2309 generateUserKeyLocked(userId);
2310 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002311 if (userKeySetting == null || userKeySetting.isNull()
2312 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002313 throw new IllegalStateException("User key not accessible");
2314 }
2315 }
2316 final String userKey = userKeySetting.getValue();
2317
2318 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002319 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2320
2321 // Validate that the key is of expected length.
2322 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2323 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002324 throw new IllegalStateException("User key invalid");
2325 }
2326
Mark Rathjen7599f132017-01-23 14:15:54 -08002327 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002328 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002329 m = Mac.getInstance("HmacSHA256");
2330 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002331 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002332 throw new IllegalStateException("HmacSHA256 is not available", e);
2333 } catch (InvalidKeyException e) {
2334 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002335 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002336
Mark Rathjenf42dd912017-06-05 19:04:34 -07002337 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002338 for (int i = 0; i < callingPkg.signatures.length; i++) {
2339 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002340 m.update(getLengthPrefix(sig), 0, 4);
2341 m.update(sig);
2342 }
Mark Rathjend891f012017-01-19 04:10:37 +00002343
2344 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002345 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2346 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002347
2348 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002349 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002350 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2351 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002352 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002353
2354 if (!success) {
2355 throw new IllegalStateException("Ssaid settings not accessible");
2356 }
2357
2358 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2359 }
2360
2361 public void syncSsaidTableOnStart() {
2362 synchronized (mLock) {
2363 // Verify that each user's packages and ssaid's are in sync.
2364 for (UserInfo user : mUserManager.getUsers(true)) {
2365 // Get all uids for the user's packages.
2366 final List<PackageInfo> packages;
2367 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002368 packages = mPackageManager.getInstalledPackages(
2369 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2370 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002371 } catch (RemoteException e) {
2372 throw new IllegalStateException("Package manager not available");
2373 }
2374 final Set<String> appUids = new HashSet<>();
2375 for (PackageInfo info : packages) {
2376 appUids.add(Integer.toString(info.applicationInfo.uid));
2377 }
2378
2379 // Get all uids currently stored in the user's ssaid table.
2380 final Set<String> ssaidUids = new HashSet<>(
2381 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2382 ssaidUids.remove(SSAID_USER_KEY);
2383
2384 // Perform a set difference for the appUids and ssaidUids.
2385 ssaidUids.removeAll(appUids);
2386
2387 // If there are ssaidUids left over they need to be removed from the table.
2388 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2389 user.id);
2390 for (String uid : ssaidUids) {
2391 ssaidSettings.deleteSettingLocked(uid);
2392 }
2393 }
2394 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002395 }
2396
Svetoslav683914b2015-01-15 14:22:26 -08002397 public List<String> getSettingsNamesLocked(int type, int userId) {
2398 final int key = makeKey(type, userId);
2399 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002400 if (settingsState == null) {
2401 return new ArrayList<String>();
2402 }
Svetoslav683914b2015-01-15 14:22:26 -08002403 return settingsState.getSettingNamesLocked();
2404 }
2405
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002406 public SparseBooleanArray getKnownUsersLocked() {
2407 SparseBooleanArray users = new SparseBooleanArray();
2408 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2409 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2410 }
2411 return users;
2412 }
2413
Kweku Adamsb0886f32017-10-31 15:32:09 -07002414 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002415 public SettingsState getSettingsLocked(int type, int userId) {
2416 final int key = makeKey(type, userId);
2417 return peekSettingsStateLocked(key);
2418 }
2419
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002420 public boolean ensureSettingsForUserLocked(int userId) {
2421 // First make sure this user actually exists.
2422 if (mUserManager.getUserInfo(userId) == null) {
2423 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2424 return false;
2425 }
2426
Svetoslav683914b2015-01-15 14:22:26 -08002427 // Migrate the setting for this user if needed.
2428 migrateLegacySettingsForUserIfNeededLocked(userId);
2429
Matt Pape1b31a332018-10-17 09:58:28 -07002430 // Ensure config settings loaded if owner.
2431 if (userId == UserHandle.USER_SYSTEM) {
2432 final int configKey
2433 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2434 ensureSettingsStateLocked(configKey);
2435 }
2436
Svetoslav683914b2015-01-15 14:22:26 -08002437 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002438 if (userId == UserHandle.USER_SYSTEM) {
2439 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002440 ensureSettingsStateLocked(globalKey);
2441 }
2442
2443 // Ensure secure settings loaded.
2444 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2445 ensureSettingsStateLocked(secureKey);
2446
2447 // Make sure the secure settings have an Android id set.
2448 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2449 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2450
2451 // Ensure system settings loaded.
2452 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2453 ensureSettingsStateLocked(systemKey);
2454
Mark Rathjend891f012017-01-19 04:10:37 +00002455 // Ensure secure settings loaded.
2456 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2457 ensureSettingsStateLocked(ssaidKey);
2458
Svetoslav683914b2015-01-15 14:22:26 -08002459 // Upgrade the settings to the latest version.
2460 UpgradeController upgrader = new UpgradeController(userId);
2461 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002462 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002463 }
2464
2465 private void ensureSettingsStateLocked(int key) {
2466 if (mSettingsStates.get(key) == null) {
2467 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002468 SettingsState settingsState = new SettingsState(getContext(), mLock,
2469 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002470 mSettingsStates.put(key, settingsState);
2471 }
2472 }
2473
2474 public void removeUserStateLocked(int userId, boolean permanently) {
2475 // We always keep the global settings in memory.
2476
2477 // Nuke system settings.
2478 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2479 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2480 if (systemSettingsState != null) {
2481 if (permanently) {
2482 mSettingsStates.remove(systemKey);
2483 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002484 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002485 systemSettingsState.destroyLocked(new Runnable() {
2486 @Override
2487 public void run() {
2488 mSettingsStates.remove(systemKey);
2489 }
2490 });
2491 }
2492 }
2493
2494 // Nuke secure settings.
2495 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2496 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2497 if (secureSettingsState != null) {
2498 if (permanently) {
2499 mSettingsStates.remove(secureKey);
2500 secureSettingsState.destroyLocked(null);
2501 } else {
2502 secureSettingsState.destroyLocked(new Runnable() {
2503 @Override
2504 public void run() {
2505 mSettingsStates.remove(secureKey);
2506 }
2507 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002508 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002509 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002510
Mark Rathjend891f012017-01-19 04:10:37 +00002511 // Nuke ssaid settings.
2512 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2513 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2514 if (ssaidSettingsState != null) {
2515 if (permanently) {
2516 mSettingsStates.remove(ssaidKey);
2517 ssaidSettingsState.destroyLocked(null);
2518 } else {
2519 ssaidSettingsState.destroyLocked(new Runnable() {
2520 @Override
2521 public void run() {
2522 mSettingsStates.remove(ssaidKey);
2523 }
2524 });
2525 }
2526 }
2527
Svet Ganov53a441c2016-04-19 19:38:00 -07002528 // Nuke generation tracking data
2529 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002530 }
2531
Svetoslav683914b2015-01-15 14:22:26 -08002532 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002533 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2534 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002535 final int key = makeKey(type, userId);
2536
Svetoslav Ganove080da92016-12-21 17:10:35 -08002537 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002538 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002539 if (settingsState != null) {
2540 success = settingsState.insertSettingLocked(name, value,
2541 tag, makeDefault, packageName);
2542 }
Svetoslav683914b2015-01-15 14:22:26 -08002543
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002544 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2545 settingsState.persistSyncLocked();
2546 }
2547
Svet Ganov53a441c2016-04-19 19:38:00 -07002548 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002549 notifyForSettingsChange(key, name);
2550 }
2551 return success;
2552 }
2553
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002554 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2555 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002556 final int key = makeKey(type, userId);
2557
Svetoslav Ganove080da92016-12-21 17:10:35 -08002558 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002559 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002560 if (settingsState != null) {
2561 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002562 }
Svetoslav683914b2015-01-15 14:22:26 -08002563
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002564 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2565 settingsState.persistSyncLocked();
2566 }
2567
Svet Ganov53a441c2016-04-19 19:38:00 -07002568 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002569 notifyForSettingsChange(key, name);
2570 }
2571 return success;
2572 }
2573
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002574 public boolean updateSettingLocked(int type, int userId, String name, String value,
2575 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2576 Set<String> criticalSettings) {
2577 final int key = makeKey(type, userId);
2578
2579 boolean success = false;
2580 SettingsState settingsState = peekSettingsStateLocked(key);
2581 if (settingsState != null) {
2582 success = settingsState.updateSettingLocked(name, value, tag,
2583 makeDefault, packageName);
2584 }
2585
2586 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2587 settingsState.persistSyncLocked();
2588 }
2589
2590 if (forceNotify || success) {
2591 notifyForSettingsChange(key, name);
2592 }
2593
2594 return success;
2595 }
2596
Svetoslav683914b2015-01-15 14:22:26 -08002597 public Setting getSettingLocked(int type, int userId, String name) {
2598 final int key = makeKey(type, userId);
2599
2600 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002601 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002602 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002603 }
Mark Rathjend891f012017-01-19 04:10:37 +00002604
2605 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002606 return settingsState.getSettingLocked(name);
2607 }
2608
Svetoslav Ganove080da92016-12-21 17:10:35 -08002609 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2610 String tag) {
2611 final int key = makeKey(type, userId);
2612 SettingsState settingsState = peekSettingsStateLocked(key);
2613 if (settingsState == null) {
2614 return;
2615 }
2616
2617 switch (mode) {
2618 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2619 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002620 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002621 Setting setting = settingsState.getSettingLocked(name);
2622 if (packageName.equals(setting.getPackageName())) {
2623 if (tag != null && !tag.equals(setting.getTag())) {
2624 continue;
2625 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002626 if (settingsState.resetSettingLocked(name)) {
2627 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002628 notifyForSettingsChange(key, name);
2629 }
2630 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002631 if (someSettingChanged) {
2632 settingsState.persistSyncLocked();
2633 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002634 }
2635 } break;
2636
2637 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2638 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002639 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002640 Setting setting = settingsState.getSettingLocked(name);
2641 if (!SettingsState.isSystemPackage(getContext(),
2642 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002643 if (settingsState.resetSettingLocked(name)) {
2644 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002645 notifyForSettingsChange(key, name);
2646 }
2647 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002648 if (someSettingChanged) {
2649 settingsState.persistSyncLocked();
2650 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002651 }
2652 } break;
2653
2654 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2655 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002656 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002657 Setting setting = settingsState.getSettingLocked(name);
2658 if (!SettingsState.isSystemPackage(getContext(),
2659 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002660 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002661 if (settingsState.resetSettingLocked(name)) {
2662 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002663 notifyForSettingsChange(key, name);
2664 }
2665 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002666 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002667 notifyForSettingsChange(key, name);
2668 }
2669 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002670 if (someSettingChanged) {
2671 settingsState.persistSyncLocked();
2672 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002673 }
2674 } break;
2675
2676 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2677 for (String name : settingsState.getSettingNamesLocked()) {
2678 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002679 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002680 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002681 if (settingsState.resetSettingLocked(name)) {
2682 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002683 notifyForSettingsChange(key, name);
2684 }
2685 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002686 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002687 notifyForSettingsChange(key, name);
2688 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002689 if (someSettingChanged) {
2690 settingsState.persistSyncLocked();
2691 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002692 }
2693 } break;
2694 }
2695 }
2696
Zimuzoc56192c2018-07-25 10:40:01 +01002697 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002698 // Global and secure settings are signature protected. Apps signed
2699 // by the platform certificate are generally not uninstalled and
2700 // the main exception is tests. We trust components signed
2701 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002702
2703 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2704 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002705 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002706 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002707 }
Svetoslav683914b2015-01-15 14:22:26 -08002708 }
2709
Mark Rathjend891f012017-01-19 04:10:37 +00002710 public void onUidRemovedLocked(int uid) {
2711 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2712 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002713 if (ssaidSettings != null) {
2714 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2715 }
Mark Rathjend891f012017-01-19 04:10:37 +00002716 }
2717
Kweku Adamsb0886f32017-10-31 15:32:09 -07002718 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002719 private SettingsState peekSettingsStateLocked(int key) {
2720 SettingsState settingsState = mSettingsStates.get(key);
2721 if (settingsState != null) {
2722 return settingsState;
2723 }
2724
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002725 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2726 return null;
2727 }
Svetoslav683914b2015-01-15 14:22:26 -08002728 return mSettingsStates.get(key);
2729 }
2730
2731 private void migrateAllLegacySettingsIfNeeded() {
2732 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002733 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002734 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002735 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002736 return;
2737 }
2738
Amith Yamasani39452022017-03-21 15:23:47 -07002739 mSettingsCreationBuildId = Build.ID;
2740
Svetoslav683914b2015-01-15 14:22:26 -08002741 final long identity = Binder.clearCallingIdentity();
2742 try {
2743 List<UserInfo> users = mUserManager.getUsers(true);
2744
2745 final int userCount = users.size();
2746 for (int i = 0; i < userCount; i++) {
2747 final int userId = users.get(i).id;
2748
2749 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2750 SQLiteDatabase database = dbHelper.getWritableDatabase();
2751 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2752
2753 // Upgrade to the latest version.
2754 UpgradeController upgrader = new UpgradeController(userId);
2755 upgrader.upgradeIfNeededLocked();
2756
2757 // Drop from memory if not a running user.
2758 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2759 removeUserStateLocked(userId, false);
2760 }
2761 }
2762 } finally {
2763 Binder.restoreCallingIdentity(identity);
2764 }
2765 }
2766 }
2767
2768 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2769 // Every user has secure settings and if no file we need to migrate.
2770 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2771 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002772 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002773 return;
2774 }
2775
2776 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2777 SQLiteDatabase database = dbHelper.getWritableDatabase();
2778
2779 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2780 }
2781
2782 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2783 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002784 // Move over the system settings.
2785 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2786 ensureSettingsStateLocked(systemKey);
2787 SettingsState systemSettings = mSettingsStates.get(systemKey);
2788 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2789 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002790
2791 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002792 // Do this after System settings, since this is the first thing we check when deciding
2793 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002794 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2795 ensureSettingsStateLocked(secureKey);
2796 SettingsState secureSettings = mSettingsStates.get(secureKey);
2797 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2798 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2799 secureSettings.persistSyncLocked();
2800
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002801 // Move over the global settings if owner.
2802 // Do this last, since this is the first thing we check when deciding
2803 // to skip over migration from db to xml for owner user.
2804 if (userId == UserHandle.USER_SYSTEM) {
2805 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2806 ensureSettingsStateLocked(globalKey);
2807 SettingsState globalSettings = mSettingsStates.get(globalKey);
2808 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002809 // If this was just created
2810 if (mSettingsCreationBuildId != null) {
2811 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2812 mSettingsCreationBuildId, null, true,
2813 SettingsState.SYSTEM_PACKAGE_NAME);
2814 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002815 globalSettings.persistSyncLocked();
2816 }
Svetoslav683914b2015-01-15 14:22:26 -08002817
2818 // Drop the database as now all is moved and persisted.
2819 if (DROP_DATABASE_ON_MIGRATION) {
2820 dbHelper.dropDatabase();
2821 } else {
2822 dbHelper.backupDatabase();
2823 }
2824 }
2825
2826 private void migrateLegacySettingsLocked(SettingsState settingsState,
2827 SQLiteDatabase database, String table) {
2828 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2829 queryBuilder.setTables(table);
2830
2831 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2832 null, null, null, null, null);
2833
2834 if (cursor == null) {
2835 return;
2836 }
2837
2838 try {
2839 if (!cursor.moveToFirst()) {
2840 return;
2841 }
2842
2843 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2844 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2845
2846 settingsState.setVersionLocked(database.getVersion());
2847
2848 while (!cursor.isAfterLast()) {
2849 String name = cursor.getString(nameColumnIdx);
2850 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002851 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002852 SettingsState.SYSTEM_PACKAGE_NAME);
2853 cursor.moveToNext();
2854 }
2855 } finally {
2856 cursor.close();
2857 }
2858 }
2859
Andreas Gampeb58893072018-09-05 16:52:31 -07002860 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002861 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2862 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2863
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002864 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002865 return;
2866 }
2867
2868 final int userId = getUserIdFromKey(secureSettings.mKey);
2869
2870 final UserInfo user;
2871 final long identity = Binder.clearCallingIdentity();
2872 try {
2873 user = mUserManager.getUserInfo(userId);
2874 } finally {
2875 Binder.restoreCallingIdentity(identity);
2876 }
2877 if (user == null) {
2878 // Can happen due to races when deleting users - treat as benign.
2879 return;
2880 }
2881
2882 String androidId = Long.toHexString(new SecureRandom().nextLong());
2883 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002884 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002885
2886 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2887 + "] for user " + userId);
2888
2889 // Write a drop box entry if it's a restricted profile
2890 if (user.isRestricted()) {
2891 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2892 Context.DROPBOX_SERVICE);
2893 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2894 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2895 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2896 }
2897 }
2898 }
2899
2900 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07002901 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07002902 mGenerationRegistry.incrementGeneration(key);
2903
Svet Ganov945864c2018-03-22 21:49:10 -07002904 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06002905 final long token = Binder.clearCallingIdentity();
2906 try {
2907 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2908 // When the global kill switch is updated, send the
2909 // change notification for the location setting.
2910 notifyLocationChangeForRunningUsers();
2911 }
2912 notifyGlobalSettingChangeForRunningUsers(key, name);
2913 } finally {
2914 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07002915 }
Svet Ganov945864c2018-03-22 21:49:10 -07002916 } else {
2917 final int userId = getUserIdFromKey(key);
2918 final Uri uri = getNotificationUriFor(key, name);
2919 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2920 userId, 0, uri).sendToTarget();
2921 if (isSecureSettingsKey(key)) {
2922 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2923 sSecureCloneToManagedSettings);
2924 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2925 sSystemCloneFromParentOnDependency.values());
2926 } else if (isSystemSettingsKey(key)) {
2927 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2928 sSystemCloneToManagedSettings);
2929 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002930 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002931
Svet Ganov945864c2018-03-22 21:49:10 -07002932 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07002933 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002934 }
2935
Svet Ganov53a441c2016-04-19 19:38:00 -07002936 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002937 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002938 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002939 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002940 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002941 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07002942 final int key = makeKey(type, profileId);
2943 // Increment the generation first, so observers always see the new value
2944 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07002945 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002946 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002947 }
2948 }
2949 }
Svetoslav683914b2015-01-15 14:22:26 -08002950 }
2951
Svet Ganov945864c2018-03-22 21:49:10 -07002952 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
2953 // Important: No need to update generation for each user as there
2954 // is a singleton generation entry for the global settings which
2955 // is already incremented be the caller.
2956 final Uri uri = getNotificationUriFor(key, name);
2957 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
2958 for (int i = 0; i < users.size(); i++) {
2959 final int userId = users.get(i).id;
2960 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
2961 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2962 userId, 0, uri).sendToTarget();
2963 }
2964 }
2965 }
2966
Makoto Onuki0000d322017-11-28 16:31:47 -08002967 private void notifyLocationChangeForRunningUsers() {
2968 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2969
2970 for (int i = 0; i < users.size(); i++) {
2971 final int userId = users.get(i).id;
2972
2973 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2974 continue;
2975 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002976
Svet Ganov945864c2018-03-22 21:49:10 -07002977 // Increment the generation first, so observers always see the new value
2978 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2979 mGenerationRegistry.incrementGeneration(key);
2980
2981 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08002982 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2983 userId, 0, uri).sendToTarget();
2984 }
2985 }
2986
Matt Pape1b31a332018-10-17 09:58:28 -07002987 private boolean isConfigSettingsKey(int key) {
2988 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
2989 }
2990
Svetoslav683914b2015-01-15 14:22:26 -08002991 private boolean isGlobalSettingsKey(int key) {
2992 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2993 }
2994
2995 private boolean isSystemSettingsKey(int key) {
2996 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2997 }
2998
2999 private boolean isSecureSettingsKey(int key) {
3000 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3001 }
3002
Mark Rathjend891f012017-01-19 04:10:37 +00003003 private boolean isSsaidSettingsKey(int key) {
3004 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3005 }
3006
Svetoslav683914b2015-01-15 14:22:26 -08003007 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003008 if (isConfigSettingsKey(key)) {
3009 final int userId = getUserIdFromKey(key);
3010 return new File(Environment.getUserSystemDirectory(userId),
3011 SETTINGS_FILE_CONFIG);
3012 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003013 final int userId = getUserIdFromKey(key);
3014 return new File(Environment.getUserSystemDirectory(userId),
3015 SETTINGS_FILE_GLOBAL);
3016 } else if (isSystemSettingsKey(key)) {
3017 final int userId = getUserIdFromKey(key);
3018 return new File(Environment.getUserSystemDirectory(userId),
3019 SETTINGS_FILE_SYSTEM);
3020 } else if (isSecureSettingsKey(key)) {
3021 final int userId = getUserIdFromKey(key);
3022 return new File(Environment.getUserSystemDirectory(userId),
3023 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003024 } else if (isSsaidSettingsKey(key)) {
3025 final int userId = getUserIdFromKey(key);
3026 return new File(Environment.getUserSystemDirectory(userId),
3027 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003028 } else {
3029 throw new IllegalArgumentException("Invalid settings key:" + key);
3030 }
3031 }
3032
3033 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003034 if (isConfigSettingsKey(key)) {
3035 return (name != null) ? Uri.withAppendedPath(CONFIG_CONTENT_URI, name)
3036 : CONFIG_CONTENT_URI;
3037 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003038 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3039 : Settings.Global.CONTENT_URI;
3040 } else if (isSecureSettingsKey(key)) {
3041 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3042 : Settings.Secure.CONTENT_URI;
3043 } else if (isSystemSettingsKey(key)) {
3044 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3045 : Settings.System.CONTENT_URI;
3046 } else {
3047 throw new IllegalArgumentException("Invalid settings key:" + key);
3048 }
3049 }
3050
3051 private int getMaxBytesPerPackageForType(int type) {
3052 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003053 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003054 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003055 case SETTINGS_TYPE_SECURE:
3056 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003057 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3058 }
3059
3060 default: {
3061 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3062 }
3063 }
3064 }
3065
Svetoslav7e0683b2015-08-03 16:02:52 -07003066 private final class MyHandler extends Handler {
3067 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3068 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3069
3070 public MyHandler(Looper looper) {
3071 super(looper);
3072 }
3073
3074 @Override
3075 public void handleMessage(Message msg) {
3076 switch (msg.what) {
3077 case MSG_NOTIFY_URI_CHANGED: {
3078 final int userId = msg.arg1;
3079 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003080 try {
3081 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3082 } catch (SecurityException e) {
3083 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3084 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003085 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003086 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3087 }
3088 } break;
3089
3090 case MSG_NOTIFY_DATA_CHANGED: {
3091 mBackupManager.dataChanged();
3092 } break;
3093 }
3094 }
3095 }
3096
Svetoslav683914b2015-01-15 14:22:26 -08003097 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003098 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003099
3100 private final int mUserId;
3101
3102 public UpgradeController(int userId) {
3103 mUserId = userId;
3104 }
3105
3106 public void upgradeIfNeededLocked() {
3107 // The version of all settings for a user is the same (all users have secure).
3108 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003109 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003110
3111 // Try an update from the current state.
3112 final int oldVersion = secureSettings.getVersionLocked();
3113 final int newVersion = SETTINGS_VERSION;
3114
Svet Ganovc9755bc2015-03-28 13:21:22 -07003115 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003116 if (oldVersion == newVersion) {
3117 return;
3118 }
3119
3120 // Try to upgrade.
3121 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3122
3123 // If upgrade failed start from scratch and upgrade.
3124 if (curVersion != newVersion) {
3125 // Drop state we have for this user.
3126 removeUserStateLocked(mUserId, true);
3127
3128 // Recreate the database.
3129 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3130 SQLiteDatabase database = dbHelper.getWritableDatabase();
3131 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3132
3133 // Migrate the settings for this user.
3134 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3135
3136 // Now upgrade should work fine.
3137 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003138
3139 // Make a note what happened, so we don't wonder why data was lost
3140 String reason = "Settings rebuilt! Current version: "
3141 + curVersion + " while expected: " + newVersion;
3142 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003143 Settings.Global.DATABASE_DOWNGRADE_REASON,
3144 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003145 }
3146
3147 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003148 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003149 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003150 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003151 globalSettings.setVersionLocked(newVersion);
3152 }
3153
3154 // Set the secure settings version.
3155 secureSettings.setVersionLocked(newVersion);
3156
3157 // Set the system settings version.
3158 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003159 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003160 systemSettings.setVersionLocked(newVersion);
3161 }
3162
3163 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003164 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003165 }
3166
3167 private SettingsState getSecureSettingsLocked(int userId) {
3168 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3169 }
3170
Mark Rathjend891f012017-01-19 04:10:37 +00003171 private SettingsState getSsaidSettingsLocked(int userId) {
3172 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3173 }
3174
Svetoslav683914b2015-01-15 14:22:26 -08003175 private SettingsState getSystemSettingsLocked(int userId) {
3176 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3177 }
3178
Jeff Brown503cffc2015-03-26 18:08:51 -07003179 /**
3180 * You must perform all necessary mutations to bring the settings
3181 * for this user from the old to the new version. When you add a new
3182 * upgrade step you *must* update SETTINGS_VERSION.
3183 *
3184 * This is an example of moving a setting from secure to global.
3185 *
3186 * // v119: Example settings changes.
3187 * if (currentVersion == 118) {
3188 * if (userId == UserHandle.USER_OWNER) {
3189 * // Remove from the secure settings.
3190 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3191 * String name = "example_setting_to_move";
3192 * String value = secureSettings.getSetting(name);
3193 * secureSettings.deleteSetting(name);
3194 *
3195 * // Add to the global settings.
3196 * SettingsState globalSettings = getGlobalSettingsLocked();
3197 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3198 * }
3199 *
3200 * // Update the current version.
3201 * currentVersion = 119;
3202 * }
3203 */
Svetoslav683914b2015-01-15 14:22:26 -08003204 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3205 if (DEBUG) {
3206 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3207 + oldVersion + " to version: " + newVersion);
3208 }
3209
Jeff Brown503cffc2015-03-26 18:08:51 -07003210 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003211
John Spurlocke11ae112015-05-11 16:09:03 -04003212 // v119: Reset zen + ringer mode.
3213 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003214 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003215 final SettingsState globalSettings = getGlobalSettingsLocked();
3216 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003217 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3218 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003219 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003220 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3221 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003222 }
3223 currentVersion = 119;
3224 }
3225
Jason Monk27bbb2d2015-03-31 16:46:39 -04003226 // v120: Add double tap to wake setting.
3227 if (currentVersion == 119) {
3228 SettingsState secureSettings = getSecureSettingsLocked(userId);
3229 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3230 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003231 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003232 SettingsState.SYSTEM_PACKAGE_NAME);
3233
3234 currentVersion = 120;
3235 }
3236
Svetoslav7e0683b2015-08-03 16:02:52 -07003237 if (currentVersion == 120) {
3238 // Before 121, we used a different string encoding logic. We just bump the
3239 // version here; SettingsState knows how to handle pre-version 120 files.
3240 currentVersion = 121;
3241 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003242
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003243 if (currentVersion == 121) {
3244 // Version 122: allow OEMs to set a default payment component in resources.
3245 // Note that we only write the default if no default has been set;
3246 // if there is, we just leave the default at whatever it currently is.
3247 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3248 String defaultComponent = (getContext().getResources().getString(
3249 R.string.def_nfc_payment_component));
3250 Setting currentSetting = secureSettings.getSettingLocked(
3251 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3252 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003253 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003254 secureSettings.insertSettingLocked(
3255 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003256 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003257 }
3258 currentVersion = 122;
3259 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003260
3261 if (currentVersion == 122) {
3262 // Version 123: Adding a default value for the ability to add a user from
3263 // the lock screen.
3264 if (userId == UserHandle.USER_SYSTEM) {
3265 final SettingsState globalSettings = getGlobalSettingsLocked();
3266 Setting currentSetting = globalSettings.getSettingLocked(
3267 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003268 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003269 globalSettings.insertSettingLocked(
3270 Settings.Global.ADD_USERS_WHEN_LOCKED,
3271 getContext().getResources().getBoolean(
3272 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003273 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003274 }
3275 }
3276 currentVersion = 123;
3277 }
Bryce Leebd179282015-12-17 19:01:37 -08003278
3279 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003280 final SettingsState globalSettings = getGlobalSettingsLocked();
3281 String defaultDisabledProfiles = (getContext().getResources().getString(
3282 R.string.def_bluetooth_disabled_profiles));
3283 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003284 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003285 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003286 }
3287
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003288 if (currentVersion == 124) {
3289 // Version 124: allow OEMs to set a default value for whether IME should be
3290 // shown when a physical keyboard is connected.
3291 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3292 Setting currentSetting = secureSettings.getSettingLocked(
3293 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003294 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003295 secureSettings.insertSettingLocked(
3296 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3297 getContext().getResources().getBoolean(
3298 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003299 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003300 }
3301 currentVersion = 125;
3302 }
3303
Ruben Brunk98576cf2016-03-07 18:54:28 -08003304 if (currentVersion == 125) {
3305 // Version 125: Allow OEMs to set the default VR service.
3306 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3307
3308 Setting currentSetting = secureSettings.getSettingLocked(
3309 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003310 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003311 ArraySet<ComponentName> l =
3312 SystemConfig.getInstance().getDefaultVrComponents();
3313
3314 if (l != null && !l.isEmpty()) {
3315 StringBuilder b = new StringBuilder();
3316 boolean start = true;
3317 for (ComponentName c : l) {
3318 if (!start) {
3319 b.append(':');
3320 }
3321 b.append(c.flattenToString());
3322 start = false;
3323 }
3324 secureSettings.insertSettingLocked(
3325 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003326 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003327 }
3328
3329 }
3330 currentVersion = 126;
3331 }
3332
Daniel U02ba6122016-04-01 18:41:42 +01003333 if (currentVersion == 126) {
3334 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3335 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3336 if (mUserManager.isManagedProfile(userId)) {
3337 final SettingsState systemSecureSettings =
3338 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3339
3340 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3341 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003342 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003343 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3344 secureSettings.insertSettingLocked(
3345 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003346 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003347 SettingsState.SYSTEM_PACKAGE_NAME);
3348 }
3349
3350 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3351 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003352 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003353 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3354 secureSettings.insertSettingLocked(
3355 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003356 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003357 SettingsState.SYSTEM_PACKAGE_NAME);
3358 }
3359 }
3360 currentVersion = 127;
3361 }
3362
Steven Ngdc20ba62016-04-26 18:19:04 +01003363 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003364 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003365 currentVersion = 128;
3366 }
3367
Julia Reynolds1f721e12016-07-11 08:50:58 -04003368 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003369 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003370 currentVersion = 129;
3371 }
3372
Dan Sandler71f85e92016-07-20 13:46:05 -04003373 if (currentVersion == 129) {
3374 // default longpress timeout changed from 500 to 400. If unchanged from the old
3375 // default, update to the new default.
3376 final SettingsState systemSecureSettings =
3377 getSecureSettingsLocked(userId);
3378 final String oldValue = systemSecureSettings.getSettingLocked(
3379 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3380 if (TextUtils.equals("500", oldValue)) {
3381 systemSecureSettings.insertSettingLocked(
3382 Settings.Secure.LONG_PRESS_TIMEOUT,
3383 String.valueOf(getContext().getResources().getInteger(
3384 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003385 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003386 }
3387 currentVersion = 130;
3388 }
3389
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003390 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003391 // Split Ambient settings
3392 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3393 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3394 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3395
3396 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003397 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003398 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003399 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003400 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003401 }
3402 currentVersion = 131;
3403 }
3404
3405 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003406 // Initialize new multi-press timeout to default value
3407 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3408 final String oldValue = systemSecureSettings.getSettingLocked(
3409 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3410 if (TextUtils.equals(null, oldValue)) {
3411 systemSecureSettings.insertSettingLocked(
3412 Settings.Secure.MULTI_PRESS_TIMEOUT,
3413 String.valueOf(getContext().getResources().getInteger(
3414 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003415 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003416 }
3417
Adrian Roos69741a22016-10-21 14:49:17 -07003418 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003419 }
3420
Adrian Roos69741a22016-10-21 14:49:17 -07003421 if (currentVersion == 132) {
3422 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003423 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3424 String defaultSyncParentSounds = (getContext().getResources()
3425 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3426 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003427 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3428 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003429 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003430 }
3431
Adrian Roos69741a22016-10-21 14:49:17 -07003432 if (currentVersion == 133) {
3433 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003434 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003435 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3436 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003437 String defaultEndButtonBehavior = Integer.toString(getContext()
3438 .getResources().getInteger(R.integer.def_end_button_behavior));
3439 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003440 defaultEndButtonBehavior, null, true,
3441 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003442 }
Adrian Roos69741a22016-10-21 14:49:17 -07003443 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003444 }
3445
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003446 if (currentVersion == 134) {
3447 // Remove setting that specifies if magnification values should be preserved.
3448 // This setting defaulted to true and never has a UI.
3449 getSecureSettingsLocked(userId).deleteSettingLocked(
3450 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3451 currentVersion = 135;
3452 }
3453
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003454 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003455 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003456 currentVersion = 136;
3457 }
3458
Mark Rathjend891f012017-01-19 04:10:37 +00003459 if (currentVersion == 136) {
3460 // Version 136: Store legacy SSAID for all apps currently installed on the
3461 // device as first step in migrating SSAID to be unique per application.
3462
3463 final boolean isUpgrade;
3464 try {
3465 isUpgrade = mPackageManager.isUpgrade();
3466 } catch (RemoteException e) {
3467 throw new IllegalStateException("Package manager not available");
3468 }
3469 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3470 // user data or first boot on a new device should use new ssaid generation.
3471 if (isUpgrade) {
3472 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003473 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3474 userId, Settings.Secure.ANDROID_ID);
3475 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3476 || legacySsaidSetting.getValue() == null) {
3477 throw new IllegalStateException("Legacy ssaid not accessible");
3478 }
3479 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003480
3481 // Fill each uid with the legacy ssaid to be backwards compatible.
3482 final List<PackageInfo> packages;
3483 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003484 packages = mPackageManager.getInstalledPackages(
3485 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3486 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003487 } catch (RemoteException e) {
3488 throw new IllegalStateException("Package manager not available");
3489 }
3490
3491 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3492 for (PackageInfo info : packages) {
3493 // Check if the UID already has an entry in the table.
3494 final String uid = Integer.toString(info.applicationInfo.uid);
3495 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3496
3497 if (ssaid.isNull() || ssaid.getValue() == null) {
3498 // Android Id doesn't exist for this package so create it.
3499 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3500 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003501 if (DEBUG) {
3502 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3503 }
Mark Rathjend891f012017-01-19 04:10:37 +00003504 }
3505 }
3506 }
3507
3508 currentVersion = 137;
3509 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003510 if (currentVersion == 137) {
3511 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3512 // default value set to 1. The user can no longer change the value of this
3513 // setting through the UI.
3514 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3515 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003516 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3517 && secureSetting.getSettingLocked(
3518 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3519
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003520 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3521 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003522 // For managed profiles with profile owners, DevicePolicyManagerService
3523 // may want to set the user restriction in this case
3524 secureSetting.insertSettingLocked(
3525 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3526 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003527 }
3528 currentVersion = 138;
3529 }
Mark Rathjend891f012017-01-19 04:10:37 +00003530
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003531 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003532 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003533 currentVersion = 139;
3534 }
3535
Phil Weaver385912e2017-02-10 10:06:56 -08003536 if (currentVersion == 139) {
3537 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3538 // the user can no longer change the value of this setting through the UI.
3539 // Force to true.
3540 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3541 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3542 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3543 currentVersion = 140;
3544 }
3545
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003546 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003547 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003548 currentVersion = 141;
3549 }
3550
Svet Ganov13701552017-02-23 12:45:17 -08003551 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003552 // This implementation was incorrectly setting the current value of
3553 // settings changed by non-system packages as the default which default
3554 // is set by the system. We add a new upgrade step at the end to properly
3555 // handle this case which would also fix incorrect changes made by the
3556 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003557 currentVersion = 142;
3558 }
3559
Stephen Chen5d0922f2017-03-27 10:28:04 -07003560 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003561 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003562 if (userId == UserHandle.USER_SYSTEM) {
3563 final SettingsState globalSettings = getGlobalSettingsLocked();
3564 Setting currentSetting = globalSettings.getSettingLocked(
3565 Settings.Global.WIFI_WAKEUP_ENABLED);
3566 if (currentSetting.isNull()) {
3567 globalSettings.insertSettingLocked(
3568 Settings.Global.WIFI_WAKEUP_ENABLED,
3569 getContext().getResources().getBoolean(
3570 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3571 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3572 }
3573 }
3574
3575 currentVersion = 143;
3576 }
3577
Felipe Lemeff355092017-04-03 12:55:02 -07003578 if (currentVersion == 143) {
3579 // Version 144: Set a default value for Autofill service.
3580 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3581 final Setting currentSetting = secureSettings
3582 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3583 if (currentSetting.isNull()) {
3584 final String defaultValue = getContext().getResources().getString(
3585 com.android.internal.R.string.config_defaultAutofillService);
3586 if (defaultValue != null) {
3587 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3588 + "for user " + userId);
3589 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3590 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3591 }
3592 }
3593
3594 currentVersion = 144;
3595 }
3596
Jeremy Joslin45caa252017-05-04 11:22:46 -07003597 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003598 // Version 145: Removed
3599 currentVersion = 145;
3600 }
3601
3602 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003603 // Version 146: In step 142 we had a bug where incorrectly
3604 // some settings were considered system set and as a result
3605 // made the default and marked as the default being set by
3606 // the system. Here reevaluate the default and default system
3607 // set flags. This would both fix corruption by the old impl
3608 // of step 142 and also properly handle devices which never
3609 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003610 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003611 SettingsState globalSettings = getGlobalSettingsLocked();
3612 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3613 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003614 }
3615
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003616 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3617 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3618 secureSettings.persistSyncLocked();
3619
3620 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3621 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3622 systemSettings.persistSyncLocked();
3623
Amin Shaikh86367962017-06-07 08:58:22 -07003624 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003625 }
3626
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003627 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003628 // Version 147: Removed. (This version previously allowed showing the
3629 // "wifi_wakeup_available" setting).
3630 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003631 currentVersion = 147;
3632 }
3633
3634 if (currentVersion == 147) {
3635 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003636 if (userId == UserHandle.USER_SYSTEM) {
3637 final SettingsState globalSettings = getGlobalSettingsLocked();
3638 final Setting currentSetting = globalSettings.getSettingLocked(
3639 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3640 if (currentSetting.isNull()) {
3641 globalSettings.insertSettingLocked(
3642 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3643 getContext().getResources().getBoolean(
3644 R.bool.def_restrict_background_data) ? "1" : "0",
3645 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3646 }
3647 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003648 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003649 }
3650
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003651 if (currentVersion == 148) {
3652 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3653 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3654 final String oldValue = systemSecureSettings.getSettingLocked(
3655 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3656 if (TextUtils.equals(null, oldValue)) {
3657 final String defaultValue = getContext().getResources().getString(
3658 R.string.def_backup_manager_constants);
3659 if (!TextUtils.isEmpty(defaultValue)) {
3660 systemSecureSettings.insertSettingLocked(
3661 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3662 true, SettingsState.SYSTEM_PACKAGE_NAME);
3663 }
3664 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003665 currentVersion = 149;
3666 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003667
3668 if (currentVersion == 149) {
3669 // Version 150: Set a default value for mobile data always on
3670 final SettingsState globalSettings = getGlobalSettingsLocked();
3671 final Setting currentSetting = globalSettings.getSettingLocked(
3672 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3673 if (currentSetting.isNull()) {
3674 globalSettings.insertSettingLocked(
3675 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3676 getContext().getResources().getBoolean(
3677 R.bool.def_mobile_data_always_on) ? "1" : "0",
3678 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3679 }
3680
3681 currentVersion = 150;
3682 }
3683
Mike Digman4af4a6f2018-01-16 14:49:38 -08003684 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003685 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003686 currentVersion = 151;
3687 }
3688
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003689 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003690 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3691 // by default but it is now no longer configurable).
3692 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003693 currentVersion = 152;
3694 }
3695
Joe LaPenna250d7842018-01-25 10:19:42 -08003696 if (currentVersion == 152) {
3697 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3698 currentVersion = 153;
3699 }
3700
Ben Linb4df8bc2018-01-29 11:48:20 -08003701 if (currentVersion == 153) {
3702 // Version 154: Read notification badge configuration from config.
3703 // If user has already set the value, don't do anything.
3704 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3705 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3706 Settings.Secure.NOTIFICATION_BADGING);
3707 if (showNotificationBadges.isNull()) {
3708 final boolean defaultValue = getContext().getResources().getBoolean(
3709 com.android.internal.R.bool.config_notificationBadging);
3710 systemSecureSettings.insertSettingLocked(
3711 Secure.NOTIFICATION_BADGING,
3712 defaultValue ? "1" : "0",
3713 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3714 }
3715 currentVersion = 154;
3716 }
3717
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003718 if (currentVersion == 154) {
3719 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3720 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3721 final String oldValue = systemSecureSettings.getSettingLocked(
3722 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3723 if (TextUtils.equals(null, oldValue)) {
3724 final String defaultValue = getContext().getResources().getString(
3725 R.string.def_backup_local_transport_parameters);
3726 if (!TextUtils.isEmpty(defaultValue)) {
3727 systemSecureSettings.insertSettingLocked(
3728 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3729 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3730 }
3731
3732 }
3733 currentVersion = 155;
3734 }
3735
Beverlyda904812018-03-02 09:55:30 -05003736 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003737 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003738 final SettingsState globalSettings = getGlobalSettingsLocked();
3739 final String oldValue = globalSettings.getSettingLocked(
3740 Global.CHARGING_STARTED_SOUND).getValue();
3741 final String oldDefault = getContext().getResources().getString(
3742 R.string.def_wireless_charging_started_sound);
3743 if (TextUtils.equals(null, oldValue)
3744 || TextUtils.equals(oldValue, oldDefault)) {
3745 final String defaultValue = getContext().getResources().getString(
3746 R.string.def_charging_started_sound);
3747 if (!TextUtils.isEmpty(defaultValue)) {
3748 globalSettings.insertSettingLocked(
3749 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3750 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3751 }
3752
3753 }
3754 currentVersion = 156;
3755 }
3756
Beverly09da25f2018-02-26 09:17:07 -05003757 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003758 // Version 157: Set a default value for zen duration,
3759 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003760 final SettingsState globalSettings = getGlobalSettingsLocked();
3761 final Setting currentSetting = globalSettings.getSettingLocked(
3762 Global.ZEN_DURATION);
3763 if (currentSetting.isNull()) {
3764 String defaultZenDuration = Integer.toString(getContext()
3765 .getResources().getInteger(R.integer.def_zen_duration));
3766 globalSettings.insertSettingLocked(
3767 Global.ZEN_DURATION, defaultZenDuration,
3768 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3769 }
Beverly09da25f2018-02-26 09:17:07 -05003770 currentVersion = 157;
3771 }
Annie Mengd069a882018-03-13 15:31:40 +00003772
3773 if (currentVersion == 157) {
3774 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3775 final SettingsState globalSettings = getGlobalSettingsLocked();
3776 final String oldValue = globalSettings.getSettingLocked(
3777 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3778 if (TextUtils.equals(null, oldValue)) {
3779 final String defaultValue = getContext().getResources().getString(
3780 R.string.def_backup_agent_timeout_parameters);
3781 if (!TextUtils.isEmpty(defaultValue)) {
3782 globalSettings.insertSettingLocked(
3783 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3784 null, true,
3785 SettingsState.SYSTEM_PACKAGE_NAME);
3786 }
3787 }
3788 currentVersion = 158;
3789 }
Roshan Pius9c396672018-03-02 14:54:13 -08003790
3791 if (currentVersion == 158) {
3792 // Remove setting that specifies wifi bgscan throttling params
3793 getGlobalSettingsLocked().deleteSettingLocked(
3794 "wifi_scan_background_throttle_interval_ms");
3795 getGlobalSettingsLocked().deleteSettingLocked(
3796 "wifi_scan_background_throttle_package_whitelist");
3797 currentVersion = 159;
3798 }
3799
Pavel Grafovc5c97302018-03-19 13:37:15 +00003800 if (currentVersion == 159) {
3801 // Version 160: Hiding notifications from the lockscreen is only available as
3802 // primary user option, profiles can only make them redacted. If a profile was
3803 // configured to not show lockscreen notifications, ensure that at the very
3804 // least these will be come hidden.
3805 if (mUserManager.isManagedProfile(userId)) {
3806 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3807 Setting showNotifications = secureSettings.getSettingLocked(
3808 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3809 // The default value is "1", check if user has turned it off.
3810 if ("0".equals(showNotifications.getValue())) {
3811 secureSettings.insertSettingLocked(
3812 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3813 null /* tag */, false /* makeDefault */,
3814 SettingsState.SYSTEM_PACKAGE_NAME);
3815 }
3816 // The setting is no longer valid for managed profiles, it should be
3817 // treated as if it was set to "1".
3818 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3819 }
3820 currentVersion = 160;
3821 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003822
3823 if (currentVersion == 160) {
3824 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003825 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003826 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3827 final SettingsState globalSettings = getGlobalSettingsLocked();
3828
3829 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003830 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3831 if (TextUtils.equals(null, oldValue)) {
3832 globalSettings.insertSettingLocked(
3833 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3834 Integer.toString(getContext().getResources().getInteger(
3835 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3836 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3837 }
3838
3839 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003840 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3841 if (TextUtils.equals(null, oldValue)) {
3842 globalSettings.insertSettingLocked(
3843 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3844 Integer.toString(getContext().getResources().getInteger(
3845 R.integer.def_sound_trigger_detection_service_op_timeout)),
3846 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3847 }
3848 currentVersion = 161;
3849 }
3850
Mike Digman55272862018-02-20 14:35:17 -08003851 if (currentVersion == 161) {
3852 // Version 161: Add a gesture for silencing phones
3853 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3854 final Setting currentSetting = secureSettings.getSettingLocked(
3855 Secure.VOLUME_HUSH_GESTURE);
3856 if (currentSetting.isNull()) {
3857 secureSettings.insertSettingLocked(
3858 Secure.VOLUME_HUSH_GESTURE,
3859 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3860 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3861 }
3862
3863 currentVersion = 162;
3864 }
3865
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003866 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003867 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003868 currentVersion = 163;
3869 }
3870
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003871 if (currentVersion == 163) {
3872 // Version 163: Update default value of
3873 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3874 final SettingsState settings = getGlobalSettingsLocked();
3875 final Setting currentSetting = settings.getSettingLocked(
3876 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3877 if (currentSetting.isDefaultFromSystem()) {
3878 settings.insertSettingLocked(
3879 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3880 Integer.toString(getContext().getResources().getInteger(
3881 R.integer
3882 .def_max_sound_trigger_detection_service_ops_per_day)),
3883 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3884 }
3885
3886 currentVersion = 164;
3887 }
3888
Julia Reynolds76bfa602018-04-23 09:38:47 -04003889 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003890 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003891 currentVersion = 165;
3892 }
3893
Beverly301e92a2018-04-27 09:43:05 -04003894 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003895 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3896 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003897 currentVersion = 166;
3898 }
3899
Beverly38fcfd02018-05-18 17:33:40 -04003900 if (currentVersion == 166) {
3901 // Version 166: add default values for hush gesture used and manual ringer
3902 // toggle
3903 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3904 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3905 Secure.HUSH_GESTURE_USED);
3906 if (currentHushUsedSetting.isNull()) {
3907 secureSettings.insertSettingLocked(
3908 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
3909 SettingsState.SYSTEM_PACKAGE_NAME);
3910 }
3911
3912 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
3913 Secure.MANUAL_RINGER_TOGGLE_COUNT);
3914 if (currentRingerToggleCountSetting.isNull()) {
3915 secureSettings.insertSettingLocked(
3916 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
3917 SettingsState.SYSTEM_PACKAGE_NAME);
3918 }
3919 currentVersion = 167;
3920 }
3921
Beverly155c9d22018-05-23 18:03:23 -04003922 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04003923 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
3924 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04003925 currentVersion = 168;
3926 }
3927
Michael Wright0e9eeee2018-05-26 00:31:20 +01003928 if (currentVersion == 168) {
3929 // Version 168: by default, vibrate for phone calls
3930 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3931 final Setting currentSetting = systemSettings.getSettingLocked(
3932 Settings.System.VIBRATE_WHEN_RINGING);
3933 if (currentSetting.isNull()) {
3934 systemSettings.insertSettingLocked(
3935 Settings.System.VIBRATE_WHEN_RINGING,
3936 getContext().getResources().getBoolean(
3937 R.bool.def_vibrate_when_ringing) ? "1" : "0",
3938 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3939 }
3940 currentVersion = 169;
3941 }
3942
Nadav Barf9f115d2018-06-24 10:06:50 +03003943 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04003944 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
3945 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
3946 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03003947
Beverly91d0a632018-07-02 16:45:00 -04003948 final SettingsState globalSettings = getGlobalSettingsLocked();
3949 final Setting globalZenDuration = globalSettings.getSettingLocked(
3950 Global.ZEN_DURATION);
3951
3952 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3953 final Setting secureZenDuration = secureSettings.getSettingLocked(
3954 Secure.ZEN_DURATION);
3955
3956 // ZEN_DURATION
3957 if (!globalZenDuration.isNull()) {
3958 secureSettings.insertSettingLocked(
3959 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
3960 SettingsState.SYSTEM_PACKAGE_NAME);
3961
3962 // set global zen duration setting to null since it's deprecated
3963 globalSettings.insertSettingLocked(
3964 Global.ZEN_DURATION, null, null, true,
3965 SettingsState.SYSTEM_PACKAGE_NAME);
3966 } else if (secureZenDuration.isNull()) {
3967 String defaultZenDuration = Integer.toString(getContext()
3968 .getResources().getInteger(R.integer.def_zen_duration));
3969 secureSettings.insertSettingLocked(
3970 Secure.ZEN_DURATION, defaultZenDuration, null, true,
3971 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03003972 }
Beverly91d0a632018-07-02 16:45:00 -04003973
3974 // SHOW_ZEN_SETTINGS_SUGGESTION
3975 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
3976 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
3977 if (currentShowZenSettingSuggestion.isNull()) {
3978 secureSettings.insertSettingLocked(
3979 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
3980 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3981 }
3982
3983 // ZEN_SETTINGS_UPDATED
3984 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
3985 Secure.ZEN_SETTINGS_UPDATED);
3986 if (currentUpdatedSetting.isNull()) {
3987 secureSettings.insertSettingLocked(
3988 Secure.ZEN_SETTINGS_UPDATED, "0",
3989 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3990 }
3991
3992 // ZEN_SETTINGS_SUGGESTION_VIEWED
3993 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
3994 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
3995 if (currentSettingSuggestionViewed.isNull()) {
3996 secureSettings.insertSettingLocked(
3997 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
3998 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3999 }
4000
Nadav Barf9f115d2018-06-24 10:06:50 +03004001 currentVersion = 170;
4002 }
4003
Beverly91d0a632018-07-02 16:45:00 -04004004 if (currentVersion == 170) {
4005 // Version 170: Set the default value for Secure Settings:
4006 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4007
4008 final SettingsState globalSettings = getGlobalSettingsLocked();
4009 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4010
4011 // CHARGING_SOUNDS_ENABLED
4012 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4013 Global.CHARGING_SOUNDS_ENABLED);
4014 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4015 Secure.CHARGING_SOUNDS_ENABLED);
4016
4017 if (!globalChargingSoundEnabled.isNull()) {
4018 secureSettings.insertSettingLocked(
4019 Secure.CHARGING_SOUNDS_ENABLED,
4020 globalChargingSoundEnabled.getValue(), null, false,
4021 SettingsState.SYSTEM_PACKAGE_NAME);
4022
4023 // set global charging_sounds_enabled setting to null since it's deprecated
4024 globalSettings.insertSettingLocked(
4025 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4026 SettingsState.SYSTEM_PACKAGE_NAME);
4027 } else if (secureChargingSoundsEnabled.isNull()) {
4028 String defChargingSoundsEnabled = getContext().getResources()
4029 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4030 secureSettings.insertSettingLocked(
4031 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4032 true, SettingsState.SYSTEM_PACKAGE_NAME);
4033 }
4034
4035 // CHARGING_VIBRATION_ENABLED
4036 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4037 Secure.CHARGING_VIBRATION_ENABLED);
4038
4039 if (secureChargingVibrationEnabled.isNull()) {
4040 String defChargingVibrationEnabled = getContext().getResources()
4041 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4042 secureSettings.insertSettingLocked(
4043 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4044 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4045 }
4046
4047 currentVersion = 171;
4048 }
4049
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004050 if (currentVersion == 171) {
4051 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4052 // be muted.
4053 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4054 final Setting currentSetting = systemSettings.getSettingLocked(
4055 Settings.System.MUTE_STREAMS_AFFECTED);
4056 if (!currentSetting.isNull()) {
4057 try {
4058 int currentSettingIntegerValue = Integer.parseInt(
4059 currentSetting.getValue());
4060 if ((currentSettingIntegerValue
4061 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4062 systemSettings.insertSettingLocked(
4063 Settings.System.MUTE_STREAMS_AFFECTED,
4064 Integer.toString(
4065 currentSettingIntegerValue
4066 | (1 << AudioManager.STREAM_VOICE_CALL)),
4067 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4068 }
4069 } catch (NumberFormatException e) {
4070 // remove the setting in case it is not a valid integer
4071 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4072 + "setting, removing setting", e);
4073 systemSettings.deleteSettingLocked(
4074 Settings.System.MUTE_STREAMS_AFFECTED);
4075 }
4076
4077 }
4078 currentVersion = 172;
4079 }
4080
Felipe Lemeff355092017-04-03 12:55:02 -07004081 // vXXX: Add new settings above this point.
4082
Dan Sandler71f85e92016-07-20 13:46:05 -04004083 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004084 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004085 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004086 + currentVersion +
4087 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4088 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004089 if (DEBUG) {
4090 throw new RuntimeException("db upgrade error");
4091 }
4092 }
4093
Jeff Brown503cffc2015-03-26 18:08:51 -07004094 // Return the current version.
4095 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004096 }
4097 }
Svet Ganov13701552017-02-23 12:45:17 -08004098
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004099 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4100 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004101 List<String> names = settings.getSettingNamesLocked();
4102 final int nameCount = names.size();
4103 for (int i = 0; i < nameCount; i++) {
4104 String name = names.get(i);
4105 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004106
4107 // In the upgrade case we pretend the call is made from the app
4108 // that made the last change to the setting to properly determine
4109 // whether the call has been made by a system component.
4110 int callingUid = -1;
4111 try {
4112 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4113 } catch (RemoteException e) {
4114 /* ignore - handled below */
4115 }
4116 if (callingUid < 0) {
4117 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4118 continue;
4119 }
4120 try {
4121 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4122 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004123 if (systemSet) {
4124 settings.insertSettingLocked(name, setting.getValue(),
4125 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004126 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4127 // We had a bug where changes by non-system packages were marked
4128 // as system made and as a result set as the default. Therefore, if
4129 // the package changed the setting last is not a system one but the
4130 // setting is marked as its default coming from the system we clear
4131 // the default and clear the system set flag.
4132 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004133 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004134 } catch (IllegalStateException e) {
4135 // If the package goes over its quota during the upgrade, don't
4136 // crash but just log the error as the system does the upgrade.
4137 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4138
Svet Ganov13701552017-02-23 12:45:17 -08004139 }
4140 }
4141 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004142 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004143}