blob: 256ebbb6e2a9573a1eab079ba63f9a1e3e86db10 [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
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700188 // Overlay specified settings whitelisted for Instant Apps
189 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
190 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
191 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
192
Matt Pape1b31a332018-10-17 09:58:28 -0700193 /**
194 * TODO(b/113100523): Move this to DeviceConfig.java when it is added, and expose it as a System
195 * API.
196 */
197 private static final Uri CONFIG_CONTENT_URI =
198 Uri.parse("content://" + Settings.AUTHORITY + "/config");
199
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700200 static {
201 for (String name : Resources.getSystem().getStringArray(
202 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
203 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
204 }
205 for (String name : Resources.getSystem().getStringArray(
206 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
207 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
208 }
209 for (String name : Resources.getSystem().getStringArray(
210 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
211 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
212 }
213 }
214
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800215 // Changes to these global settings are synchronously persisted
216 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
217 static {
218 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
219 }
220
221 // Changes to these secure settings are synchronously persisted
222 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
223 static {
224 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
225 }
226
Svetoslav683914b2015-01-15 14:22:26 -0800227 // Per user secure settings that moved to the for all users global settings.
228 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
229 static {
230 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700231 }
232
Svetoslav683914b2015-01-15 14:22:26 -0800233 // Per user system settings that moved to the for all users global settings.
234 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
235 static {
236 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700237 }
238
Svetoslav683914b2015-01-15 14:22:26 -0800239 // Per user system settings that moved to the per user secure settings.
240 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
241 static {
242 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700243 }
244
Svetoslav683914b2015-01-15 14:22:26 -0800245 // Per all users global settings that moved to the per user secure settings.
246 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
247 static {
248 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249 }
250
Svetoslav683914b2015-01-15 14:22:26 -0800251 // Per user secure settings that are cloned for the managed profiles of the user.
252 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
253 static {
254 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700255 }
256
Svetoslav683914b2015-01-15 14:22:26 -0800257 // Per user system settings that are cloned for the managed profiles of the user.
258 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
259 static {
260 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400261 }
262
Andre Lago3fa139c2016-08-04 13:53:44 +0100263 // Per user system settings that are cloned from the profile's parent when a dependency
264 // in {@link Settings.Secure} is set to "1".
265 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
266 static {
267 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
268 }
269
Svetoslav683914b2015-01-15 14:22:26 -0800270 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700271
Svetoslav683914b2015-01-15 14:22:26 -0800272 @GuardedBy("mLock")
273 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700274
Svet Ganova8f90262016-05-10 08:44:48 -0700275 @GuardedBy("mLock")
276 private HandlerThread mHandlerThread;
277
Makoto Onuki73360ab2017-03-17 11:50:13 -0700278 @GuardedBy("mLock")
279 private Handler mHandler;
280
Svetoslav7ec28e82015-05-20 17:01:10 -0700281 // We have to call in the user manager with no lock held,
282 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800283
yuemingw1d13eae2018-01-30 17:27:54 +0000284 private UserManagerInternal mUserManagerInternal;
285
Svetoslav7ec28e82015-05-20 17:01:10 -0700286 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700287 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700288
Svet Ganov53a441c2016-04-19 19:38:00 -0700289 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800290 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 }
292
293 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800294 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700295 }
296
297 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800298 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700299 }
300
301 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800302 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700303 }
304
305 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800306 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700307 }
308
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700309 @Override
310 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800311 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000312
313 // fail to boot if there're any backed up settings that don't have a non-null validator
314 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000315 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000316 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000317
Svetoslav683914b2015-01-15 14:22:26 -0800318 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700319 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000320 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700321 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700322 mHandlerThread = new HandlerThread(LOG_TAG,
323 Process.THREAD_PRIORITY_BACKGROUND);
324 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700325 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800326 mSettingsRegistry = new SettingsRegistry();
327 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700328 mHandler.post(() -> {
329 registerBroadcastReceivers();
330 startWatchingUserRestrictionChanges();
331 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700332 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333 return true;
334 }
335
Michal Karpinski2c37b082018-01-18 16:14:27 +0000336 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000337 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
338 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000339
340 failToBootIfOffendersPresent(offenders, "Settings.System");
341 }
342
343 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000344 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
345 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000346
347 failToBootIfOffendersPresent(offenders, "Settings.Global");
348 }
349
Michal Karpinski964943a2018-01-19 16:28:26 +0000350 private void ensureAllBackedUpSecureSettingsHaveValidators() {
351 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
352 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
353
354 failToBootIfOffendersPresent(offenders, "Settings.Secure");
355 }
356
Michal Karpinski5db1e432018-01-18 20:10:24 +0000357 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
358 if (offenders.length() > 0) {
359 throw new RuntimeException("All " + settingsType + " settings that are backed up"
360 + " have to have a non-null validator, but those don't: " + offenders);
361 }
362 }
363
364 private String getOffenders(String[] settingsToBackup, Map<String,
365 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000366 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000367 for (String setting : settingsToBackup) {
368 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000369 offenders.append(setting).append(" ");
370 }
371 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000372 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000373 }
374
Michal Karpinski964943a2018-01-19 16:28:26 +0000375 private final String[] concat(String[] first, String[] second) {
376 if (second == null || second.length == 0) {
377 return first;
378 }
379 final int firstLen = first.length;
380 final int secondLen = second.length;
381 String[] both = new String[firstLen + secondLen];
382 System.arraycopy(first, 0, both, 0, firstLen);
383 System.arraycopy(second, 0, both, firstLen, secondLen);
384 return both;
385 }
386
Svetoslav683914b2015-01-15 14:22:26 -0800387 @Override
388 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700389 final int requestingUserId = getRequestingUserId(args);
390 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700391 case Settings.CALL_METHOD_GET_CONFIG: {
392 Setting setting = getConfigSetting(name);
393 return packageValueForCallResult(setting, isTrackingGeneration(args));
394 }
395
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 case Settings.CALL_METHOD_GET_GLOBAL: {
397 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700398 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800399 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700400
401 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800402 Setting setting = getSecureSetting(name, requestingUserId,
403 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700404 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 }
406
407 case Settings.CALL_METHOD_GET_SYSTEM: {
408 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700409 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700410 }
411
Matt Pape1b31a332018-10-17 09:58:28 -0700412 case Settings.CALL_METHOD_PUT_CONFIG: {
413 String value = getSettingValue(args);
414 String tag = getSettingTag(args);
415 final boolean makeDefault = getSettingMakeDefault(args);
416 insertConfigSetting(name, value, tag, makeDefault, requestingUserId, false);
417 break;
418 }
419
Svetoslav7ec28e82015-05-20 17:01:10 -0700420 case Settings.CALL_METHOD_PUT_GLOBAL: {
421 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800422 String tag = getSettingTag(args);
423 final boolean makeDefault = getSettingMakeDefault(args);
424 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 break;
426 }
427
428 case Settings.CALL_METHOD_PUT_SECURE: {
429 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800430 String tag = getSettingTag(args);
431 final boolean makeDefault = getSettingMakeDefault(args);
432 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700433 break;
434 }
435
436 case Settings.CALL_METHOD_PUT_SYSTEM: {
437 String value = getSettingValue(args);
438 insertSystemSetting(name, value, requestingUserId);
439 break;
440 }
441
Matt Pape1b31a332018-10-17 09:58:28 -0700442 case Settings.CALL_METHOD_RESET_CONFIG: {
443 final int mode = getResetModeEnforcingPermission(args);
444 String tag = getSettingTag(args);
445 resetConfigSetting(requestingUserId, mode, tag);
446 break;
447 }
448
Svetoslav Ganove080da92016-12-21 17:10:35 -0800449 case Settings.CALL_METHOD_RESET_GLOBAL: {
450 final int mode = getResetModeEnforcingPermission(args);
451 String tag = getSettingTag(args);
452 resetGlobalSetting(requestingUserId, mode, tag);
453 break;
454 }
455
456 case Settings.CALL_METHOD_RESET_SECURE: {
457 final int mode = getResetModeEnforcingPermission(args);
458 String tag = getSettingTag(args);
459 resetSecureSetting(requestingUserId, mode, tag);
460 break;
461 }
462
Svetoslav7ec28e82015-05-20 17:01:10 -0700463 default: {
464 Slog.w(LOG_TAG, "call() with invalid method: " + method);
465 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700466 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700467
Christopher Tate06efb532012-08-24 15:29:27 -0700468 return null;
469 }
470
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800471 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800472 public String getType(Uri uri) {
473 Arguments args = new Arguments(uri, null, null, true);
474 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700475 return "vnd.android.cursor.dir/" + args.table;
476 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700477 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700478 }
479 }
480
481 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800482 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
483 String order) {
484 if (DEBUG) {
485 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700486 }
487
Svetoslav683914b2015-01-15 14:22:26 -0800488 Arguments args = new Arguments(uri, where, whereArgs, true);
489 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490
Svetoslav683914b2015-01-15 14:22:26 -0800491 // If a legacy table that is gone, done.
492 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
493 return new MatrixCursor(normalizedProjection, 0);
494 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700495
Svetoslav7ec28e82015-05-20 17:01:10 -0700496 switch (args.table) {
497 case TABLE_GLOBAL: {
498 if (args.name != null) {
499 Setting setting = getGlobalSetting(args.name);
500 return packageSettingForQuery(setting, normalizedProjection);
501 } else {
502 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700503 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700504 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700505
Svetoslav7ec28e82015-05-20 17:01:10 -0700506 case TABLE_SECURE: {
507 final int userId = UserHandle.getCallingUserId();
508 if (args.name != null) {
509 Setting setting = getSecureSetting(args.name, userId);
510 return packageSettingForQuery(setting, normalizedProjection);
511 } else {
512 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800513 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700514 }
Svetoslav683914b2015-01-15 14:22:26 -0800515
Svetoslav7ec28e82015-05-20 17:01:10 -0700516 case TABLE_SYSTEM: {
517 final int userId = UserHandle.getCallingUserId();
518 if (args.name != null) {
519 Setting setting = getSystemSetting(args.name, userId);
520 return packageSettingForQuery(setting, normalizedProjection);
521 } else {
522 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800523 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 }
Svetoslav683914b2015-01-15 14:22:26 -0800525
Svetoslav7ec28e82015-05-20 17:01:10 -0700526 default: {
527 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700528 }
529 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700530 }
531
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700532 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800533 public Uri insert(Uri uri, ContentValues values) {
534 if (DEBUG) {
535 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700536 }
537
Svetoslav683914b2015-01-15 14:22:26 -0800538 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700539
Svetoslav683914b2015-01-15 14:22:26 -0800540 // If a legacy table that is gone, done.
541 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 return null;
543 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544
Svetoslav683914b2015-01-15 14:22:26 -0800545 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700546 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800547 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700548 }
549
Svetoslav683914b2015-01-15 14:22:26 -0800550 String value = values.getAsString(Settings.Secure.VALUE);
551
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 switch (table) {
553 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800554 if (insertGlobalSetting(name, value, null, false,
555 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700556 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700557 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700558 } break;
559
560 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800561 if (insertSecureSetting(name, value, null, false,
562 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700563 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
564 }
565 } break;
566
567 case TABLE_SYSTEM: {
568 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
569 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
570 }
571 } break;
572
573 default: {
574 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700575 }
576 }
577
Svetoslav683914b2015-01-15 14:22:26 -0800578 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700579 }
580
581 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800582 public int bulkInsert(Uri uri, ContentValues[] allValues) {
583 if (DEBUG) {
584 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700586
Svetoslav683914b2015-01-15 14:22:26 -0800587 int insertionCount = 0;
588 final int valuesCount = allValues.length;
589 for (int i = 0; i < valuesCount; i++) {
590 ContentValues values = allValues[i];
591 if (insert(uri, values) != null) {
592 insertionCount++;
593 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700594 }
Svetoslav683914b2015-01-15 14:22:26 -0800595
596 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700597 }
598
599 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800600 public int delete(Uri uri, String where, String[] whereArgs) {
601 if (DEBUG) {
602 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700604
Svetoslav683914b2015-01-15 14:22:26 -0800605 Arguments args = new Arguments(uri, where, whereArgs, false);
606
607 // If a legacy table that is gone, done.
608 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
609 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700610 }
Svetoslav683914b2015-01-15 14:22:26 -0800611
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700612 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800613 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700614 }
Svetoslav683914b2015-01-15 14:22:26 -0800615
Svetoslav7ec28e82015-05-20 17:01:10 -0700616 switch (args.table) {
617 case TABLE_GLOBAL: {
618 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700619 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700620 }
Svetoslav683914b2015-01-15 14:22:26 -0800621
Svetoslav7ec28e82015-05-20 17:01:10 -0700622 case TABLE_SECURE: {
623 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700624 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700625 }
Svetoslav683914b2015-01-15 14:22:26 -0800626
Svetoslav7ec28e82015-05-20 17:01:10 -0700627 case TABLE_SYSTEM: {
628 final int userId = UserHandle.getCallingUserId();
629 return deleteSystemSetting(args.name, userId) ? 1 : 0;
630 }
631
632 default: {
633 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800634 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700635 }
Svetoslav683914b2015-01-15 14:22:26 -0800636 }
637
638 @Override
639 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
640 if (DEBUG) {
641 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700642 }
Svetoslav683914b2015-01-15 14:22:26 -0800643
644 Arguments args = new Arguments(uri, where, whereArgs, false);
645
646 // If a legacy table that is gone, done.
647 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
648 return 0;
649 }
650
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700651 String name = values.getAsString(Settings.Secure.NAME);
652 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800653 return 0;
654 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700655 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800656
Svetoslav7ec28e82015-05-20 17:01:10 -0700657 switch (args.table) {
658 case TABLE_GLOBAL: {
659 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800660 return updateGlobalSetting(args.name, value, null, false,
661 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700662 }
Svetoslav683914b2015-01-15 14:22:26 -0800663
Svetoslav7ec28e82015-05-20 17:01:10 -0700664 case TABLE_SECURE: {
665 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800666 return updateSecureSetting(args.name, value, null, false,
667 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700668 }
Svetoslav683914b2015-01-15 14:22:26 -0800669
Svetoslav7ec28e82015-05-20 17:01:10 -0700670 case TABLE_SYSTEM: {
671 final int userId = UserHandle.getCallingUserId();
672 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
673 }
Svetoslav683914b2015-01-15 14:22:26 -0800674
Svetoslav7ec28e82015-05-20 17:01:10 -0700675 default: {
676 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800677 }
678 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700679 }
680
681 @Override
682 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100683 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
684 if (userId != UserHandle.getCallingUserId()) {
685 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
686 "Access files from the settings of another user");
687 }
688 uri = ContentProvider.getUriWithoutUserId(uri);
689
Andre Lago3fa139c2016-08-04 13:53:44 +0100690 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700691 final String cacheName;
692 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100693 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700694 cacheName = Settings.System.RINGTONE_CACHE;
695 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100696 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700697 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
698 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100699 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700700 cacheName = Settings.System.ALARM_ALERT_CACHE;
701 } else {
702 throw new FileNotFoundException("Direct file access no longer supported; "
703 + "ringtone playback is available through android.media.Ringtone");
704 }
705
Andre Lago3fa139c2016-08-04 13:53:44 +0100706 int actualCacheOwner;
707 // Redirect cache to parent if ringtone setting is owned by profile parent
708 synchronized (mLock) {
709 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
710 cacheRingtoneSetting);
711 }
712 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700713 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
714 }
715
716 private File getRingtoneCacheDir(int userId) {
717 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
718 cacheDir.mkdir();
719 SELinux.restorecon(cacheDir);
720 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700721 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800722
Eugene Suslad72c3972016-12-27 15:49:30 -0800723 /**
724 * Dump all settings as a proto buf.
725 *
726 * @param fd The file to dump to
727 */
728 void dumpProto(@NonNull FileDescriptor fd) {
729 ProtoOutputStream proto = new ProtoOutputStream(fd);
730
731 synchronized (mLock) {
732 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800733 }
734
735 proto.flush();
736 }
737
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700738 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800739 synchronized (mLock) {
740 final long identity = Binder.clearCallingIdentity();
741 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700742 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800743 final int userCount = users.size();
744 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700745 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800746 }
747 } finally {
748 Binder.restoreCallingIdentity(identity);
749 }
750 }
751 }
752
Andreas Gampeb58893072018-09-05 16:52:31 -0700753 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700754 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700755 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700756 pw.println("CONFIG SETTINGS (user " + userId + ")");
757 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
758 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
759 if (configSettings != null) {
760 dumpSettingsLocked(configSettings, pw);
761 pw.println();
762 configSettings.dumpHistoricalOperations(pw);
763 }
764
Svetoslavb505ccc2015-02-17 12:41:04 -0800765 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700766 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
767 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700768 if (globalSettings != null) {
769 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800770 pw.println();
771 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700772 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800773 }
774
775 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700776 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
777 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700778 if (secureSettings != null) {
779 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800780 pw.println();
781 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700782 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700783
Svetoslavb505ccc2015-02-17 12:41:04 -0800784 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700785 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
786 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700787 if (systemSettings != null) {
788 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800789 pw.println();
790 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700791 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800792 }
793
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700794 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
795 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800796
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700797 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800798
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700799 for (int i = 0; i < nameCount; i++) {
800 String name = names.get(i);
801 Setting setting = settingsState.getSettingLocked(name);
802 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
803 pw.print(" name:"); pw.print(toDumpString(name));
804 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800805 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700806 }
807 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800808 if (setting.getDefaultValue() != null) {
809 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800810 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800811 }
812 if (setting.getTag() != null) {
813 pw.print(" tag:"); pw.print(setting.getTag());
814 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800815 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700816 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800817 }
818
Svetoslav7e0683b2015-08-03 16:02:52 -0700819 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700820 if (s != null) {
821 return s;
822 }
823 return "{null}";
824 }
825
Svetoslav683914b2015-01-15 14:22:26 -0800826 private void registerBroadcastReceivers() {
827 IntentFilter userFilter = new IntentFilter();
828 userFilter.addAction(Intent.ACTION_USER_REMOVED);
829 userFilter.addAction(Intent.ACTION_USER_STOPPED);
830
831 getContext().registerReceiver(new BroadcastReceiver() {
832 @Override
833 public void onReceive(Context context, Intent intent) {
834 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700835 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800836
837 switch (intent.getAction()) {
838 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700839 synchronized (mLock) {
840 mSettingsRegistry.removeUserStateLocked(userId, true);
841 }
Svetoslav683914b2015-01-15 14:22:26 -0800842 } break;
843
844 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700845 synchronized (mLock) {
846 mSettingsRegistry.removeUserStateLocked(userId, false);
847 }
Svetoslav683914b2015-01-15 14:22:26 -0800848 } break;
849 }
850 }
851 }, userFilter);
852
853 PackageMonitor monitor = new PackageMonitor() {
854 @Override
855 public void onPackageRemoved(String packageName, int uid) {
856 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100857 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800858 UserHandle.getUserId(uid));
859 }
860 }
Mark Rathjend891f012017-01-19 04:10:37 +0000861
862 @Override
863 public void onUidRemoved(int uid) {
864 synchronized (mLock) {
865 mSettingsRegistry.onUidRemovedLocked(uid);
866 }
867 }
Zimuzoc56192c2018-07-25 10:40:01 +0100868
869 @Override
870 public void onPackageDataCleared(String packageName, int uid) {
871 synchronized (mLock) {
872 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
873 UserHandle.getUserId(uid));
874 }
875 }
Svetoslav683914b2015-01-15 14:22:26 -0800876 };
877
878 // package changes
879 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
880 UserHandle.ALL, true);
881 }
882
Svet Ganov53a441c2016-04-19 19:38:00 -0700883 private void startWatchingUserRestrictionChanges() {
884 // TODO: The current design of settings looking different based on user restrictions
885 // should be reworked to keep them separate and system code should check the setting
886 // first followed by checking the user restriction before performing an operation.
887 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
888 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
889 Bundle prevRestrictions) -> {
890 // We are changing the settings affected by restrictions to their current
891 // value with a forced update to ensure that all cross profile dependencies
892 // are taken into account. Also make sure the settings update to.. the same
893 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800894 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
895 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700896 final long identity = Binder.clearCallingIdentity();
897 try {
898 synchronized (mLock) {
899 Setting setting = getSecureSetting(
900 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
901 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800902 setting != null ? setting.getValue() : null, null,
903 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700904 }
905 } finally {
906 Binder.restoreCallingIdentity(identity);
907 }
908 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800909 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
910 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700911 final long identity = Binder.clearCallingIdentity();
912 try {
913 synchronized (mLock) {
914 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800915 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700916 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800917 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700918 }
919 } finally {
920 Binder.restoreCallingIdentity(identity);
921 }
922 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800923 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
924 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700925 final long identity = Binder.clearCallingIdentity();
926 try {
927 synchronized (mLock) {
928 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700930 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800931 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700932 }
933 } finally {
934 Binder.restoreCallingIdentity(identity);
935 }
936 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800937 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
938 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700939 final long identity = Binder.clearCallingIdentity();
940 try {
941 synchronized (mLock) {
942 Setting enable = getGlobalSetting(
943 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800944 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700945 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800946 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700947 Setting include = getGlobalSetting(
948 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800949 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700950 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800951 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700952 }
953 } finally {
954 Binder.restoreCallingIdentity(identity);
955 }
956 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800957 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
958 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700959 final long identity = Binder.clearCallingIdentity();
960 try {
961 synchronized (mLock) {
962 Setting setting = getGlobalSetting(
963 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800964 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700965 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800966 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700967 }
968 } finally {
969 Binder.restoreCallingIdentity(identity);
970 }
971 }
972 });
973 }
974
Matt Pape1b31a332018-10-17 09:58:28 -0700975 private Setting getConfigSetting(String name) {
976 if (DEBUG) {
977 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
978 }
979
980 // TODO(b/117663715): Ensure the caller can access the setting.
981 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
982
983 // Get the value.
984 synchronized (mLock) {
985 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
986 UserHandle.USER_SYSTEM, name);
987 }
988 }
989
990 private boolean insertConfigSetting(String name, String value, String tag,
991 boolean makeDefault, int requestingUserId, boolean forceNotify) {
992 if (DEBUG) {
993 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
994 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
995 + ", " + forceNotify + ")");
996 }
997 return mutateConfigSetting(name, value, tag, makeDefault, requestingUserId,
998 MUTATION_OPERATION_INSERT, forceNotify, 0);
999 }
1000
1001 private void resetConfigSetting(int requestingUserId, int mode, String tag) {
1002 if (DEBUG) {
1003 Slog.v(LOG_TAG, "resetConfigSetting(" + requestingUserId + ", "
1004 + mode + ", " + tag + ")");
1005 }
1006 mutateConfigSetting(null, null, tag, false, requestingUserId,
1007 MUTATION_OPERATION_RESET, false, mode);
1008 }
1009
1010 private boolean mutateConfigSetting(String name, String value, String tag,
1011 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1012 int mode) {
1013 // TODO(b/117663715): check the new permission when it's added.
1014 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1015
1016 // Resolve the userId on whose behalf the call is made.
1017 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1018
1019 // Perform the mutation.
1020 synchronized (mLock) {
1021 switch (operation) {
1022 case MUTATION_OPERATION_INSERT: {
1023 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
1024 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
1025 getCallingPackage(), forceNotify, null);
1026 }
1027
1028 case MUTATION_OPERATION_RESET: {
1029 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
1030 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1031 } return true;
1032 }
1033 }
1034
1035 return false;
1036 }
1037
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001039 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001040 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001041 }
1042
Svetoslav7ec28e82015-05-20 17:01:10 -07001043 synchronized (mLock) {
1044 // Get the settings.
1045 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001046 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001047
Chad Brubaker97bccee2017-01-05 15:51:41 -08001048 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1049 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001050
Svetoslav7ec28e82015-05-20 17:01:10 -07001051 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001052
Svetoslav7ec28e82015-05-20 17:01:10 -07001053 String[] normalizedProjection = normalizeProjection(projection);
1054 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001055
Svetoslav7ec28e82015-05-20 17:01:10 -07001056 // Anyone can get the global settings, so no security checks.
1057 for (int i = 0; i < nameCount; i++) {
1058 String name = names.get(i);
1059 Setting setting = settingsState.getSettingLocked(name);
1060 appendSettingToCursor(result, setting);
1061 }
1062
1063 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001064 }
Svetoslav683914b2015-01-15 14:22:26 -08001065 }
1066
Svetoslav7ec28e82015-05-20 17:01:10 -07001067 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001068 if (DEBUG) {
1069 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1070 }
1071
Chad Brubakera6830e72017-04-28 17:34:36 -07001072 // Ensure the caller can access the setting.
1073 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1074
Svetoslav683914b2015-01-15 14:22:26 -08001075 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001076 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001077 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001078 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001079 }
Svetoslav683914b2015-01-15 14:22:26 -08001080 }
1081
Svetoslav Ganove080da92016-12-21 17:10:35 -08001082 private boolean updateGlobalSetting(String name, String value, String tag,
1083 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001084 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001085 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1086 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1087 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001088 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001089 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1090 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001091 }
1092
Svetoslav Ganove080da92016-12-21 17:10:35 -08001093 private boolean insertGlobalSetting(String name, String value, String tag,
1094 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001095 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001096 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1097 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1098 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001099 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001100 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1101 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001102 }
1103
Svet Ganov53a441c2016-04-19 19:38:00 -07001104 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001105 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001106 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1107 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001108 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001109 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1110 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001111 }
1112
Svetoslav Ganove080da92016-12-21 17:10:35 -08001113 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1114 if (DEBUG) {
1115 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1116 + mode + ", " + tag + ")");
1117 }
1118 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1119 MUTATION_OPERATION_RESET, false, mode);
1120 }
1121
1122 private boolean mutateGlobalSetting(String name, String value, String tag,
1123 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1124 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001125 // Make sure the caller can change the settings - treated as secure.
1126 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1127
Svetoslav683914b2015-01-15 14:22:26 -08001128 // Resolve the userId on whose behalf the call is made.
1129 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1130
Makoto Onuki28da2e32015-11-20 11:30:44 -08001131 // If this is a setting that is currently restricted for this user, do not allow
1132 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001133 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1134 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001135 return false;
1136 }
1137
1138 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001139 synchronized (mLock) {
1140 switch (operation) {
1141 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001142 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1143 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001144 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001145 }
Svetoslav683914b2015-01-15 14:22:26 -08001146
Svetoslav7ec28e82015-05-20 17:01:10 -07001147 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001148 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001149 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001150 }
Svetoslav683914b2015-01-15 14:22:26 -08001151
Svetoslav7ec28e82015-05-20 17:01:10 -07001152 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001153 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1154 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001155 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001156 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001157
1158 case MUTATION_OPERATION_RESET: {
1159 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1160 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1161 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001162 }
1163 }
1164
1165 return false;
1166 }
1167
Christopher Tateb218e762017-04-05 16:34:07 -07001168 private PackageInfo getCallingPackageInfo(int userId) {
1169 try {
1170 return mPackageManager.getPackageInfo(getCallingPackage(),
1171 PackageManager.GET_SIGNATURES, userId);
1172 } catch (RemoteException e) {
1173 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1174 }
1175 }
1176
Svetoslav7ec28e82015-05-20 17:01:10 -07001177 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001178 if (DEBUG) {
1179 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1180 }
1181
1182 // Resolve the userId on whose behalf the call is made.
1183 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1184
Christopher Tateb218e762017-04-05 16:34:07 -07001185 // The relevant "calling package" userId will be the owning userId for some
1186 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1187 // up front who the effective "new SSAID" user ID for that settings name will be.
1188 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1189 Settings.Secure.ANDROID_ID);
1190 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1191
Svetoslav7ec28e82015-05-20 17:01:10 -07001192 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001193 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001194
Svetoslav7ec28e82015-05-20 17:01:10 -07001195 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001196
Svetoslav7ec28e82015-05-20 17:01:10 -07001197 String[] normalizedProjection = normalizeProjection(projection);
1198 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001199
Svetoslav7ec28e82015-05-20 17:01:10 -07001200 for (int i = 0; i < nameCount; i++) {
1201 String name = names.get(i);
1202 // Determine the owning user as some profile settings are cloned from the parent.
1203 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1204 name);
Svetoslav683914b2015-01-15 14:22:26 -08001205
Alex Klyubin1991f572017-03-03 14:08:36 -08001206 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1207 // This caller is not permitted to access this setting. Pretend the setting
1208 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001209 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001210 }
Svetoslav683914b2015-01-15 14:22:26 -08001211
Mark Rathjen7599f132017-01-23 14:15:54 -08001212 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001213 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1214 final Setting setting;
1215 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001216 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001217 } else {
1218 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1219 name);
1220 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001221 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001222 }
1223
Svetoslav7ec28e82015-05-20 17:01:10 -07001224 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001225 }
Svetoslav683914b2015-01-15 14:22:26 -08001226 }
1227
Svetoslav7ec28e82015-05-20 17:01:10 -07001228 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001229 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1230 }
1231
1232 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001233 if (DEBUG) {
1234 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1235 }
1236
1237 // Resolve the userId on whose behalf the call is made.
1238 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1239
Chad Brubakera6830e72017-04-28 17:34:36 -07001240 // Ensure the caller can access the setting.
1241 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1242
Svetoslav683914b2015-01-15 14:22:26 -08001243 // Determine the owning user as some profile settings are cloned from the parent.
1244 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1245
Alex Klyubin1991f572017-03-03 14:08:36 -08001246 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1247 // This caller is not permitted to access this setting. Pretend the setting doesn't
1248 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001249 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1250 owningUserId);
1251 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001252 }
1253
Christopher Tateb218e762017-04-05 16:34:07 -07001254 // As of Android O, the SSAID is read from an app-specific entry in table
1255 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1256 if (isNewSsaidSetting(name)) {
1257 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1258 synchronized (mLock) {
1259 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001260 }
Christopher Tateb218e762017-04-05 16:34:07 -07001261 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001262 if (enableOverride) {
1263 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1264 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1265 if (overridden != null) {
1266 return overridden;
1267 }
1268 }
1269 }
Mark Rathjend891f012017-01-19 04:10:37 +00001270
Christopher Tateb218e762017-04-05 16:34:07 -07001271 // Not the SSAID; do a straight lookup
1272 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001273 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 owningUserId, name);
1275 }
Svetoslav683914b2015-01-15 14:22:26 -08001276 }
1277
Mark Rathjend891f012017-01-19 04:10:37 +00001278 private boolean isNewSsaidSetting(String name) {
1279 return Settings.Secure.ANDROID_ID.equals(name)
1280 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1281 }
1282
Andreas Gampeb58893072018-09-05 16:52:31 -07001283 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001284 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001285 // Get uid of caller (key) used to store ssaid value
1286 String name = Integer.toString(
1287 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1288
1289 if (DEBUG) {
1290 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1291 }
1292
1293 // Retrieve the ssaid from the table if present.
1294 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1295 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001296 // If the app is an Instant App use its stored SSAID instead of our own.
1297 final String instantSsaid;
1298 final long token = Binder.clearCallingIdentity();
1299 try {
1300 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1301 owningUserId);
1302 } catch (RemoteException e) {
1303 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1304 return null;
1305 } finally {
1306 Binder.restoreCallingIdentity(token);
1307 }
Svet Ganov96c99462017-05-05 14:27:13 -07001308
1309 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1310 SETTINGS_TYPE_SSAID, owningUserId);
1311
Chad Brubaker0d277a72017-04-12 16:56:53 -07001312 if (instantSsaid != null) {
1313 // Use the stored value if it is still valid.
1314 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001315 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001316 }
1317 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001318 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1319 true, callingPkg.packageName);
1320 if (!success) {
1321 throw new IllegalStateException("Failed to update instant app android id");
1322 }
Svet Ganov96c99462017-05-05 14:27:13 -07001323 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1324 owningUserId, name);
1325 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001326 }
Mark Rathjend891f012017-01-19 04:10:37 +00001327
1328 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001329 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001330 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1331 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001332 }
1333
Svet Ganov96c99462017-05-05 14:27:13 -07001334 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1335 }
1336
1337 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1338 // SSAID settings are located in a dedicated table for internal bookkeeping
1339 // but for the world they reside in the secure table, so adjust the key here.
1340 // We have a special name when looking it up but want the world to see it as
1341 // "android_id".
1342 if (ssaidSetting != null) {
1343 return settingsState.new Setting(ssaidSetting) {
1344 @Override
1345 public int getKey() {
1346 final int userId = getUserIdFromKey(super.getKey());
1347 return makeKey(SETTINGS_TYPE_SECURE, userId);
1348 }
1349
1350 @Override
1351 public String getName() {
1352 return Settings.Secure.ANDROID_ID;
1353 }
1354 };
1355 }
1356 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001357 }
1358
Makoto Onuki0000d322017-11-28 16:31:47 -08001359 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1360 synchronized (mLock) {
1361 final Setting setting = getGlobalSetting(
1362 Global.LOCATION_GLOBAL_KILL_SWITCH);
1363 if (!"1".equals(setting.getValue())) {
1364 return null;
1365 }
1366 // Global kill-switch is enabled. Return an empty value.
1367 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1368 SETTINGS_TYPE_SECURE, owningUserId);
1369 return settingsState.new Setting(
1370 Secure.LOCATION_PROVIDERS_ALLOWED,
1371 "", // value
1372 "", // tag
1373 "", // default value
1374 "", // package name
1375 false, // from system
1376 "0" // id
1377 ) {
1378 @Override
1379 public boolean update(String value, boolean setDefault, String packageName,
1380 String tag, boolean forceNonSystemPackage) {
1381 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1382 return false;
1383 }
1384 };
1385 }
1386 }
1387
Svetoslav Ganove080da92016-12-21 17:10:35 -08001388 private boolean insertSecureSetting(String name, String value, String tag,
1389 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001390 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001391 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001392 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1393 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001394 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001395 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1396 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001397 }
1398
Svet Ganov53a441c2016-04-19 19:38:00 -07001399 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001400 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001401 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1402 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001403 }
1404
Svetoslav Ganove080da92016-12-21 17:10:35 -08001405 return mutateSecureSetting(name, null, null, false, requestingUserId,
1406 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001407 }
1408
Svetoslav Ganove080da92016-12-21 17:10:35 -08001409 private boolean updateSecureSetting(String name, String value, String tag,
1410 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001411 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001412 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001413 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1414 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001415 }
1416
Svetoslav Ganove080da92016-12-21 17:10:35 -08001417 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1418 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001419 }
1420
Svetoslav Ganove080da92016-12-21 17:10:35 -08001421 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1422 if (DEBUG) {
1423 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1424 + mode + ", " + tag + ")");
1425 }
1426
1427 mutateSecureSetting(null, null, tag, false, requestingUserId,
1428 MUTATION_OPERATION_RESET, false, mode);
1429 }
1430
1431 private boolean mutateSecureSetting(String name, String value, String tag,
1432 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1433 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001434 // Make sure the caller can change the settings.
1435 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1436
Svetoslav683914b2015-01-15 14:22:26 -08001437 // Resolve the userId on whose behalf the call is made.
1438 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1439
Makoto Onuki28da2e32015-11-20 11:30:44 -08001440 // If this is a setting that is currently restricted for this user, do not allow
1441 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001442 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1443 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001444 return false;
1445 }
1446
1447 // Determine the owning user as some profile settings are cloned from the parent.
1448 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1449
1450 // Only the owning user can change the setting.
1451 if (owningUserId != callingUserId) {
1452 return false;
1453 }
1454
1455 // Special cases for location providers (sigh).
1456 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001457 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1458 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001459 }
1460
1461 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001462 synchronized (mLock) {
1463 switch (operation) {
1464 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001465 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001466 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001467 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001468 }
Svetoslav683914b2015-01-15 14:22:26 -08001469
Svetoslav7ec28e82015-05-20 17:01:10 -07001470 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001471 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001472 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001473 }
Svetoslav683914b2015-01-15 14:22:26 -08001474
Svetoslav7ec28e82015-05-20 17:01:10 -07001475 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001476 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001477 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001478 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001479 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001480
1481 case MUTATION_OPERATION_RESET: {
1482 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1483 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1484 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001485 }
1486 }
1487
1488 return false;
1489 }
1490
Svetoslav7ec28e82015-05-20 17:01:10 -07001491 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001492 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001493 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001494 }
1495
1496 // Resolve the userId on whose behalf the call is made.
1497 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1498
Svetoslav7ec28e82015-05-20 17:01:10 -07001499 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001500 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001501
Svetoslav7ec28e82015-05-20 17:01:10 -07001502 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001503
Svetoslav7ec28e82015-05-20 17:01:10 -07001504 String[] normalizedProjection = normalizeProjection(projection);
1505 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001506
Svetoslav7ec28e82015-05-20 17:01:10 -07001507 for (int i = 0; i < nameCount; i++) {
1508 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001509
Svetoslav7ec28e82015-05-20 17:01:10 -07001510 // Determine the owning user as some profile settings are cloned from the parent.
1511 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1512 name);
Svetoslav683914b2015-01-15 14:22:26 -08001513
Svetoslav7ec28e82015-05-20 17:01:10 -07001514 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001515 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001516 appendSettingToCursor(result, setting);
1517 }
1518
1519 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001520 }
Svetoslav683914b2015-01-15 14:22:26 -08001521 }
1522
Svetoslav7ec28e82015-05-20 17:01:10 -07001523 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001524 if (DEBUG) {
1525 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1526 }
1527
1528 // Resolve the userId on whose behalf the call is made.
1529 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1530
Chad Brubakera6830e72017-04-28 17:34:36 -07001531 // Ensure the caller can access the setting.
1532 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001533
Svetoslav683914b2015-01-15 14:22:26 -08001534 // Determine the owning user as some profile settings are cloned from the parent.
1535 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1536
1537 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001538 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001539 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001540 }
Svetoslav683914b2015-01-15 14:22:26 -08001541 }
1542
Svetoslav7ec28e82015-05-20 17:01:10 -07001543 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001544 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001545 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001546 + requestingUserId + ")");
1547 }
1548
Svetoslav7ec28e82015-05-20 17:01:10 -07001549 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001550 }
1551
Svetoslav7ec28e82015-05-20 17:01:10 -07001552 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001553 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001554 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001555 }
1556
Svetoslav7ec28e82015-05-20 17:01:10 -07001557 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001558 }
1559
Svetoslav7ec28e82015-05-20 17:01:10 -07001560 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001561 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001562 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001563 + requestingUserId + ")");
1564 }
1565
Svetoslav7ec28e82015-05-20 17:01:10 -07001566 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001567 }
1568
Svetoslav7ec28e82015-05-20 17:01:10 -07001569 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001570 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001571 if (!hasWriteSecureSettingsPermission()) {
1572 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1573 // operation is allowed for the calling package through appops.
1574 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1575 Binder.getCallingUid(), getCallingPackage(), true)) {
1576 return false;
1577 }
Svetoslav683914b2015-01-15 14:22:26 -08001578 }
1579
Svetoslav683914b2015-01-15 14:22:26 -08001580 // Resolve the userId on whose behalf the call is made.
1581 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1582
yuemingw1d13eae2018-01-30 17:27:54 +00001583 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1584 name, callingUserId, value, Binder.getCallingUid())) {
1585 return false;
1586 }
1587
Svetoslavd8d25e02015-11-20 13:09:26 -08001588 // Enforce what the calling package can mutate the system settings.
1589 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1590
Svetoslav683914b2015-01-15 14:22:26 -08001591 // Determine the owning user as some profile settings are cloned from the parent.
1592 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1593
1594 // Only the owning user id can change the setting.
1595 if (owningUserId != callingUserId) {
1596 return false;
1597 }
1598
Jeff Sharkey413573a2016-02-22 17:52:45 -07001599 // Invalidate any relevant cache files
1600 String cacheName = null;
1601 if (Settings.System.RINGTONE.equals(name)) {
1602 cacheName = Settings.System.RINGTONE_CACHE;
1603 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1604 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1605 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1606 cacheName = Settings.System.ALARM_ALERT_CACHE;
1607 }
1608 if (cacheName != null) {
1609 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001610 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001611 cacheFile.delete();
1612 }
1613
Svetoslav683914b2015-01-15 14:22:26 -08001614 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001615 synchronized (mLock) {
1616 switch (operation) {
1617 case MUTATION_OPERATION_INSERT: {
1618 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001619 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001620 owningUserId, name, value, null, false, getCallingPackage(),
1621 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001622 }
1623
1624 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001625 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001626 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001627 }
1628
1629 case MUTATION_OPERATION_UPDATE: {
1630 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001631 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001632 owningUserId, name, value, null, false, getCallingPackage(),
1633 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001634 }
Svetoslav683914b2015-01-15 14:22:26 -08001635 }
1636
Svetoslav7ec28e82015-05-20 17:01:10 -07001637 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001638 }
Svetoslav683914b2015-01-15 14:22:26 -08001639 }
1640
Billy Lau6ad2d662015-07-18 00:26:58 +01001641 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001642 // Write secure settings is a more protected permission. If caller has it we are good.
1643 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1644 == PackageManager.PERMISSION_GRANTED) {
1645 return true;
1646 }
1647
Svetoslavf41334b2015-06-23 12:06:03 -07001648 return false;
1649 }
1650
Svetoslav683914b2015-01-15 14:22:26 -08001651 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001652 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001653 if (validator != null && !validator.validate(value)) {
1654 throw new IllegalArgumentException("Invalid value: " + value
1655 + " for setting: " + name);
1656 }
1657 }
1658
Alex Klyubin1991f572017-03-03 14:08:36 -08001659 /**
1660 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1661 */
1662 private boolean isSecureSettingAccessible(String name, int callingUserId,
1663 int owningUserId) {
1664 // Special case for location (sigh).
1665 // This check is not inside the name-based checks below because this method performs checks
1666 // only if the calling user ID is not the same as the owning user ID.
1667 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1668 return false;
1669 }
1670
1671 switch (name) {
1672 case "bluetooth_address":
1673 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1674 // address in this secure setting. Secure settings can normally be read by any app,
1675 // which thus enables them to bypass the recently introduced restrictions on access
1676 // to device identifiers.
1677 // To mitigate this we make this setting available only to callers privileged to see
1678 // this device's MAC addresses, same as through public API
1679 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1680 return getContext().checkCallingOrSelfPermission(
1681 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1682 default:
1683 return true;
1684 }
1685 }
1686
Svetoslav683914b2015-01-15 14:22:26 -08001687 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1688 int owningUserId) {
1689 // Optimization - location providers are restricted only for managed profiles.
1690 if (callingUserId == owningUserId) {
1691 return false;
1692 }
1693 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1694 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1695 new UserHandle(callingUserId))) {
1696 return true;
1697 }
1698 return false;
1699 }
1700
Svetoslav683914b2015-01-15 14:22:26 -08001701 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1702 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1703 }
1704
1705 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001706 final int parentId;
1707 // Resolves dependency if setting has a dependency and the calling user has a parent
1708 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1709 && (parentId = getGroupParentLocked(userId)) != userId) {
1710 // The setting has a dependency and the profile has a parent
1711 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001712 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1713 final long token = Binder.clearCallingIdentity();
1714 try {
1715 Setting settingObj = getSecureSetting(dependency, userId);
1716 if (settingObj != null && settingObj.getValue().equals("1")) {
1717 return parentId;
1718 }
1719 } finally {
1720 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001721 }
1722 }
Svetoslav683914b2015-01-15 14:22:26 -08001723 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1724 }
1725
1726 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1727 final int parentId = getGroupParentLocked(userId);
1728 if (parentId != userId && keys.contains(name)) {
1729 return parentId;
1730 }
1731 return userId;
1732 }
1733
Svetoslavf41334b2015-06-23 12:06:03 -07001734 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001735 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001736 // System/root/shell can mutate whatever secure settings they want.
1737 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001738 final int appId = UserHandle.getAppId(callingUid);
1739 if (appId == android.os.Process.SYSTEM_UID
1740 || appId == Process.SHELL_UID
1741 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001742 return;
1743 }
1744
1745 switch (operation) {
1746 case MUTATION_OPERATION_INSERT:
1747 // Insert updates.
1748 case MUTATION_OPERATION_UPDATE: {
1749 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1750 return;
1751 }
1752
1753 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001754 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001755
1756 // Privileged apps can do whatever they want.
1757 if ((packageInfo.applicationInfo.privateFlags
1758 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1759 return;
1760 }
1761
1762 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1763 packageInfo.applicationInfo.targetSdkVersion, name);
1764 } break;
1765
1766 case MUTATION_OPERATION_DELETE: {
1767 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1768 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1769 throw new IllegalArgumentException("You cannot delete system defined"
1770 + " secure settings.");
1771 }
1772
1773 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001774 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001775
1776 // Privileged apps can do whatever they want.
1777 if ((packageInfo.applicationInfo.privateFlags &
1778 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1779 return;
1780 }
1781
1782 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1783 packageInfo.applicationInfo.targetSdkVersion, name);
1784 } break;
1785 }
1786 }
1787
Todd Kennedybe0b8892017-02-15 14:13:52 -08001788 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001789 switch (settingsType) {
1790 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001791 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001792 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001793 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001794 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001795 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001796 default:
1797 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1798 }
1799 }
1800
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001801 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1802 switch (settingsType) {
1803 case SETTINGS_TYPE_GLOBAL:
1804 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1805 case SETTINGS_TYPE_SYSTEM:
1806 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1807 case SETTINGS_TYPE_SECURE:
1808 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1809 default:
1810 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1811 }
1812 }
1813
Andreas Gampeb58893072018-09-05 16:52:31 -07001814 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001815 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001816 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1817 // in the current form.
1818 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001819 }
1820
Chad Brubakera6830e72017-04-28 17:34:36 -07001821 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001822 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1823 return;
1824 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001825 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001826 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001827 return;
1828 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001829 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1830 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001831 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1832 // breakage in the current form.
1833 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1834 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001835 }
1836 }
1837
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001838 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1839 // We always use the callingUid for this lookup. This means that if hypothetically an
1840 // app was installed in user A with cross user and in user B as an Instant App
1841 // the app in A would be able to see all the settings in user B. However since cross
1842 // user is a system permission and the app must be uninstalled in B and then installed as
1843 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001844 ApplicationInfo ai = null;
1845 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001846 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1847 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001848 } catch (RemoteException ignored) {
1849 }
1850 if (ai == null) {
1851 throw new IllegalStateException("Failed to lookup info for package "
1852 + getCallingPackage());
1853 }
1854 return ai;
1855 }
1856
Xiaohui Chen43765b72015-08-31 10:57:33 -07001857 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001858 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001859 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1860 getCallingPackage(), 0, userId);
1861 if (packageInfo != null) {
1862 return packageInfo;
1863 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001864 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001865 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001866 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001867 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001868 }
1869
1870 private int getGroupParentLocked(int userId) {
1871 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001872 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001873 return userId;
1874 }
1875 // We are in the same process with the user manager and the returned
1876 // user info is a cached instance, so just look up instead of cache.
1877 final long identity = Binder.clearCallingIdentity();
1878 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001879 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001880 UserInfo userInfo = mUserManager.getProfileParent(userId);
1881 return (userInfo != null) ? userInfo.id : userId;
1882 } finally {
1883 Binder.restoreCallingIdentity(identity);
1884 }
1885 }
1886
Svetoslav683914b2015-01-15 14:22:26 -08001887 private void enforceWritePermission(String permission) {
1888 if (getContext().checkCallingOrSelfPermission(permission)
1889 != PackageManager.PERMISSION_GRANTED) {
1890 throw new SecurityException("Permission denial: writing to settings requires:"
1891 + permission);
1892 }
1893 }
1894
1895 /*
1896 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1897 * This setting contains a list of the currently enabled location providers.
1898 * But helper functions in android.providers.Settings can enable or disable
1899 * a single provider by using a "+" or "-" prefix before the provider name.
1900 *
yuemingw1d13eae2018-01-30 17:27:54 +00001901 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1902 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1903 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001904 *
Svetoslav683914b2015-01-15 14:22:26 -08001905 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001906 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001907 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001908 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1909 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001910 if (TextUtils.isEmpty(value)) {
1911 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001912 }
Maggie83e03f52018-03-16 12:22:20 -07001913 Setting oldSetting = getSecureSetting(
1914 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1915 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001916 return false;
1917 }
Maggie83e03f52018-03-16 12:22:20 -07001918 String oldProviders = oldSetting.getValue();
1919 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1920 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1921 Set<String> newProvidersSet = new ArraySet<>();
1922 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08001923
Maggie83e03f52018-03-16 12:22:20 -07001924 String[] providerUpdates = value.split(",");
1925 boolean inputError = false;
1926 for (String provider : providerUpdates) {
1927 // do not update location_providers_allowed when input is invalid
1928 if (TextUtils.isEmpty(provider)) {
1929 inputError = true;
1930 break;
Svetoslav683914b2015-01-15 14:22:26 -08001931 }
Maggie83e03f52018-03-16 12:22:20 -07001932 final char prefix = provider.charAt(0);
1933 // do not update location_providers_allowed when input is invalid
1934 if (prefix != '+' && prefix != '-') {
1935 inputError = true;
1936 break;
Svetoslav683914b2015-01-15 14:22:26 -08001937 }
Maggie83e03f52018-03-16 12:22:20 -07001938 // skip prefix
1939 provider = provider.substring(1);
1940 if (prefix == '+') {
1941 newProvidersSet.add(provider);
1942 } else if (prefix == '-') {
1943 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08001944 }
Maggie83e03f52018-03-16 12:22:20 -07001945 }
1946 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
1947 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08001948 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001949 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07001950 mSettingsRegistry.notifyForSettingsChange(
1951 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07001952 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1953 }
Svetoslav683914b2015-01-15 14:22:26 -08001954 return false;
1955 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001956 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07001957 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
1958 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001959 }
1960
Svetoslav683914b2015-01-15 14:22:26 -08001961 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1962 int targetSdkVersion, String name) {
1963 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1964 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1965 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1966 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1967 + " This will soon become an error.");
1968 } else {
1969 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1970 + " This will soon become an error.");
1971 }
1972 } else {
1973 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1974 throw new IllegalArgumentException("You cannot change private secure settings.");
1975 } else {
1976 throw new IllegalArgumentException("You cannot keep your settings in"
1977 + " the secure settings.");
1978 }
1979 }
1980 }
1981
1982 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1983 if (requestingUserId == UserHandle.getCallingUserId()) {
1984 return requestingUserId;
1985 }
1986 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1987 Binder.getCallingUid(), requestingUserId, false, true,
1988 "get/set setting for user", null);
1989 }
1990
Svet Ganov53a441c2016-04-19 19:38:00 -07001991 private Bundle packageValueForCallResult(Setting setting,
1992 boolean trackingGeneration) {
1993 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001994 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001995 return NULL_SETTING_BUNDLE;
1996 }
1997 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001998 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001999 Bundle result = new Bundle();
2000 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002001 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002002
Svetoslav Ganove080da92016-12-21 17:10:35 -08002003 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002004 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002005 }
2006
2007 private static int getRequestingUserId(Bundle args) {
2008 final int callingUserId = UserHandle.getCallingUserId();
2009 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2010 : callingUserId;
2011 }
2012
Svet Ganov53a441c2016-04-19 19:38:00 -07002013 private boolean isTrackingGeneration(Bundle args) {
2014 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2015 }
2016
Svetoslav683914b2015-01-15 14:22:26 -08002017 private static String getSettingValue(Bundle args) {
2018 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2019 }
2020
Svetoslav Ganove080da92016-12-21 17:10:35 -08002021 private static String getSettingTag(Bundle args) {
2022 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2023 }
2024
2025 private static boolean getSettingMakeDefault(Bundle args) {
2026 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2027 }
2028
2029 private static int getResetModeEnforcingPermission(Bundle args) {
2030 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2031 switch (mode) {
2032 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2033 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2034 throw new SecurityException("Only system, shell/root on a "
2035 + "debuggable build can reset to untrusted defaults");
2036 }
2037 return mode;
2038 }
2039 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2040 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2041 throw new SecurityException("Only system, shell/root on a "
2042 + "debuggable build can reset untrusted changes");
2043 }
2044 return mode;
2045 }
2046 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2047 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2048 throw new SecurityException("Only system, shell/root on a "
2049 + "debuggable build can reset to trusted defaults");
2050 }
2051 return mode;
2052 }
2053 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2054 return mode;
2055 }
2056 }
2057 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2058 }
2059
2060 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2061 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2062 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2063 && (appId == SHELL_UID || appId == ROOT_UID));
2064 }
2065
Svetoslav683914b2015-01-15 14:22:26 -08002066 private static String getValidTableOrThrow(Uri uri) {
2067 if (uri.getPathSegments().size() > 0) {
2068 String table = uri.getPathSegments().get(0);
2069 if (DatabaseHelper.isValidTable(table)) {
2070 return table;
2071 }
2072 throw new IllegalArgumentException("Bad root path: " + table);
2073 }
2074 throw new IllegalArgumentException("Invalid URI:" + uri);
2075 }
2076
2077 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002078 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002079 return new MatrixCursor(projection, 0);
2080 }
2081 MatrixCursor cursor = new MatrixCursor(projection, 1);
2082 appendSettingToCursor(cursor, setting);
2083 return cursor;
2084 }
2085
2086 private static String[] normalizeProjection(String[] projection) {
2087 if (projection == null) {
2088 return ALL_COLUMNS;
2089 }
2090
2091 final int columnCount = projection.length;
2092 for (int i = 0; i < columnCount; i++) {
2093 String column = projection[i];
2094 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2095 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002096 }
2097 }
2098
Svetoslav683914b2015-01-15 14:22:26 -08002099 return projection;
2100 }
2101
2102 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002103 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002104 return;
2105 }
Svetoslav683914b2015-01-15 14:22:26 -08002106 final int columnCount = cursor.getColumnCount();
2107
2108 String[] values = new String[columnCount];
2109
2110 for (int i = 0; i < columnCount; i++) {
2111 String column = cursor.getColumnName(i);
2112
2113 switch (column) {
2114 case Settings.NameValueTable._ID: {
2115 values[i] = setting.getId();
2116 } break;
2117
2118 case Settings.NameValueTable.NAME: {
2119 values[i] = setting.getName();
2120 } break;
2121
2122 case Settings.NameValueTable.VALUE: {
2123 values[i] = setting.getValue();
2124 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002125 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002126 }
2127
Svetoslav683914b2015-01-15 14:22:26 -08002128 cursor.addRow(values);
2129 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002130
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002131 private static boolean isKeyValid(String key) {
2132 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2133 }
2134
Svetoslav683914b2015-01-15 14:22:26 -08002135 private static final class Arguments {
2136 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2137 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2138
2139 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2140 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2141
2142 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2143 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2144
2145 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2146 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2147
2148 public final String table;
2149 public final String name;
2150
2151 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2152 final int segmentSize = uri.getPathSegments().size();
2153 switch (segmentSize) {
2154 case 1: {
2155 if (where != null
2156 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2157 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2158 && whereArgs.length == 1) {
2159 name = whereArgs[0];
2160 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002161 return;
Svetoslav683914b2015-01-15 14:22:26 -08002162 } else if (where != null
2163 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2164 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2165 final int startIndex = Math.max(where.indexOf("'"),
2166 where.indexOf("\"")) + 1;
2167 final int endIndex = Math.max(where.lastIndexOf("'"),
2168 where.lastIndexOf("\""));
2169 name = where.substring(startIndex, endIndex);
2170 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002171 return;
Svetoslav683914b2015-01-15 14:22:26 -08002172 } else if (supportAll && where == null && whereArgs == null) {
2173 name = null;
2174 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002175 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002176 }
Svetoslav683914b2015-01-15 14:22:26 -08002177 } break;
2178
Svetoslav28494652015-02-12 14:11:42 -08002179 case 2: {
2180 if (where == null && whereArgs == null) {
2181 name = uri.getPathSegments().get(1);
2182 table = computeTableForSetting(uri, name);
2183 return;
2184 }
2185 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002186 }
Svetoslav28494652015-02-12 14:11:42 -08002187
2188 EventLogTags.writeUnsupportedSettingsQuery(
2189 uri.toSafeString(), where, Arrays.toString(whereArgs));
2190 String message = String.format( "Supported SQL:\n"
2191 + " uri content://some_table/some_property with null where and where args\n"
2192 + " uri content://some_table with query name=? and single name as arg\n"
2193 + " uri content://some_table with query name=some_name and null args\n"
2194 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2195 Arrays.toString(whereArgs));
2196 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002197 }
2198
Svetoslav28494652015-02-12 14:11:42 -08002199 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002200 String table = getValidTableOrThrow(uri);
2201
2202 if (name != null) {
2203 if (sSystemMovedToSecureSettings.contains(name)) {
2204 table = TABLE_SECURE;
2205 }
2206
2207 if (sSystemMovedToGlobalSettings.contains(name)) {
2208 table = TABLE_GLOBAL;
2209 }
2210
2211 if (sSecureMovedToGlobalSettings.contains(name)) {
2212 table = TABLE_GLOBAL;
2213 }
2214
2215 if (sGlobalMovedToSecureSettings.contains(name)) {
2216 table = TABLE_SECURE;
2217 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002218 }
Svetoslav683914b2015-01-15 14:22:26 -08002219
2220 return table;
2221 }
2222 }
2223
2224 final class SettingsRegistry {
2225 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2226
Svetoslav683914b2015-01-15 14:22:26 -08002227 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2228 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2229 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002230 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002231 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002232
2233 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002234
2235 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2236
Svet Ganov53a441c2016-04-19 19:38:00 -07002237 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002238
Svetoslav7e0683b2015-08-03 16:02:52 -07002239 private final Handler mHandler;
2240
Svet Ganov53a441c2016-04-19 19:38:00 -07002241 private final BackupManager mBackupManager;
2242
Amith Yamasani39452022017-03-21 15:23:47 -07002243 private String mSettingsCreationBuildId;
2244
Svetoslav683914b2015-01-15 14:22:26 -08002245 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002246 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002247 mGenerationRegistry = new GenerationRegistry(mLock);
2248 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002249 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002250 syncSsaidTableOnStart();
2251 }
2252
2253 private void generateUserKeyLocked(int userId) {
2254 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002255 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002256 final SecureRandom rand = new SecureRandom();
2257 rand.nextBytes(keyBytes);
2258
2259 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002260 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002261
2262 // Store the key in the ssaid table.
2263 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2264 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2265 true, SettingsState.SYSTEM_PACKAGE_NAME);
2266
2267 if (!success) {
2268 throw new IllegalStateException("Ssaid settings not accessible");
2269 }
2270 }
2271
Mark Rathjen7599f132017-01-23 14:15:54 -08002272 private byte[] getLengthPrefix(byte[] data) {
2273 return ByteBuffer.allocate(4).putInt(data.length).array();
2274 }
2275
Christopher Tateb218e762017-04-05 16:34:07 -07002276 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002277 // Read the user's key from the ssaid table.
2278 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002279 if (userKeySetting == null || userKeySetting.isNull()
2280 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002281 // Lazy initialize and store the user key.
2282 generateUserKeyLocked(userId);
2283 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002284 if (userKeySetting == null || userKeySetting.isNull()
2285 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002286 throw new IllegalStateException("User key not accessible");
2287 }
2288 }
2289 final String userKey = userKeySetting.getValue();
2290
2291 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002292 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2293
2294 // Validate that the key is of expected length.
2295 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2296 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002297 throw new IllegalStateException("User key invalid");
2298 }
2299
Mark Rathjen7599f132017-01-23 14:15:54 -08002300 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002301 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002302 m = Mac.getInstance("HmacSHA256");
2303 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002304 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002305 throw new IllegalStateException("HmacSHA256 is not available", e);
2306 } catch (InvalidKeyException e) {
2307 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002308 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002309
Mark Rathjenf42dd912017-06-05 19:04:34 -07002310 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002311 for (int i = 0; i < callingPkg.signatures.length; i++) {
2312 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002313 m.update(getLengthPrefix(sig), 0, 4);
2314 m.update(sig);
2315 }
Mark Rathjend891f012017-01-19 04:10:37 +00002316
2317 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002318 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2319 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002320
2321 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002322 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002323 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2324 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002325 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002326
2327 if (!success) {
2328 throw new IllegalStateException("Ssaid settings not accessible");
2329 }
2330
2331 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2332 }
2333
2334 public void syncSsaidTableOnStart() {
2335 synchronized (mLock) {
2336 // Verify that each user's packages and ssaid's are in sync.
2337 for (UserInfo user : mUserManager.getUsers(true)) {
2338 // Get all uids for the user's packages.
2339 final List<PackageInfo> packages;
2340 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002341 packages = mPackageManager.getInstalledPackages(
2342 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2343 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002344 } catch (RemoteException e) {
2345 throw new IllegalStateException("Package manager not available");
2346 }
2347 final Set<String> appUids = new HashSet<>();
2348 for (PackageInfo info : packages) {
2349 appUids.add(Integer.toString(info.applicationInfo.uid));
2350 }
2351
2352 // Get all uids currently stored in the user's ssaid table.
2353 final Set<String> ssaidUids = new HashSet<>(
2354 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2355 ssaidUids.remove(SSAID_USER_KEY);
2356
2357 // Perform a set difference for the appUids and ssaidUids.
2358 ssaidUids.removeAll(appUids);
2359
2360 // If there are ssaidUids left over they need to be removed from the table.
2361 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2362 user.id);
2363 for (String uid : ssaidUids) {
2364 ssaidSettings.deleteSettingLocked(uid);
2365 }
2366 }
2367 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002368 }
2369
Svetoslav683914b2015-01-15 14:22:26 -08002370 public List<String> getSettingsNamesLocked(int type, int userId) {
2371 final int key = makeKey(type, userId);
2372 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002373 if (settingsState == null) {
2374 return new ArrayList<String>();
2375 }
Svetoslav683914b2015-01-15 14:22:26 -08002376 return settingsState.getSettingNamesLocked();
2377 }
2378
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002379 public SparseBooleanArray getKnownUsersLocked() {
2380 SparseBooleanArray users = new SparseBooleanArray();
2381 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2382 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2383 }
2384 return users;
2385 }
2386
Kweku Adamsb0886f32017-10-31 15:32:09 -07002387 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002388 public SettingsState getSettingsLocked(int type, int userId) {
2389 final int key = makeKey(type, userId);
2390 return peekSettingsStateLocked(key);
2391 }
2392
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002393 public boolean ensureSettingsForUserLocked(int userId) {
2394 // First make sure this user actually exists.
2395 if (mUserManager.getUserInfo(userId) == null) {
2396 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2397 return false;
2398 }
2399
Svetoslav683914b2015-01-15 14:22:26 -08002400 // Migrate the setting for this user if needed.
2401 migrateLegacySettingsForUserIfNeededLocked(userId);
2402
Matt Pape1b31a332018-10-17 09:58:28 -07002403 // Ensure config settings loaded if owner.
2404 if (userId == UserHandle.USER_SYSTEM) {
2405 final int configKey
2406 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2407 ensureSettingsStateLocked(configKey);
2408 }
2409
Svetoslav683914b2015-01-15 14:22:26 -08002410 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002411 if (userId == UserHandle.USER_SYSTEM) {
2412 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002413 ensureSettingsStateLocked(globalKey);
2414 }
2415
2416 // Ensure secure settings loaded.
2417 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2418 ensureSettingsStateLocked(secureKey);
2419
2420 // Make sure the secure settings have an Android id set.
2421 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2422 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2423
2424 // Ensure system settings loaded.
2425 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2426 ensureSettingsStateLocked(systemKey);
2427
Mark Rathjend891f012017-01-19 04:10:37 +00002428 // Ensure secure settings loaded.
2429 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2430 ensureSettingsStateLocked(ssaidKey);
2431
Svetoslav683914b2015-01-15 14:22:26 -08002432 // Upgrade the settings to the latest version.
2433 UpgradeController upgrader = new UpgradeController(userId);
2434 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002435 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002436 }
2437
2438 private void ensureSettingsStateLocked(int key) {
2439 if (mSettingsStates.get(key) == null) {
2440 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002441 SettingsState settingsState = new SettingsState(getContext(), mLock,
2442 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002443 mSettingsStates.put(key, settingsState);
2444 }
2445 }
2446
2447 public void removeUserStateLocked(int userId, boolean permanently) {
2448 // We always keep the global settings in memory.
2449
2450 // Nuke system settings.
2451 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2452 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2453 if (systemSettingsState != null) {
2454 if (permanently) {
2455 mSettingsStates.remove(systemKey);
2456 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002457 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002458 systemSettingsState.destroyLocked(new Runnable() {
2459 @Override
2460 public void run() {
2461 mSettingsStates.remove(systemKey);
2462 }
2463 });
2464 }
2465 }
2466
2467 // Nuke secure settings.
2468 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2469 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2470 if (secureSettingsState != null) {
2471 if (permanently) {
2472 mSettingsStates.remove(secureKey);
2473 secureSettingsState.destroyLocked(null);
2474 } else {
2475 secureSettingsState.destroyLocked(new Runnable() {
2476 @Override
2477 public void run() {
2478 mSettingsStates.remove(secureKey);
2479 }
2480 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002481 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002482 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002483
Mark Rathjend891f012017-01-19 04:10:37 +00002484 // Nuke ssaid settings.
2485 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2486 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2487 if (ssaidSettingsState != null) {
2488 if (permanently) {
2489 mSettingsStates.remove(ssaidKey);
2490 ssaidSettingsState.destroyLocked(null);
2491 } else {
2492 ssaidSettingsState.destroyLocked(new Runnable() {
2493 @Override
2494 public void run() {
2495 mSettingsStates.remove(ssaidKey);
2496 }
2497 });
2498 }
2499 }
2500
Svet Ganov53a441c2016-04-19 19:38:00 -07002501 // Nuke generation tracking data
2502 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002503 }
2504
Svetoslav683914b2015-01-15 14:22:26 -08002505 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002506 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2507 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002508 final int key = makeKey(type, userId);
2509
Svetoslav Ganove080da92016-12-21 17:10:35 -08002510 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002511 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002512 if (settingsState != null) {
2513 success = settingsState.insertSettingLocked(name, value,
2514 tag, makeDefault, packageName);
2515 }
Svetoslav683914b2015-01-15 14:22:26 -08002516
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002517 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2518 settingsState.persistSyncLocked();
2519 }
2520
Svet Ganov53a441c2016-04-19 19:38:00 -07002521 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002522 notifyForSettingsChange(key, name);
2523 }
2524 return success;
2525 }
2526
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002527 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2528 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002529 final int key = makeKey(type, userId);
2530
Svetoslav Ganove080da92016-12-21 17:10:35 -08002531 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002532 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002533 if (settingsState != null) {
2534 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002535 }
Svetoslav683914b2015-01-15 14:22:26 -08002536
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002537 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2538 settingsState.persistSyncLocked();
2539 }
2540
Svet Ganov53a441c2016-04-19 19:38:00 -07002541 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002542 notifyForSettingsChange(key, name);
2543 }
2544 return success;
2545 }
2546
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002547 public boolean updateSettingLocked(int type, int userId, String name, String value,
2548 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2549 Set<String> criticalSettings) {
2550 final int key = makeKey(type, userId);
2551
2552 boolean success = false;
2553 SettingsState settingsState = peekSettingsStateLocked(key);
2554 if (settingsState != null) {
2555 success = settingsState.updateSettingLocked(name, value, tag,
2556 makeDefault, packageName);
2557 }
2558
2559 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2560 settingsState.persistSyncLocked();
2561 }
2562
2563 if (forceNotify || success) {
2564 notifyForSettingsChange(key, name);
2565 }
2566
2567 return success;
2568 }
2569
Svetoslav683914b2015-01-15 14:22:26 -08002570 public Setting getSettingLocked(int type, int userId, String name) {
2571 final int key = makeKey(type, userId);
2572
2573 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002574 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002575 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002576 }
Mark Rathjend891f012017-01-19 04:10:37 +00002577
2578 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002579 return settingsState.getSettingLocked(name);
2580 }
2581
Svetoslav Ganove080da92016-12-21 17:10:35 -08002582 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2583 String tag) {
2584 final int key = makeKey(type, userId);
2585 SettingsState settingsState = peekSettingsStateLocked(key);
2586 if (settingsState == null) {
2587 return;
2588 }
2589
2590 switch (mode) {
2591 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2592 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002593 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002594 Setting setting = settingsState.getSettingLocked(name);
2595 if (packageName.equals(setting.getPackageName())) {
2596 if (tag != null && !tag.equals(setting.getTag())) {
2597 continue;
2598 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002599 if (settingsState.resetSettingLocked(name)) {
2600 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002601 notifyForSettingsChange(key, name);
2602 }
2603 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002604 if (someSettingChanged) {
2605 settingsState.persistSyncLocked();
2606 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002607 }
2608 } break;
2609
2610 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2611 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002612 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002613 Setting setting = settingsState.getSettingLocked(name);
2614 if (!SettingsState.isSystemPackage(getContext(),
2615 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002616 if (settingsState.resetSettingLocked(name)) {
2617 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002618 notifyForSettingsChange(key, name);
2619 }
2620 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002621 if (someSettingChanged) {
2622 settingsState.persistSyncLocked();
2623 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002624 }
2625 } break;
2626
2627 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2628 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002629 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002630 Setting setting = settingsState.getSettingLocked(name);
2631 if (!SettingsState.isSystemPackage(getContext(),
2632 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002633 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002634 if (settingsState.resetSettingLocked(name)) {
2635 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002636 notifyForSettingsChange(key, name);
2637 }
2638 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002639 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002640 notifyForSettingsChange(key, name);
2641 }
2642 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002643 if (someSettingChanged) {
2644 settingsState.persistSyncLocked();
2645 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002646 }
2647 } break;
2648
2649 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2650 for (String name : settingsState.getSettingNamesLocked()) {
2651 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002652 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002653 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002654 if (settingsState.resetSettingLocked(name)) {
2655 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002656 notifyForSettingsChange(key, name);
2657 }
2658 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002659 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002660 notifyForSettingsChange(key, name);
2661 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002662 if (someSettingChanged) {
2663 settingsState.persistSyncLocked();
2664 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002665 }
2666 } break;
2667 }
2668 }
2669
Zimuzoc56192c2018-07-25 10:40:01 +01002670 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002671 // Global and secure settings are signature protected. Apps signed
2672 // by the platform certificate are generally not uninstalled and
2673 // the main exception is tests. We trust components signed
2674 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002675
2676 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2677 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002678 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002679 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002680 }
Svetoslav683914b2015-01-15 14:22:26 -08002681 }
2682
Mark Rathjend891f012017-01-19 04:10:37 +00002683 public void onUidRemovedLocked(int uid) {
2684 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2685 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002686 if (ssaidSettings != null) {
2687 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2688 }
Mark Rathjend891f012017-01-19 04:10:37 +00002689 }
2690
Kweku Adamsb0886f32017-10-31 15:32:09 -07002691 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002692 private SettingsState peekSettingsStateLocked(int key) {
2693 SettingsState settingsState = mSettingsStates.get(key);
2694 if (settingsState != null) {
2695 return settingsState;
2696 }
2697
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002698 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2699 return null;
2700 }
Svetoslav683914b2015-01-15 14:22:26 -08002701 return mSettingsStates.get(key);
2702 }
2703
2704 private void migrateAllLegacySettingsIfNeeded() {
2705 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002706 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002707 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002708 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002709 return;
2710 }
2711
Amith Yamasani39452022017-03-21 15:23:47 -07002712 mSettingsCreationBuildId = Build.ID;
2713
Svetoslav683914b2015-01-15 14:22:26 -08002714 final long identity = Binder.clearCallingIdentity();
2715 try {
2716 List<UserInfo> users = mUserManager.getUsers(true);
2717
2718 final int userCount = users.size();
2719 for (int i = 0; i < userCount; i++) {
2720 final int userId = users.get(i).id;
2721
2722 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2723 SQLiteDatabase database = dbHelper.getWritableDatabase();
2724 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2725
2726 // Upgrade to the latest version.
2727 UpgradeController upgrader = new UpgradeController(userId);
2728 upgrader.upgradeIfNeededLocked();
2729
2730 // Drop from memory if not a running user.
2731 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2732 removeUserStateLocked(userId, false);
2733 }
2734 }
2735 } finally {
2736 Binder.restoreCallingIdentity(identity);
2737 }
2738 }
2739 }
2740
2741 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2742 // Every user has secure settings and if no file we need to migrate.
2743 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2744 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002745 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002746 return;
2747 }
2748
2749 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2750 SQLiteDatabase database = dbHelper.getWritableDatabase();
2751
2752 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2753 }
2754
2755 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2756 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002757 // Move over the system settings.
2758 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2759 ensureSettingsStateLocked(systemKey);
2760 SettingsState systemSettings = mSettingsStates.get(systemKey);
2761 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2762 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002763
2764 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002765 // Do this after System settings, since this is the first thing we check when deciding
2766 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002767 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2768 ensureSettingsStateLocked(secureKey);
2769 SettingsState secureSettings = mSettingsStates.get(secureKey);
2770 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2771 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2772 secureSettings.persistSyncLocked();
2773
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002774 // Move over the global settings if owner.
2775 // Do this last, since this is the first thing we check when deciding
2776 // to skip over migration from db to xml for owner user.
2777 if (userId == UserHandle.USER_SYSTEM) {
2778 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2779 ensureSettingsStateLocked(globalKey);
2780 SettingsState globalSettings = mSettingsStates.get(globalKey);
2781 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002782 // If this was just created
2783 if (mSettingsCreationBuildId != null) {
2784 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2785 mSettingsCreationBuildId, null, true,
2786 SettingsState.SYSTEM_PACKAGE_NAME);
2787 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002788 globalSettings.persistSyncLocked();
2789 }
Svetoslav683914b2015-01-15 14:22:26 -08002790
2791 // Drop the database as now all is moved and persisted.
2792 if (DROP_DATABASE_ON_MIGRATION) {
2793 dbHelper.dropDatabase();
2794 } else {
2795 dbHelper.backupDatabase();
2796 }
2797 }
2798
2799 private void migrateLegacySettingsLocked(SettingsState settingsState,
2800 SQLiteDatabase database, String table) {
2801 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2802 queryBuilder.setTables(table);
2803
2804 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2805 null, null, null, null, null);
2806
2807 if (cursor == null) {
2808 return;
2809 }
2810
2811 try {
2812 if (!cursor.moveToFirst()) {
2813 return;
2814 }
2815
2816 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2817 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2818
2819 settingsState.setVersionLocked(database.getVersion());
2820
2821 while (!cursor.isAfterLast()) {
2822 String name = cursor.getString(nameColumnIdx);
2823 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002824 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002825 SettingsState.SYSTEM_PACKAGE_NAME);
2826 cursor.moveToNext();
2827 }
2828 } finally {
2829 cursor.close();
2830 }
2831 }
2832
Andreas Gampeb58893072018-09-05 16:52:31 -07002833 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002834 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2835 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2836
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002837 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002838 return;
2839 }
2840
2841 final int userId = getUserIdFromKey(secureSettings.mKey);
2842
2843 final UserInfo user;
2844 final long identity = Binder.clearCallingIdentity();
2845 try {
2846 user = mUserManager.getUserInfo(userId);
2847 } finally {
2848 Binder.restoreCallingIdentity(identity);
2849 }
2850 if (user == null) {
2851 // Can happen due to races when deleting users - treat as benign.
2852 return;
2853 }
2854
2855 String androidId = Long.toHexString(new SecureRandom().nextLong());
2856 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002857 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002858
2859 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2860 + "] for user " + userId);
2861
2862 // Write a drop box entry if it's a restricted profile
2863 if (user.isRestricted()) {
2864 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2865 Context.DROPBOX_SERVICE);
2866 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2867 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2868 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2869 }
2870 }
2871 }
2872
2873 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07002874 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07002875 mGenerationRegistry.incrementGeneration(key);
2876
Svet Ganov945864c2018-03-22 21:49:10 -07002877 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06002878 final long token = Binder.clearCallingIdentity();
2879 try {
2880 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2881 // When the global kill switch is updated, send the
2882 // change notification for the location setting.
2883 notifyLocationChangeForRunningUsers();
2884 }
2885 notifyGlobalSettingChangeForRunningUsers(key, name);
2886 } finally {
2887 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07002888 }
Svet Ganov945864c2018-03-22 21:49:10 -07002889 } else {
2890 final int userId = getUserIdFromKey(key);
2891 final Uri uri = getNotificationUriFor(key, name);
2892 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2893 userId, 0, uri).sendToTarget();
2894 if (isSecureSettingsKey(key)) {
2895 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2896 sSecureCloneToManagedSettings);
2897 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2898 sSystemCloneFromParentOnDependency.values());
2899 } else if (isSystemSettingsKey(key)) {
2900 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2901 sSystemCloneToManagedSettings);
2902 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002903 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002904
Svet Ganov945864c2018-03-22 21:49:10 -07002905 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07002906 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002907 }
2908
Svet Ganov53a441c2016-04-19 19:38:00 -07002909 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002910 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002911 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002912 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002913 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002914 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07002915 final int key = makeKey(type, profileId);
2916 // Increment the generation first, so observers always see the new value
2917 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07002918 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002919 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002920 }
2921 }
2922 }
Svetoslav683914b2015-01-15 14:22:26 -08002923 }
2924
Svet Ganov945864c2018-03-22 21:49:10 -07002925 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
2926 // Important: No need to update generation for each user as there
2927 // is a singleton generation entry for the global settings which
2928 // is already incremented be the caller.
2929 final Uri uri = getNotificationUriFor(key, name);
2930 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
2931 for (int i = 0; i < users.size(); i++) {
2932 final int userId = users.get(i).id;
2933 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
2934 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2935 userId, 0, uri).sendToTarget();
2936 }
2937 }
2938 }
2939
Makoto Onuki0000d322017-11-28 16:31:47 -08002940 private void notifyLocationChangeForRunningUsers() {
2941 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2942
2943 for (int i = 0; i < users.size(); i++) {
2944 final int userId = users.get(i).id;
2945
2946 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2947 continue;
2948 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002949
Svet Ganov945864c2018-03-22 21:49:10 -07002950 // Increment the generation first, so observers always see the new value
2951 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2952 mGenerationRegistry.incrementGeneration(key);
2953
2954 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08002955 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2956 userId, 0, uri).sendToTarget();
2957 }
2958 }
2959
Matt Pape1b31a332018-10-17 09:58:28 -07002960 private boolean isConfigSettingsKey(int key) {
2961 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
2962 }
2963
Svetoslav683914b2015-01-15 14:22:26 -08002964 private boolean isGlobalSettingsKey(int key) {
2965 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2966 }
2967
2968 private boolean isSystemSettingsKey(int key) {
2969 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2970 }
2971
2972 private boolean isSecureSettingsKey(int key) {
2973 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2974 }
2975
Mark Rathjend891f012017-01-19 04:10:37 +00002976 private boolean isSsaidSettingsKey(int key) {
2977 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2978 }
2979
Svetoslav683914b2015-01-15 14:22:26 -08002980 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07002981 if (isConfigSettingsKey(key)) {
2982 final int userId = getUserIdFromKey(key);
2983 return new File(Environment.getUserSystemDirectory(userId),
2984 SETTINGS_FILE_CONFIG);
2985 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08002986 final int userId = getUserIdFromKey(key);
2987 return new File(Environment.getUserSystemDirectory(userId),
2988 SETTINGS_FILE_GLOBAL);
2989 } else if (isSystemSettingsKey(key)) {
2990 final int userId = getUserIdFromKey(key);
2991 return new File(Environment.getUserSystemDirectory(userId),
2992 SETTINGS_FILE_SYSTEM);
2993 } else if (isSecureSettingsKey(key)) {
2994 final int userId = getUserIdFromKey(key);
2995 return new File(Environment.getUserSystemDirectory(userId),
2996 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002997 } else if (isSsaidSettingsKey(key)) {
2998 final int userId = getUserIdFromKey(key);
2999 return new File(Environment.getUserSystemDirectory(userId),
3000 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003001 } else {
3002 throw new IllegalArgumentException("Invalid settings key:" + key);
3003 }
3004 }
3005
3006 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003007 if (isConfigSettingsKey(key)) {
3008 return (name != null) ? Uri.withAppendedPath(CONFIG_CONTENT_URI, name)
3009 : CONFIG_CONTENT_URI;
3010 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003011 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3012 : Settings.Global.CONTENT_URI;
3013 } else if (isSecureSettingsKey(key)) {
3014 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3015 : Settings.Secure.CONTENT_URI;
3016 } else if (isSystemSettingsKey(key)) {
3017 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3018 : Settings.System.CONTENT_URI;
3019 } else {
3020 throw new IllegalArgumentException("Invalid settings key:" + key);
3021 }
3022 }
3023
3024 private int getMaxBytesPerPackageForType(int type) {
3025 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003026 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003027 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003028 case SETTINGS_TYPE_SECURE:
3029 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003030 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3031 }
3032
3033 default: {
3034 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3035 }
3036 }
3037 }
3038
Svetoslav7e0683b2015-08-03 16:02:52 -07003039 private final class MyHandler extends Handler {
3040 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3041 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3042
3043 public MyHandler(Looper looper) {
3044 super(looper);
3045 }
3046
3047 @Override
3048 public void handleMessage(Message msg) {
3049 switch (msg.what) {
3050 case MSG_NOTIFY_URI_CHANGED: {
3051 final int userId = msg.arg1;
3052 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003053 try {
3054 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3055 } catch (SecurityException e) {
3056 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3057 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003058 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003059 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3060 }
3061 } break;
3062
3063 case MSG_NOTIFY_DATA_CHANGED: {
3064 mBackupManager.dataChanged();
3065 } break;
3066 }
3067 }
3068 }
3069
Svetoslav683914b2015-01-15 14:22:26 -08003070 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003071 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003072
3073 private final int mUserId;
3074
3075 public UpgradeController(int userId) {
3076 mUserId = userId;
3077 }
3078
3079 public void upgradeIfNeededLocked() {
3080 // The version of all settings for a user is the same (all users have secure).
3081 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003082 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003083
3084 // Try an update from the current state.
3085 final int oldVersion = secureSettings.getVersionLocked();
3086 final int newVersion = SETTINGS_VERSION;
3087
Svet Ganovc9755bc2015-03-28 13:21:22 -07003088 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003089 if (oldVersion == newVersion) {
3090 return;
3091 }
3092
3093 // Try to upgrade.
3094 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3095
3096 // If upgrade failed start from scratch and upgrade.
3097 if (curVersion != newVersion) {
3098 // Drop state we have for this user.
3099 removeUserStateLocked(mUserId, true);
3100
3101 // Recreate the database.
3102 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3103 SQLiteDatabase database = dbHelper.getWritableDatabase();
3104 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3105
3106 // Migrate the settings for this user.
3107 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3108
3109 // Now upgrade should work fine.
3110 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003111
3112 // Make a note what happened, so we don't wonder why data was lost
3113 String reason = "Settings rebuilt! Current version: "
3114 + curVersion + " while expected: " + newVersion;
3115 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003116 Settings.Global.DATABASE_DOWNGRADE_REASON,
3117 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003118 }
3119
3120 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003121 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003122 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003123 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003124 globalSettings.setVersionLocked(newVersion);
3125 }
3126
3127 // Set the secure settings version.
3128 secureSettings.setVersionLocked(newVersion);
3129
3130 // Set the system settings version.
3131 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003132 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003133 systemSettings.setVersionLocked(newVersion);
3134 }
3135
3136 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003137 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003138 }
3139
3140 private SettingsState getSecureSettingsLocked(int userId) {
3141 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3142 }
3143
Mark Rathjend891f012017-01-19 04:10:37 +00003144 private SettingsState getSsaidSettingsLocked(int userId) {
3145 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3146 }
3147
Svetoslav683914b2015-01-15 14:22:26 -08003148 private SettingsState getSystemSettingsLocked(int userId) {
3149 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3150 }
3151
Jeff Brown503cffc2015-03-26 18:08:51 -07003152 /**
3153 * You must perform all necessary mutations to bring the settings
3154 * for this user from the old to the new version. When you add a new
3155 * upgrade step you *must* update SETTINGS_VERSION.
3156 *
3157 * This is an example of moving a setting from secure to global.
3158 *
3159 * // v119: Example settings changes.
3160 * if (currentVersion == 118) {
3161 * if (userId == UserHandle.USER_OWNER) {
3162 * // Remove from the secure settings.
3163 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3164 * String name = "example_setting_to_move";
3165 * String value = secureSettings.getSetting(name);
3166 * secureSettings.deleteSetting(name);
3167 *
3168 * // Add to the global settings.
3169 * SettingsState globalSettings = getGlobalSettingsLocked();
3170 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3171 * }
3172 *
3173 * // Update the current version.
3174 * currentVersion = 119;
3175 * }
3176 */
Svetoslav683914b2015-01-15 14:22:26 -08003177 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3178 if (DEBUG) {
3179 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3180 + oldVersion + " to version: " + newVersion);
3181 }
3182
Jeff Brown503cffc2015-03-26 18:08:51 -07003183 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003184
John Spurlocke11ae112015-05-11 16:09:03 -04003185 // v119: Reset zen + ringer mode.
3186 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003187 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003188 final SettingsState globalSettings = getGlobalSettingsLocked();
3189 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003190 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3191 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003192 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003193 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3194 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003195 }
3196 currentVersion = 119;
3197 }
3198
Jason Monk27bbb2d2015-03-31 16:46:39 -04003199 // v120: Add double tap to wake setting.
3200 if (currentVersion == 119) {
3201 SettingsState secureSettings = getSecureSettingsLocked(userId);
3202 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3203 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003204 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003205 SettingsState.SYSTEM_PACKAGE_NAME);
3206
3207 currentVersion = 120;
3208 }
3209
Svetoslav7e0683b2015-08-03 16:02:52 -07003210 if (currentVersion == 120) {
3211 // Before 121, we used a different string encoding logic. We just bump the
3212 // version here; SettingsState knows how to handle pre-version 120 files.
3213 currentVersion = 121;
3214 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003215
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003216 if (currentVersion == 121) {
3217 // Version 122: allow OEMs to set a default payment component in resources.
3218 // Note that we only write the default if no default has been set;
3219 // if there is, we just leave the default at whatever it currently is.
3220 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3221 String defaultComponent = (getContext().getResources().getString(
3222 R.string.def_nfc_payment_component));
3223 Setting currentSetting = secureSettings.getSettingLocked(
3224 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3225 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003226 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003227 secureSettings.insertSettingLocked(
3228 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003229 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003230 }
3231 currentVersion = 122;
3232 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003233
3234 if (currentVersion == 122) {
3235 // Version 123: Adding a default value for the ability to add a user from
3236 // the lock screen.
3237 if (userId == UserHandle.USER_SYSTEM) {
3238 final SettingsState globalSettings = getGlobalSettingsLocked();
3239 Setting currentSetting = globalSettings.getSettingLocked(
3240 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003241 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003242 globalSettings.insertSettingLocked(
3243 Settings.Global.ADD_USERS_WHEN_LOCKED,
3244 getContext().getResources().getBoolean(
3245 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003246 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003247 }
3248 }
3249 currentVersion = 123;
3250 }
Bryce Leebd179282015-12-17 19:01:37 -08003251
3252 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003253 final SettingsState globalSettings = getGlobalSettingsLocked();
3254 String defaultDisabledProfiles = (getContext().getResources().getString(
3255 R.string.def_bluetooth_disabled_profiles));
3256 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003257 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003258 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003259 }
3260
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003261 if (currentVersion == 124) {
3262 // Version 124: allow OEMs to set a default value for whether IME should be
3263 // shown when a physical keyboard is connected.
3264 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3265 Setting currentSetting = secureSettings.getSettingLocked(
3266 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003267 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003268 secureSettings.insertSettingLocked(
3269 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3270 getContext().getResources().getBoolean(
3271 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003272 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003273 }
3274 currentVersion = 125;
3275 }
3276
Ruben Brunk98576cf2016-03-07 18:54:28 -08003277 if (currentVersion == 125) {
3278 // Version 125: Allow OEMs to set the default VR service.
3279 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3280
3281 Setting currentSetting = secureSettings.getSettingLocked(
3282 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003283 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003284 ArraySet<ComponentName> l =
3285 SystemConfig.getInstance().getDefaultVrComponents();
3286
3287 if (l != null && !l.isEmpty()) {
3288 StringBuilder b = new StringBuilder();
3289 boolean start = true;
3290 for (ComponentName c : l) {
3291 if (!start) {
3292 b.append(':');
3293 }
3294 b.append(c.flattenToString());
3295 start = false;
3296 }
3297 secureSettings.insertSettingLocked(
3298 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003299 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003300 }
3301
3302 }
3303 currentVersion = 126;
3304 }
3305
Daniel U02ba6122016-04-01 18:41:42 +01003306 if (currentVersion == 126) {
3307 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3308 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3309 if (mUserManager.isManagedProfile(userId)) {
3310 final SettingsState systemSecureSettings =
3311 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3312
3313 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3314 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003315 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003316 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3317 secureSettings.insertSettingLocked(
3318 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003319 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003320 SettingsState.SYSTEM_PACKAGE_NAME);
3321 }
3322
3323 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3324 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003325 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003326 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3327 secureSettings.insertSettingLocked(
3328 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003329 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003330 SettingsState.SYSTEM_PACKAGE_NAME);
3331 }
3332 }
3333 currentVersion = 127;
3334 }
3335
Steven Ngdc20ba62016-04-26 18:19:04 +01003336 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003337 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003338 currentVersion = 128;
3339 }
3340
Julia Reynolds1f721e12016-07-11 08:50:58 -04003341 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003342 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003343 currentVersion = 129;
3344 }
3345
Dan Sandler71f85e92016-07-20 13:46:05 -04003346 if (currentVersion == 129) {
3347 // default longpress timeout changed from 500 to 400. If unchanged from the old
3348 // default, update to the new default.
3349 final SettingsState systemSecureSettings =
3350 getSecureSettingsLocked(userId);
3351 final String oldValue = systemSecureSettings.getSettingLocked(
3352 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3353 if (TextUtils.equals("500", oldValue)) {
3354 systemSecureSettings.insertSettingLocked(
3355 Settings.Secure.LONG_PRESS_TIMEOUT,
3356 String.valueOf(getContext().getResources().getInteger(
3357 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003358 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003359 }
3360 currentVersion = 130;
3361 }
3362
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003363 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003364 // Split Ambient settings
3365 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3366 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3367 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3368
3369 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003370 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003371 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003372 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003373 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003374 }
3375 currentVersion = 131;
3376 }
3377
3378 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003379 // Initialize new multi-press timeout to default value
3380 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3381 final String oldValue = systemSecureSettings.getSettingLocked(
3382 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3383 if (TextUtils.equals(null, oldValue)) {
3384 systemSecureSettings.insertSettingLocked(
3385 Settings.Secure.MULTI_PRESS_TIMEOUT,
3386 String.valueOf(getContext().getResources().getInteger(
3387 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003388 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003389 }
3390
Adrian Roos69741a22016-10-21 14:49:17 -07003391 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003392 }
3393
Adrian Roos69741a22016-10-21 14:49:17 -07003394 if (currentVersion == 132) {
3395 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003396 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3397 String defaultSyncParentSounds = (getContext().getResources()
3398 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3399 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003400 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3401 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003402 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003403 }
3404
Adrian Roos69741a22016-10-21 14:49:17 -07003405 if (currentVersion == 133) {
3406 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003407 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3408 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3409 null) {
3410 String defaultEndButtonBehavior = Integer.toString(getContext()
3411 .getResources().getInteger(R.integer.def_end_button_behavior));
3412 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003413 defaultEndButtonBehavior, null, true,
3414 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003415 }
Adrian Roos69741a22016-10-21 14:49:17 -07003416 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003417 }
3418
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003419 if (currentVersion == 134) {
3420 // Remove setting that specifies if magnification values should be preserved.
3421 // This setting defaulted to true and never has a UI.
3422 getSecureSettingsLocked(userId).deleteSettingLocked(
3423 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3424 currentVersion = 135;
3425 }
3426
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003427 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003428 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003429 currentVersion = 136;
3430 }
3431
Mark Rathjend891f012017-01-19 04:10:37 +00003432 if (currentVersion == 136) {
3433 // Version 136: Store legacy SSAID for all apps currently installed on the
3434 // device as first step in migrating SSAID to be unique per application.
3435
3436 final boolean isUpgrade;
3437 try {
3438 isUpgrade = mPackageManager.isUpgrade();
3439 } catch (RemoteException e) {
3440 throw new IllegalStateException("Package manager not available");
3441 }
3442 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3443 // user data or first boot on a new device should use new ssaid generation.
3444 if (isUpgrade) {
3445 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003446 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3447 userId, Settings.Secure.ANDROID_ID);
3448 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3449 || legacySsaidSetting.getValue() == null) {
3450 throw new IllegalStateException("Legacy ssaid not accessible");
3451 }
3452 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003453
3454 // Fill each uid with the legacy ssaid to be backwards compatible.
3455 final List<PackageInfo> packages;
3456 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003457 packages = mPackageManager.getInstalledPackages(
3458 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3459 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003460 } catch (RemoteException e) {
3461 throw new IllegalStateException("Package manager not available");
3462 }
3463
3464 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3465 for (PackageInfo info : packages) {
3466 // Check if the UID already has an entry in the table.
3467 final String uid = Integer.toString(info.applicationInfo.uid);
3468 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3469
3470 if (ssaid.isNull() || ssaid.getValue() == null) {
3471 // Android Id doesn't exist for this package so create it.
3472 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3473 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003474 if (DEBUG) {
3475 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3476 }
Mark Rathjend891f012017-01-19 04:10:37 +00003477 }
3478 }
3479 }
3480
3481 currentVersion = 137;
3482 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003483 if (currentVersion == 137) {
3484 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3485 // default value set to 1. The user can no longer change the value of this
3486 // setting through the UI.
3487 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3488 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003489 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3490 && secureSetting.getSettingLocked(
3491 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3492
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003493 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3494 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003495 // For managed profiles with profile owners, DevicePolicyManagerService
3496 // may want to set the user restriction in this case
3497 secureSetting.insertSettingLocked(
3498 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3499 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003500 }
3501 currentVersion = 138;
3502 }
Mark Rathjend891f012017-01-19 04:10:37 +00003503
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003504 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003505 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003506 currentVersion = 139;
3507 }
3508
Phil Weaver385912e2017-02-10 10:06:56 -08003509 if (currentVersion == 139) {
3510 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3511 // the user can no longer change the value of this setting through the UI.
3512 // Force to true.
3513 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3514 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3515 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3516 currentVersion = 140;
3517 }
3518
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003519 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003520 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003521 currentVersion = 141;
3522 }
3523
Svet Ganov13701552017-02-23 12:45:17 -08003524 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003525 // This implementation was incorrectly setting the current value of
3526 // settings changed by non-system packages as the default which default
3527 // is set by the system. We add a new upgrade step at the end to properly
3528 // handle this case which would also fix incorrect changes made by the
3529 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003530 currentVersion = 142;
3531 }
3532
Stephen Chen5d0922f2017-03-27 10:28:04 -07003533 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003534 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003535 if (userId == UserHandle.USER_SYSTEM) {
3536 final SettingsState globalSettings = getGlobalSettingsLocked();
3537 Setting currentSetting = globalSettings.getSettingLocked(
3538 Settings.Global.WIFI_WAKEUP_ENABLED);
3539 if (currentSetting.isNull()) {
3540 globalSettings.insertSettingLocked(
3541 Settings.Global.WIFI_WAKEUP_ENABLED,
3542 getContext().getResources().getBoolean(
3543 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3544 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3545 }
3546 }
3547
3548 currentVersion = 143;
3549 }
3550
Felipe Lemeff355092017-04-03 12:55:02 -07003551 if (currentVersion == 143) {
3552 // Version 144: Set a default value for Autofill service.
3553 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3554 final Setting currentSetting = secureSettings
3555 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3556 if (currentSetting.isNull()) {
3557 final String defaultValue = getContext().getResources().getString(
3558 com.android.internal.R.string.config_defaultAutofillService);
3559 if (defaultValue != null) {
3560 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3561 + "for user " + userId);
3562 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3563 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3564 }
3565 }
3566
3567 currentVersion = 144;
3568 }
3569
Jeremy Joslin45caa252017-05-04 11:22:46 -07003570 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003571 // Version 145: Removed
3572 currentVersion = 145;
3573 }
3574
3575 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003576 // Version 146: In step 142 we had a bug where incorrectly
3577 // some settings were considered system set and as a result
3578 // made the default and marked as the default being set by
3579 // the system. Here reevaluate the default and default system
3580 // set flags. This would both fix corruption by the old impl
3581 // of step 142 and also properly handle devices which never
3582 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003583 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003584 SettingsState globalSettings = getGlobalSettingsLocked();
3585 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3586 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003587 }
3588
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003589 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3590 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3591 secureSettings.persistSyncLocked();
3592
3593 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3594 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3595 systemSettings.persistSyncLocked();
3596
Amin Shaikh86367962017-06-07 08:58:22 -07003597 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003598 }
3599
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003600 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003601 // Version 147: Removed. (This version previously allowed showing the
3602 // "wifi_wakeup_available" setting).
3603 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003604 currentVersion = 147;
3605 }
3606
3607 if (currentVersion == 147) {
3608 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003609 if (userId == UserHandle.USER_SYSTEM) {
3610 final SettingsState globalSettings = getGlobalSettingsLocked();
3611 final Setting currentSetting = globalSettings.getSettingLocked(
3612 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3613 if (currentSetting.isNull()) {
3614 globalSettings.insertSettingLocked(
3615 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3616 getContext().getResources().getBoolean(
3617 R.bool.def_restrict_background_data) ? "1" : "0",
3618 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3619 }
3620 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003621 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003622 }
3623
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003624 if (currentVersion == 148) {
3625 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3626 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3627 final String oldValue = systemSecureSettings.getSettingLocked(
3628 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3629 if (TextUtils.equals(null, oldValue)) {
3630 final String defaultValue = getContext().getResources().getString(
3631 R.string.def_backup_manager_constants);
3632 if (!TextUtils.isEmpty(defaultValue)) {
3633 systemSecureSettings.insertSettingLocked(
3634 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3635 true, SettingsState.SYSTEM_PACKAGE_NAME);
3636 }
3637 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003638 currentVersion = 149;
3639 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003640
3641 if (currentVersion == 149) {
3642 // Version 150: Set a default value for mobile data always on
3643 final SettingsState globalSettings = getGlobalSettingsLocked();
3644 final Setting currentSetting = globalSettings.getSettingLocked(
3645 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3646 if (currentSetting.isNull()) {
3647 globalSettings.insertSettingLocked(
3648 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3649 getContext().getResources().getBoolean(
3650 R.bool.def_mobile_data_always_on) ? "1" : "0",
3651 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3652 }
3653
3654 currentVersion = 150;
3655 }
3656
Mike Digman4af4a6f2018-01-16 14:49:38 -08003657 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003658 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003659 currentVersion = 151;
3660 }
3661
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003662 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003663 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3664 // by default but it is now no longer configurable).
3665 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003666 currentVersion = 152;
3667 }
3668
Joe LaPenna250d7842018-01-25 10:19:42 -08003669 if (currentVersion == 152) {
3670 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3671 currentVersion = 153;
3672 }
3673
Ben Linb4df8bc2018-01-29 11:48:20 -08003674 if (currentVersion == 153) {
3675 // Version 154: Read notification badge configuration from config.
3676 // If user has already set the value, don't do anything.
3677 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3678 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3679 Settings.Secure.NOTIFICATION_BADGING);
3680 if (showNotificationBadges.isNull()) {
3681 final boolean defaultValue = getContext().getResources().getBoolean(
3682 com.android.internal.R.bool.config_notificationBadging);
3683 systemSecureSettings.insertSettingLocked(
3684 Secure.NOTIFICATION_BADGING,
3685 defaultValue ? "1" : "0",
3686 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3687 }
3688 currentVersion = 154;
3689 }
3690
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003691 if (currentVersion == 154) {
3692 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3693 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3694 final String oldValue = systemSecureSettings.getSettingLocked(
3695 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3696 if (TextUtils.equals(null, oldValue)) {
3697 final String defaultValue = getContext().getResources().getString(
3698 R.string.def_backup_local_transport_parameters);
3699 if (!TextUtils.isEmpty(defaultValue)) {
3700 systemSecureSettings.insertSettingLocked(
3701 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3702 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3703 }
3704
3705 }
3706 currentVersion = 155;
3707 }
3708
Beverlyda904812018-03-02 09:55:30 -05003709 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003710 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003711 final SettingsState globalSettings = getGlobalSettingsLocked();
3712 final String oldValue = globalSettings.getSettingLocked(
3713 Global.CHARGING_STARTED_SOUND).getValue();
3714 final String oldDefault = getContext().getResources().getString(
3715 R.string.def_wireless_charging_started_sound);
3716 if (TextUtils.equals(null, oldValue)
3717 || TextUtils.equals(oldValue, oldDefault)) {
3718 final String defaultValue = getContext().getResources().getString(
3719 R.string.def_charging_started_sound);
3720 if (!TextUtils.isEmpty(defaultValue)) {
3721 globalSettings.insertSettingLocked(
3722 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3723 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3724 }
3725
3726 }
3727 currentVersion = 156;
3728 }
3729
Beverly09da25f2018-02-26 09:17:07 -05003730 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003731 // Version 157: Set a default value for zen duration,
3732 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003733 final SettingsState globalSettings = getGlobalSettingsLocked();
3734 final Setting currentSetting = globalSettings.getSettingLocked(
3735 Global.ZEN_DURATION);
3736 if (currentSetting.isNull()) {
3737 String defaultZenDuration = Integer.toString(getContext()
3738 .getResources().getInteger(R.integer.def_zen_duration));
3739 globalSettings.insertSettingLocked(
3740 Global.ZEN_DURATION, defaultZenDuration,
3741 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3742 }
Beverly09da25f2018-02-26 09:17:07 -05003743 currentVersion = 157;
3744 }
Annie Mengd069a882018-03-13 15:31:40 +00003745
3746 if (currentVersion == 157) {
3747 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3748 final SettingsState globalSettings = getGlobalSettingsLocked();
3749 final String oldValue = globalSettings.getSettingLocked(
3750 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3751 if (TextUtils.equals(null, oldValue)) {
3752 final String defaultValue = getContext().getResources().getString(
3753 R.string.def_backup_agent_timeout_parameters);
3754 if (!TextUtils.isEmpty(defaultValue)) {
3755 globalSettings.insertSettingLocked(
3756 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3757 null, true,
3758 SettingsState.SYSTEM_PACKAGE_NAME);
3759 }
3760 }
3761 currentVersion = 158;
3762 }
Roshan Pius9c396672018-03-02 14:54:13 -08003763
3764 if (currentVersion == 158) {
3765 // Remove setting that specifies wifi bgscan throttling params
3766 getGlobalSettingsLocked().deleteSettingLocked(
3767 "wifi_scan_background_throttle_interval_ms");
3768 getGlobalSettingsLocked().deleteSettingLocked(
3769 "wifi_scan_background_throttle_package_whitelist");
3770 currentVersion = 159;
3771 }
3772
Pavel Grafovc5c97302018-03-19 13:37:15 +00003773 if (currentVersion == 159) {
3774 // Version 160: Hiding notifications from the lockscreen is only available as
3775 // primary user option, profiles can only make them redacted. If a profile was
3776 // configured to not show lockscreen notifications, ensure that at the very
3777 // least these will be come hidden.
3778 if (mUserManager.isManagedProfile(userId)) {
3779 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3780 Setting showNotifications = secureSettings.getSettingLocked(
3781 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3782 // The default value is "1", check if user has turned it off.
3783 if ("0".equals(showNotifications.getValue())) {
3784 secureSettings.insertSettingLocked(
3785 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3786 null /* tag */, false /* makeDefault */,
3787 SettingsState.SYSTEM_PACKAGE_NAME);
3788 }
3789 // The setting is no longer valid for managed profiles, it should be
3790 // treated as if it was set to "1".
3791 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3792 }
3793 currentVersion = 160;
3794 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003795
3796 if (currentVersion == 160) {
3797 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003798 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003799 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3800 final SettingsState globalSettings = getGlobalSettingsLocked();
3801
3802 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003803 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3804 if (TextUtils.equals(null, oldValue)) {
3805 globalSettings.insertSettingLocked(
3806 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3807 Integer.toString(getContext().getResources().getInteger(
3808 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3809 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3810 }
3811
3812 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003813 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3814 if (TextUtils.equals(null, oldValue)) {
3815 globalSettings.insertSettingLocked(
3816 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3817 Integer.toString(getContext().getResources().getInteger(
3818 R.integer.def_sound_trigger_detection_service_op_timeout)),
3819 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3820 }
3821 currentVersion = 161;
3822 }
3823
Mike Digman55272862018-02-20 14:35:17 -08003824 if (currentVersion == 161) {
3825 // Version 161: Add a gesture for silencing phones
3826 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3827 final Setting currentSetting = secureSettings.getSettingLocked(
3828 Secure.VOLUME_HUSH_GESTURE);
3829 if (currentSetting.isNull()) {
3830 secureSettings.insertSettingLocked(
3831 Secure.VOLUME_HUSH_GESTURE,
3832 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3833 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3834 }
3835
3836 currentVersion = 162;
3837 }
3838
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003839 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003840 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003841 currentVersion = 163;
3842 }
3843
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003844 if (currentVersion == 163) {
3845 // Version 163: Update default value of
3846 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3847 final SettingsState settings = getGlobalSettingsLocked();
3848 final Setting currentSetting = settings.getSettingLocked(
3849 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3850 if (currentSetting.isDefaultFromSystem()) {
3851 settings.insertSettingLocked(
3852 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3853 Integer.toString(getContext().getResources().getInteger(
3854 R.integer
3855 .def_max_sound_trigger_detection_service_ops_per_day)),
3856 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3857 }
3858
3859 currentVersion = 164;
3860 }
3861
Julia Reynolds76bfa602018-04-23 09:38:47 -04003862 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003863 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003864 currentVersion = 165;
3865 }
3866
Beverly301e92a2018-04-27 09:43:05 -04003867 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003868 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3869 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003870 currentVersion = 166;
3871 }
3872
Beverly38fcfd02018-05-18 17:33:40 -04003873 if (currentVersion == 166) {
3874 // Version 166: add default values for hush gesture used and manual ringer
3875 // toggle
3876 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3877 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3878 Secure.HUSH_GESTURE_USED);
3879 if (currentHushUsedSetting.isNull()) {
3880 secureSettings.insertSettingLocked(
3881 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
3882 SettingsState.SYSTEM_PACKAGE_NAME);
3883 }
3884
3885 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
3886 Secure.MANUAL_RINGER_TOGGLE_COUNT);
3887 if (currentRingerToggleCountSetting.isNull()) {
3888 secureSettings.insertSettingLocked(
3889 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
3890 SettingsState.SYSTEM_PACKAGE_NAME);
3891 }
3892 currentVersion = 167;
3893 }
3894
Beverly155c9d22018-05-23 18:03:23 -04003895 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04003896 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
3897 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04003898 currentVersion = 168;
3899 }
3900
Michael Wright0e9eeee2018-05-26 00:31:20 +01003901 if (currentVersion == 168) {
3902 // Version 168: by default, vibrate for phone calls
3903 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3904 final Setting currentSetting = systemSettings.getSettingLocked(
3905 Settings.System.VIBRATE_WHEN_RINGING);
3906 if (currentSetting.isNull()) {
3907 systemSettings.insertSettingLocked(
3908 Settings.System.VIBRATE_WHEN_RINGING,
3909 getContext().getResources().getBoolean(
3910 R.bool.def_vibrate_when_ringing) ? "1" : "0",
3911 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3912 }
3913 currentVersion = 169;
3914 }
3915
Nadav Barf9f115d2018-06-24 10:06:50 +03003916 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04003917 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
3918 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
3919 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03003920
Beverly91d0a632018-07-02 16:45:00 -04003921 final SettingsState globalSettings = getGlobalSettingsLocked();
3922 final Setting globalZenDuration = globalSettings.getSettingLocked(
3923 Global.ZEN_DURATION);
3924
3925 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3926 final Setting secureZenDuration = secureSettings.getSettingLocked(
3927 Secure.ZEN_DURATION);
3928
3929 // ZEN_DURATION
3930 if (!globalZenDuration.isNull()) {
3931 secureSettings.insertSettingLocked(
3932 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
3933 SettingsState.SYSTEM_PACKAGE_NAME);
3934
3935 // set global zen duration setting to null since it's deprecated
3936 globalSettings.insertSettingLocked(
3937 Global.ZEN_DURATION, null, null, true,
3938 SettingsState.SYSTEM_PACKAGE_NAME);
3939 } else if (secureZenDuration.isNull()) {
3940 String defaultZenDuration = Integer.toString(getContext()
3941 .getResources().getInteger(R.integer.def_zen_duration));
3942 secureSettings.insertSettingLocked(
3943 Secure.ZEN_DURATION, defaultZenDuration, null, true,
3944 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03003945 }
Beverly91d0a632018-07-02 16:45:00 -04003946
3947 // SHOW_ZEN_SETTINGS_SUGGESTION
3948 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
3949 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
3950 if (currentShowZenSettingSuggestion.isNull()) {
3951 secureSettings.insertSettingLocked(
3952 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
3953 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3954 }
3955
3956 // ZEN_SETTINGS_UPDATED
3957 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
3958 Secure.ZEN_SETTINGS_UPDATED);
3959 if (currentUpdatedSetting.isNull()) {
3960 secureSettings.insertSettingLocked(
3961 Secure.ZEN_SETTINGS_UPDATED, "0",
3962 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3963 }
3964
3965 // ZEN_SETTINGS_SUGGESTION_VIEWED
3966 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
3967 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
3968 if (currentSettingSuggestionViewed.isNull()) {
3969 secureSettings.insertSettingLocked(
3970 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
3971 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3972 }
3973
Nadav Barf9f115d2018-06-24 10:06:50 +03003974 currentVersion = 170;
3975 }
3976
Beverly91d0a632018-07-02 16:45:00 -04003977 if (currentVersion == 170) {
3978 // Version 170: Set the default value for Secure Settings:
3979 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
3980
3981 final SettingsState globalSettings = getGlobalSettingsLocked();
3982 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3983
3984 // CHARGING_SOUNDS_ENABLED
3985 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
3986 Global.CHARGING_SOUNDS_ENABLED);
3987 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
3988 Secure.CHARGING_SOUNDS_ENABLED);
3989
3990 if (!globalChargingSoundEnabled.isNull()) {
3991 secureSettings.insertSettingLocked(
3992 Secure.CHARGING_SOUNDS_ENABLED,
3993 globalChargingSoundEnabled.getValue(), null, false,
3994 SettingsState.SYSTEM_PACKAGE_NAME);
3995
3996 // set global charging_sounds_enabled setting to null since it's deprecated
3997 globalSettings.insertSettingLocked(
3998 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
3999 SettingsState.SYSTEM_PACKAGE_NAME);
4000 } else if (secureChargingSoundsEnabled.isNull()) {
4001 String defChargingSoundsEnabled = getContext().getResources()
4002 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4003 secureSettings.insertSettingLocked(
4004 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4005 true, SettingsState.SYSTEM_PACKAGE_NAME);
4006 }
4007
4008 // CHARGING_VIBRATION_ENABLED
4009 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4010 Secure.CHARGING_VIBRATION_ENABLED);
4011
4012 if (secureChargingVibrationEnabled.isNull()) {
4013 String defChargingVibrationEnabled = getContext().getResources()
4014 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4015 secureSettings.insertSettingLocked(
4016 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4017 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4018 }
4019
4020 currentVersion = 171;
4021 }
4022
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004023 if (currentVersion == 171) {
4024 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4025 // be muted.
4026 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4027 final Setting currentSetting = systemSettings.getSettingLocked(
4028 Settings.System.MUTE_STREAMS_AFFECTED);
4029 if (!currentSetting.isNull()) {
4030 try {
4031 int currentSettingIntegerValue = Integer.parseInt(
4032 currentSetting.getValue());
4033 if ((currentSettingIntegerValue
4034 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4035 systemSettings.insertSettingLocked(
4036 Settings.System.MUTE_STREAMS_AFFECTED,
4037 Integer.toString(
4038 currentSettingIntegerValue
4039 | (1 << AudioManager.STREAM_VOICE_CALL)),
4040 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4041 }
4042 } catch (NumberFormatException e) {
4043 // remove the setting in case it is not a valid integer
4044 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4045 + "setting, removing setting", e);
4046 systemSettings.deleteSettingLocked(
4047 Settings.System.MUTE_STREAMS_AFFECTED);
4048 }
4049
4050 }
4051 currentVersion = 172;
4052 }
4053
Felipe Lemeff355092017-04-03 12:55:02 -07004054 // vXXX: Add new settings above this point.
4055
Dan Sandler71f85e92016-07-20 13:46:05 -04004056 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004057 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004058 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004059 + currentVersion +
4060 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4061 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004062 if (DEBUG) {
4063 throw new RuntimeException("db upgrade error");
4064 }
4065 }
4066
Jeff Brown503cffc2015-03-26 18:08:51 -07004067 // Return the current version.
4068 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004069 }
4070 }
Svet Ganov13701552017-02-23 12:45:17 -08004071
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004072 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4073 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004074 List<String> names = settings.getSettingNamesLocked();
4075 final int nameCount = names.size();
4076 for (int i = 0; i < nameCount; i++) {
4077 String name = names.get(i);
4078 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004079
4080 // In the upgrade case we pretend the call is made from the app
4081 // that made the last change to the setting to properly determine
4082 // whether the call has been made by a system component.
4083 int callingUid = -1;
4084 try {
4085 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4086 } catch (RemoteException e) {
4087 /* ignore - handled below */
4088 }
4089 if (callingUid < 0) {
4090 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4091 continue;
4092 }
4093 try {
4094 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4095 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004096 if (systemSet) {
4097 settings.insertSettingLocked(name, setting.getValue(),
4098 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004099 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4100 // We had a bug where changes by non-system packages were marked
4101 // as system made and as a result set as the default. Therefore, if
4102 // the package changed the setting last is not a system one but the
4103 // setting is marked as its default coming from the system we clear
4104 // the default and clear the system set flag.
4105 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004106 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004107 } catch (IllegalStateException e) {
4108 // If the package goes over its quota during the upgrade, don't
4109 // crash but just log the error as the system does the upgrade.
4110 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4111
Svet Ganov13701552017-02-23 12:45:17 -08004112 }
4113 }
4114 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004115 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004116}