blob: a317e3e3d33c68bee9cb89bdd64218d187ec1904 [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
Svetoslav683914b2015-01-15 14:22:26 -080019import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080020import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070021import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070022import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070023import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080024import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070025import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080026import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070027import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentValues;
29import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070030import android.content.Intent;
31import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070033import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080034import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070036import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070037import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040043import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080047import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070048import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080049import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070051import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070052import android.os.Looper;
53import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070055import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070056import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070057import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070058import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.os.UserHandle;
60import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070061import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.provider.Settings;
Yueming Wang348bf622018-02-24 03:30:17 +000063import android.provider.SettingsValidators;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010064import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080065import android.provider.Settings.Secure;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010067import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080068import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000069import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070070import android.util.Slog;
71import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070072import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080073import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040074
Svetoslav683914b2015-01-15 14:22:26 -080075import com.android.internal.annotations.GuardedBy;
76import com.android.internal.content.PackageMonitor;
77import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080078import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070079import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080080import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040081
Svetoslav683914b2015-01-15 14:22:26 -080082import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080083import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080084import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080085import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080086import java.nio.ByteBuffer;
87import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000088import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070090import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000092import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000093import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080094import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080095import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010096import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080097import java.util.Set;
98import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import javax.crypto.Mac;
100import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700101
Yueming Wang348bf622018-02-24 03:30:17 +0000102import static android.os.Process.ROOT_UID;
103import static android.os.Process.SHELL_UID;
104import static android.os.Process.SYSTEM_UID;
105
Svetoslav Ganove080da92016-12-21 17:10:35 -0800106
Svetoslav683914b2015-01-15 14:22:26 -0800107/**
108 * <p>
109 * This class is a content provider that publishes the system settings.
110 * It can be accessed via the content provider APIs or via custom call
111 * commands. The latter is a bit faster and is the preferred way to access
112 * the platform settings.
113 * </p>
114 * <p>
115 * There are three settings types, global (with signature level protection
116 * and shared across users), secure (with signature permission level
117 * protection and per user), and system (with dangerous permission level
118 * protection and per user). Global settings are stored under the device owner.
119 * Each of these settings is represented by a {@link
120 * com.android.providers.settings.SettingsState} object mapped to an integer
121 * key derived from the setting type in the most significant bits and user
122 * id in the least significant bits. Settings are synchronously loaded on
123 * instantiation of a SettingsState and asynchronously persisted on mutation.
124 * Settings are stored in the user specific system directory.
125 * </p>
126 * <p>
127 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
128 * and get a warning. Targeting higher API version prohibits this as the
129 * system settings are not a place for apps to save their state. When a package
130 * is removed the settings it added are deleted. Apps cannot delete system
131 * settings added by the platform. System settings values are validated to
132 * ensure the clients do not put bad values. Global and secure settings are
133 * changed only by trusted parties, therefore no validation is performed. Also
134 * there is a limit on the amount of app specific settings that can be added
135 * to prevent unlimited growth of the system process memory footprint.
136 * </p>
137 */
138@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700140 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700142 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800143
144 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700145
Christopher Tate06efb532012-08-24 15:29:27 -0700146 private static final String TABLE_SYSTEM = "system";
147 private static final String TABLE_SECURE = "secure";
148 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800149
150 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 private static final String TABLE_FAVORITES = "favorites";
152 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800153 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
154 private static final String TABLE_BOOKMARKS = "bookmarks";
155 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Svetoslav683914b2015-01-15 14:22:26 -0800157 // The set of removed legacy tables.
158 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700159 static {
Svetoslav683914b2015-01-15 14:22:26 -0800160 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
161 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
162 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
163 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
164 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
165 }
Christopher Tate06efb532012-08-24 15:29:27 -0700166
Svetoslav683914b2015-01-15 14:22:26 -0800167 private static final int MUTATION_OPERATION_INSERT = 1;
168 private static final int MUTATION_OPERATION_DELETE = 2;
169 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800170 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400171
Svetoslav683914b2015-01-15 14:22:26 -0800172 private static final String[] ALL_COLUMNS = new String[] {
173 Settings.NameValueTable._ID,
174 Settings.NameValueTable.NAME,
175 Settings.NameValueTable.VALUE
176 };
177
Makoto Onuki53f0e022017-11-29 13:51:01 -0800178 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
179 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
180 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
181 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Svet Ganov53a441c2016-04-19 19:38:00 -0700182
183 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
184 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700185
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700186 // Overlay specified settings whitelisted for Instant Apps
187 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
188 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
189 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
190
191 static {
192 for (String name : Resources.getSystem().getStringArray(
193 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
194 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
195 }
196 for (String name : Resources.getSystem().getStringArray(
197 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
198 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
199 }
200 for (String name : Resources.getSystem().getStringArray(
201 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
202 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
203 }
204 }
205
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800206 // Changes to these global settings are synchronously persisted
207 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
208 static {
209 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
210 }
211
212 // Changes to these secure settings are synchronously persisted
213 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
214 static {
215 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
216 }
217
Svetoslav683914b2015-01-15 14:22:26 -0800218 // Per user secure settings that moved to the for all users global settings.
219 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
220 static {
221 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700222 }
223
Svetoslav683914b2015-01-15 14:22:26 -0800224 // Per user system settings that moved to the for all users global settings.
225 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
226 static {
227 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700228 }
229
Svetoslav683914b2015-01-15 14:22:26 -0800230 // Per user system settings that moved to the per user secure settings.
231 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
232 static {
233 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700234 }
235
Svetoslav683914b2015-01-15 14:22:26 -0800236 // Per all users global settings that moved to the per user secure settings.
237 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
238 static {
239 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700240 }
241
Svetoslav683914b2015-01-15 14:22:26 -0800242 // Per user secure settings that are cloned for the managed profiles of the user.
243 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
244 static {
245 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 }
247
Svetoslav683914b2015-01-15 14:22:26 -0800248 // Per user system settings that are cloned for the managed profiles of the user.
249 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
250 static {
251 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400252 }
253
Andre Lago3fa139c2016-08-04 13:53:44 +0100254 // Per user system settings that are cloned from the profile's parent when a dependency
255 // in {@link Settings.Secure} is set to "1".
256 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
257 static {
258 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
259 }
260
Svetoslav683914b2015-01-15 14:22:26 -0800261 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700262
Svetoslav683914b2015-01-15 14:22:26 -0800263 @GuardedBy("mLock")
264 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700265
Svet Ganova8f90262016-05-10 08:44:48 -0700266 @GuardedBy("mLock")
267 private HandlerThread mHandlerThread;
268
Makoto Onuki73360ab2017-03-17 11:50:13 -0700269 @GuardedBy("mLock")
270 private Handler mHandler;
271
Svetoslav7ec28e82015-05-20 17:01:10 -0700272 // We have to call in the user manager with no lock held,
273 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800274
Svetoslav7ec28e82015-05-20 17:01:10 -0700275 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700276 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700277
Svet Ganov53a441c2016-04-19 19:38:00 -0700278 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800279 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700280 }
281
282 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800283 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700284 }
285
286 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800287 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700288 }
289
290 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800291 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700292 }
293
294 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800295 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700296 }
297
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700298 @Override
299 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800300 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000301
302 // fail to boot if there're any backed up settings that don't have a non-null validator
303 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000304 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000305 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000306
Svetoslav683914b2015-01-15 14:22:26 -0800307 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700308 mUserManager = UserManager.get(getContext());
309 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700310 mHandlerThread = new HandlerThread(LOG_TAG,
311 Process.THREAD_PRIORITY_BACKGROUND);
312 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700313 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800314 mSettingsRegistry = new SettingsRegistry();
315 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700316 mHandler.post(() -> {
317 registerBroadcastReceivers();
318 startWatchingUserRestrictionChanges();
319 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700320 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 return true;
322 }
323
Michal Karpinski2c37b082018-01-18 16:14:27 +0000324 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000325 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
326 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000327
328 failToBootIfOffendersPresent(offenders, "Settings.System");
329 }
330
331 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000332 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
333 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000334
335 failToBootIfOffendersPresent(offenders, "Settings.Global");
336 }
337
Michal Karpinski964943a2018-01-19 16:28:26 +0000338 private void ensureAllBackedUpSecureSettingsHaveValidators() {
339 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
340 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
341
342 failToBootIfOffendersPresent(offenders, "Settings.Secure");
343 }
344
Michal Karpinski5db1e432018-01-18 20:10:24 +0000345 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
346 if (offenders.length() > 0) {
347 throw new RuntimeException("All " + settingsType + " settings that are backed up"
348 + " have to have a non-null validator, but those don't: " + offenders);
349 }
350 }
351
352 private String getOffenders(String[] settingsToBackup, Map<String,
353 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000354 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000355 for (String setting : settingsToBackup) {
356 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000357 offenders.append(setting).append(" ");
358 }
359 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000360 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000361 }
362
Michal Karpinski964943a2018-01-19 16:28:26 +0000363 private final String[] concat(String[] first, String[] second) {
364 if (second == null || second.length == 0) {
365 return first;
366 }
367 final int firstLen = first.length;
368 final int secondLen = second.length;
369 String[] both = new String[firstLen + secondLen];
370 System.arraycopy(first, 0, both, 0, firstLen);
371 System.arraycopy(second, 0, both, firstLen, secondLen);
372 return both;
373 }
374
Svetoslav683914b2015-01-15 14:22:26 -0800375 @Override
376 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700377 final int requestingUserId = getRequestingUserId(args);
378 switch (method) {
379 case Settings.CALL_METHOD_GET_GLOBAL: {
380 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700381 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800382 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700383
384 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800385 Setting setting = getSecureSetting(name, requestingUserId,
386 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700387 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700388 }
389
390 case Settings.CALL_METHOD_GET_SYSTEM: {
391 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700392 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700393 }
394
395 case Settings.CALL_METHOD_PUT_GLOBAL: {
396 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800397 String tag = getSettingTag(args);
398 final boolean makeDefault = getSettingMakeDefault(args);
399 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700400 break;
401 }
402
403 case Settings.CALL_METHOD_PUT_SECURE: {
404 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800405 String tag = getSettingTag(args);
406 final boolean makeDefault = getSettingMakeDefault(args);
407 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700408 break;
409 }
410
411 case Settings.CALL_METHOD_PUT_SYSTEM: {
412 String value = getSettingValue(args);
413 insertSystemSetting(name, value, requestingUserId);
414 break;
415 }
416
Svetoslav Ganove080da92016-12-21 17:10:35 -0800417 case Settings.CALL_METHOD_RESET_GLOBAL: {
418 final int mode = getResetModeEnforcingPermission(args);
419 String tag = getSettingTag(args);
420 resetGlobalSetting(requestingUserId, mode, tag);
421 break;
422 }
423
424 case Settings.CALL_METHOD_RESET_SECURE: {
425 final int mode = getResetModeEnforcingPermission(args);
426 String tag = getSettingTag(args);
427 resetSecureSetting(requestingUserId, mode, tag);
428 break;
429 }
430
Svetoslav7ec28e82015-05-20 17:01:10 -0700431 default: {
432 Slog.w(LOG_TAG, "call() with invalid method: " + method);
433 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700434 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700435
Christopher Tate06efb532012-08-24 15:29:27 -0700436 return null;
437 }
438
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800439 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800440 public String getType(Uri uri) {
441 Arguments args = new Arguments(uri, null, null, true);
442 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700443 return "vnd.android.cursor.dir/" + args.table;
444 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700445 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700446 }
447 }
448
449 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800450 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
451 String order) {
452 if (DEBUG) {
453 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454 }
455
Svetoslav683914b2015-01-15 14:22:26 -0800456 Arguments args = new Arguments(uri, where, whereArgs, true);
457 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700458
Svetoslav683914b2015-01-15 14:22:26 -0800459 // If a legacy table that is gone, done.
460 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
461 return new MatrixCursor(normalizedProjection, 0);
462 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700463
Svetoslav7ec28e82015-05-20 17:01:10 -0700464 switch (args.table) {
465 case TABLE_GLOBAL: {
466 if (args.name != null) {
467 Setting setting = getGlobalSetting(args.name);
468 return packageSettingForQuery(setting, normalizedProjection);
469 } else {
470 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700471 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700472 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700473
Svetoslav7ec28e82015-05-20 17:01:10 -0700474 case TABLE_SECURE: {
475 final int userId = UserHandle.getCallingUserId();
476 if (args.name != null) {
477 Setting setting = getSecureSetting(args.name, userId);
478 return packageSettingForQuery(setting, normalizedProjection);
479 } else {
480 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800481 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700482 }
Svetoslav683914b2015-01-15 14:22:26 -0800483
Svetoslav7ec28e82015-05-20 17:01:10 -0700484 case TABLE_SYSTEM: {
485 final int userId = UserHandle.getCallingUserId();
486 if (args.name != null) {
487 Setting setting = getSystemSetting(args.name, userId);
488 return packageSettingForQuery(setting, normalizedProjection);
489 } else {
490 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800491 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700492 }
Svetoslav683914b2015-01-15 14:22:26 -0800493
Svetoslav7ec28e82015-05-20 17:01:10 -0700494 default: {
495 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700496 }
497 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700498 }
499
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800501 public Uri insert(Uri uri, ContentValues values) {
502 if (DEBUG) {
503 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700504 }
505
Svetoslav683914b2015-01-15 14:22:26 -0800506 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700507
Svetoslav683914b2015-01-15 14:22:26 -0800508 // If a legacy table that is gone, done.
509 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 return null;
511 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512
Svetoslav683914b2015-01-15 14:22:26 -0800513 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700514 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800515 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700516 }
517
Svetoslav683914b2015-01-15 14:22:26 -0800518 String value = values.getAsString(Settings.Secure.VALUE);
519
Svetoslav7ec28e82015-05-20 17:01:10 -0700520 switch (table) {
521 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800522 if (insertGlobalSetting(name, value, null, false,
523 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700524 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700525 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700526 } break;
527
528 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800529 if (insertSecureSetting(name, value, null, false,
530 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700531 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
532 }
533 } break;
534
535 case TABLE_SYSTEM: {
536 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
537 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
538 }
539 } break;
540
541 default: {
542 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700543 }
544 }
545
Svetoslav683914b2015-01-15 14:22:26 -0800546 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700547 }
548
549 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800550 public int bulkInsert(Uri uri, ContentValues[] allValues) {
551 if (DEBUG) {
552 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700554
Svetoslav683914b2015-01-15 14:22:26 -0800555 int insertionCount = 0;
556 final int valuesCount = allValues.length;
557 for (int i = 0; i < valuesCount; i++) {
558 ContentValues values = allValues[i];
559 if (insert(uri, values) != null) {
560 insertionCount++;
561 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700562 }
Svetoslav683914b2015-01-15 14:22:26 -0800563
564 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700565 }
566
567 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800568 public int delete(Uri uri, String where, String[] whereArgs) {
569 if (DEBUG) {
570 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700572
Svetoslav683914b2015-01-15 14:22:26 -0800573 Arguments args = new Arguments(uri, where, whereArgs, false);
574
575 // If a legacy table that is gone, done.
576 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
577 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700578 }
Svetoslav683914b2015-01-15 14:22:26 -0800579
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700580 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800581 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700582 }
Svetoslav683914b2015-01-15 14:22:26 -0800583
Svetoslav7ec28e82015-05-20 17:01:10 -0700584 switch (args.table) {
585 case TABLE_GLOBAL: {
586 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700587 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700588 }
Svetoslav683914b2015-01-15 14:22:26 -0800589
Svetoslav7ec28e82015-05-20 17:01:10 -0700590 case TABLE_SECURE: {
591 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700592 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700593 }
Svetoslav683914b2015-01-15 14:22:26 -0800594
Svetoslav7ec28e82015-05-20 17:01:10 -0700595 case TABLE_SYSTEM: {
596 final int userId = UserHandle.getCallingUserId();
597 return deleteSystemSetting(args.name, userId) ? 1 : 0;
598 }
599
600 default: {
601 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800602 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700603 }
Svetoslav683914b2015-01-15 14:22:26 -0800604 }
605
606 @Override
607 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
608 if (DEBUG) {
609 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700610 }
Svetoslav683914b2015-01-15 14:22:26 -0800611
612 Arguments args = new Arguments(uri, where, whereArgs, false);
613
614 // If a legacy table that is gone, done.
615 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
616 return 0;
617 }
618
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700619 String name = values.getAsString(Settings.Secure.NAME);
620 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800621 return 0;
622 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700623 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800624
Svetoslav7ec28e82015-05-20 17:01:10 -0700625 switch (args.table) {
626 case TABLE_GLOBAL: {
627 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800628 return updateGlobalSetting(args.name, value, null, false,
629 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700630 }
Svetoslav683914b2015-01-15 14:22:26 -0800631
Svetoslav7ec28e82015-05-20 17:01:10 -0700632 case TABLE_SECURE: {
633 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800634 return updateSecureSetting(args.name, value, null, false,
635 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700636 }
Svetoslav683914b2015-01-15 14:22:26 -0800637
Svetoslav7ec28e82015-05-20 17:01:10 -0700638 case TABLE_SYSTEM: {
639 final int userId = UserHandle.getCallingUserId();
640 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
641 }
Svetoslav683914b2015-01-15 14:22:26 -0800642
Svetoslav7ec28e82015-05-20 17:01:10 -0700643 default: {
644 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800645 }
646 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700647 }
648
649 @Override
650 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100651 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
652 if (userId != UserHandle.getCallingUserId()) {
653 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
654 "Access files from the settings of another user");
655 }
656 uri = ContentProvider.getUriWithoutUserId(uri);
657
Andre Lago3fa139c2016-08-04 13:53:44 +0100658 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700659 final String cacheName;
660 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100661 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700662 cacheName = Settings.System.RINGTONE_CACHE;
663 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100664 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700665 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
666 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100667 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700668 cacheName = Settings.System.ALARM_ALERT_CACHE;
669 } else {
670 throw new FileNotFoundException("Direct file access no longer supported; "
671 + "ringtone playback is available through android.media.Ringtone");
672 }
673
Andre Lago3fa139c2016-08-04 13:53:44 +0100674 int actualCacheOwner;
675 // Redirect cache to parent if ringtone setting is owned by profile parent
676 synchronized (mLock) {
677 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
678 cacheRingtoneSetting);
679 }
680 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700681 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
682 }
683
684 private File getRingtoneCacheDir(int userId) {
685 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
686 cacheDir.mkdir();
687 SELinux.restorecon(cacheDir);
688 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700689 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800690
Eugene Suslad72c3972016-12-27 15:49:30 -0800691 /**
692 * Dump all settings as a proto buf.
693 *
694 * @param fd The file to dump to
695 */
696 void dumpProto(@NonNull FileDescriptor fd) {
697 ProtoOutputStream proto = new ProtoOutputStream(fd);
698
699 synchronized (mLock) {
700 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800701 }
702
703 proto.flush();
704 }
705
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700706 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800707 synchronized (mLock) {
708 final long identity = Binder.clearCallingIdentity();
709 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700710 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800711 final int userCount = users.size();
712 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700713 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800714 }
715 } finally {
716 Binder.restoreCallingIdentity(identity);
717 }
718 }
719 }
720
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700721 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700722 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800723 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700724 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
725 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700726 if (globalSettings != null) {
727 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800728 pw.println();
729 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700730 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800731 }
732
733 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700734 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
735 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700736 if (secureSettings != null) {
737 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800738 pw.println();
739 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700740 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700741
Svetoslavb505ccc2015-02-17 12:41:04 -0800742 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700743 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
744 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700745 if (systemSettings != null) {
746 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800747 pw.println();
748 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700749 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800750 }
751
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700752 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
753 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800754
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700755 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800756
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700757 for (int i = 0; i < nameCount; i++) {
758 String name = names.get(i);
759 Setting setting = settingsState.getSettingLocked(name);
760 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
761 pw.print(" name:"); pw.print(toDumpString(name));
762 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800763 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700764 }
765 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800766 if (setting.getDefaultValue() != null) {
767 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800768 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800769 }
770 if (setting.getTag() != null) {
771 pw.print(" tag:"); pw.print(setting.getTag());
772 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800773 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700774 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800775 }
776
Svetoslav7e0683b2015-08-03 16:02:52 -0700777 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700778 if (s != null) {
779 return s;
780 }
781 return "{null}";
782 }
783
Svetoslav683914b2015-01-15 14:22:26 -0800784 private void registerBroadcastReceivers() {
785 IntentFilter userFilter = new IntentFilter();
786 userFilter.addAction(Intent.ACTION_USER_REMOVED);
787 userFilter.addAction(Intent.ACTION_USER_STOPPED);
788
789 getContext().registerReceiver(new BroadcastReceiver() {
790 @Override
791 public void onReceive(Context context, Intent intent) {
792 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700793 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800794
795 switch (intent.getAction()) {
796 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700797 synchronized (mLock) {
798 mSettingsRegistry.removeUserStateLocked(userId, true);
799 }
Svetoslav683914b2015-01-15 14:22:26 -0800800 } break;
801
802 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 synchronized (mLock) {
804 mSettingsRegistry.removeUserStateLocked(userId, false);
805 }
Svetoslav683914b2015-01-15 14:22:26 -0800806 } break;
807 }
808 }
809 }, userFilter);
810
811 PackageMonitor monitor = new PackageMonitor() {
812 @Override
813 public void onPackageRemoved(String packageName, int uid) {
814 synchronized (mLock) {
815 mSettingsRegistry.onPackageRemovedLocked(packageName,
816 UserHandle.getUserId(uid));
817 }
818 }
Mark Rathjend891f012017-01-19 04:10:37 +0000819
820 @Override
821 public void onUidRemoved(int uid) {
822 synchronized (mLock) {
823 mSettingsRegistry.onUidRemovedLocked(uid);
824 }
825 }
Svetoslav683914b2015-01-15 14:22:26 -0800826 };
827
828 // package changes
829 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
830 UserHandle.ALL, true);
831 }
832
Svet Ganov53a441c2016-04-19 19:38:00 -0700833 private void startWatchingUserRestrictionChanges() {
834 // TODO: The current design of settings looking different based on user restrictions
835 // should be reworked to keep them separate and system code should check the setting
836 // first followed by checking the user restriction before performing an operation.
837 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
838 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
839 Bundle prevRestrictions) -> {
840 // We are changing the settings affected by restrictions to their current
841 // value with a forced update to ensure that all cross profile dependencies
842 // are taken into account. Also make sure the settings update to.. the same
843 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800844 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
845 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700846 final long identity = Binder.clearCallingIdentity();
847 try {
848 synchronized (mLock) {
849 Setting setting = getSecureSetting(
850 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
851 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800852 setting != null ? setting.getValue() : null, null,
853 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700854 }
855 } finally {
856 Binder.restoreCallingIdentity(identity);
857 }
858 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800859 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
860 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700861 final long identity = Binder.clearCallingIdentity();
862 try {
863 synchronized (mLock) {
864 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800865 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700866 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800867 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700868 }
869 } finally {
870 Binder.restoreCallingIdentity(identity);
871 }
872 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800873 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
874 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700875 final long identity = Binder.clearCallingIdentity();
876 try {
877 synchronized (mLock) {
878 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800879 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700880 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800881 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700882 }
883 } finally {
884 Binder.restoreCallingIdentity(identity);
885 }
886 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800887 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
888 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700889 final long identity = Binder.clearCallingIdentity();
890 try {
891 synchronized (mLock) {
892 Setting enable = getGlobalSetting(
893 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800894 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700895 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800896 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700897 Setting include = getGlobalSetting(
898 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800899 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700900 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800901 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700902 }
903 } finally {
904 Binder.restoreCallingIdentity(identity);
905 }
906 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800907 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
908 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700909 final long identity = Binder.clearCallingIdentity();
910 try {
911 synchronized (mLock) {
912 Setting setting = getGlobalSetting(
913 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800914 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700915 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800916 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700917 }
918 } finally {
919 Binder.restoreCallingIdentity(identity);
920 }
921 }
922 });
923 }
924
Svetoslav7ec28e82015-05-20 17:01:10 -0700925 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800926 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700927 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800928 }
929
Svetoslav7ec28e82015-05-20 17:01:10 -0700930 synchronized (mLock) {
931 // Get the settings.
932 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700933 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800934
Chad Brubaker97bccee2017-01-05 15:51:41 -0800935 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
936 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800937
Svetoslav7ec28e82015-05-20 17:01:10 -0700938 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800939
Svetoslav7ec28e82015-05-20 17:01:10 -0700940 String[] normalizedProjection = normalizeProjection(projection);
941 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800942
Svetoslav7ec28e82015-05-20 17:01:10 -0700943 // Anyone can get the global settings, so no security checks.
944 for (int i = 0; i < nameCount; i++) {
945 String name = names.get(i);
946 Setting setting = settingsState.getSettingLocked(name);
947 appendSettingToCursor(result, setting);
948 }
949
950 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800951 }
Svetoslav683914b2015-01-15 14:22:26 -0800952 }
953
Svetoslav7ec28e82015-05-20 17:01:10 -0700954 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800955 if (DEBUG) {
956 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
957 }
958
Chad Brubakera6830e72017-04-28 17:34:36 -0700959 // Ensure the caller can access the setting.
960 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
961
Svetoslav683914b2015-01-15 14:22:26 -0800962 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700963 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700964 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700965 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800966 }
Svetoslav683914b2015-01-15 14:22:26 -0800967 }
968
Svetoslav Ganove080da92016-12-21 17:10:35 -0800969 private boolean updateGlobalSetting(String name, String value, String tag,
970 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800971 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800972 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
973 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
974 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800975 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800976 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
977 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800978 }
979
Svetoslav Ganove080da92016-12-21 17:10:35 -0800980 private boolean insertGlobalSetting(String name, String value, String tag,
981 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700982 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800983 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
984 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
985 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700986 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800987 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
988 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 }
990
Svet Ganov53a441c2016-04-19 19:38:00 -0700991 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800992 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800993 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
994 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800995 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800996 return mutateGlobalSetting(name, null, null, false, requestingUserId,
997 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800998 }
999
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1001 if (DEBUG) {
1002 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1003 + mode + ", " + tag + ")");
1004 }
1005 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1006 MUTATION_OPERATION_RESET, false, mode);
1007 }
1008
1009 private boolean mutateGlobalSetting(String name, String value, String tag,
1010 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1011 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001012 // Make sure the caller can change the settings - treated as secure.
1013 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1014
Svetoslav683914b2015-01-15 14:22:26 -08001015 // Resolve the userId on whose behalf the call is made.
1016 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1017
Makoto Onuki28da2e32015-11-20 11:30:44 -08001018 // If this is a setting that is currently restricted for this user, do not allow
1019 // unrestricting changes.
Yueming Wang348bf622018-02-24 03:30:17 +00001020 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
1021 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001022 return false;
1023 }
1024
1025 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 synchronized (mLock) {
1027 switch (operation) {
1028 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001029 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1030 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001031 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001032 }
Svetoslav683914b2015-01-15 14:22:26 -08001033
Svetoslav7ec28e82015-05-20 17:01:10 -07001034 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001035 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001036 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001037 }
Svetoslav683914b2015-01-15 14:22:26 -08001038
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001040 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1041 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001042 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001043 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001044
1045 case MUTATION_OPERATION_RESET: {
1046 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1047 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1048 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001049 }
1050 }
1051
1052 return false;
1053 }
1054
Christopher Tateb218e762017-04-05 16:34:07 -07001055 private PackageInfo getCallingPackageInfo(int userId) {
1056 try {
1057 return mPackageManager.getPackageInfo(getCallingPackage(),
1058 PackageManager.GET_SIGNATURES, userId);
1059 } catch (RemoteException e) {
1060 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1061 }
1062 }
1063
Svetoslav7ec28e82015-05-20 17:01:10 -07001064 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001065 if (DEBUG) {
1066 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1067 }
1068
1069 // Resolve the userId on whose behalf the call is made.
1070 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1071
Christopher Tateb218e762017-04-05 16:34:07 -07001072 // The relevant "calling package" userId will be the owning userId for some
1073 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1074 // up front who the effective "new SSAID" user ID for that settings name will be.
1075 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1076 Settings.Secure.ANDROID_ID);
1077 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1078
Svetoslav7ec28e82015-05-20 17:01:10 -07001079 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001080 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001081
Svetoslav7ec28e82015-05-20 17:01:10 -07001082 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001083
Svetoslav7ec28e82015-05-20 17:01:10 -07001084 String[] normalizedProjection = normalizeProjection(projection);
1085 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001086
Svetoslav7ec28e82015-05-20 17:01:10 -07001087 for (int i = 0; i < nameCount; i++) {
1088 String name = names.get(i);
1089 // Determine the owning user as some profile settings are cloned from the parent.
1090 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1091 name);
Svetoslav683914b2015-01-15 14:22:26 -08001092
Alex Klyubin1991f572017-03-03 14:08:36 -08001093 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1094 // This caller is not permitted to access this setting. Pretend the setting
1095 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001096 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001097 }
Svetoslav683914b2015-01-15 14:22:26 -08001098
Mark Rathjen7599f132017-01-23 14:15:54 -08001099 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001100 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1101 final Setting setting;
1102 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001103 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001104 } else {
1105 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1106 name);
1107 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001108 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001109 }
1110
Svetoslav7ec28e82015-05-20 17:01:10 -07001111 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001112 }
Svetoslav683914b2015-01-15 14:22:26 -08001113 }
1114
Svetoslav7ec28e82015-05-20 17:01:10 -07001115 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001116 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1117 }
1118
1119 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001120 if (DEBUG) {
1121 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1122 }
1123
1124 // Resolve the userId on whose behalf the call is made.
1125 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1126
Chad Brubakera6830e72017-04-28 17:34:36 -07001127 // Ensure the caller can access the setting.
1128 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1129
Svetoslav683914b2015-01-15 14:22:26 -08001130 // Determine the owning user as some profile settings are cloned from the parent.
1131 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1132
Alex Klyubin1991f572017-03-03 14:08:36 -08001133 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1134 // This caller is not permitted to access this setting. Pretend the setting doesn't
1135 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001136 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1137 owningUserId);
1138 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001139 }
1140
Christopher Tateb218e762017-04-05 16:34:07 -07001141 // As of Android O, the SSAID is read from an app-specific entry in table
1142 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1143 if (isNewSsaidSetting(name)) {
1144 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1145 synchronized (mLock) {
1146 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001147 }
Christopher Tateb218e762017-04-05 16:34:07 -07001148 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001149 if (enableOverride) {
1150 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1151 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1152 if (overridden != null) {
1153 return overridden;
1154 }
1155 }
1156 }
Mark Rathjend891f012017-01-19 04:10:37 +00001157
Christopher Tateb218e762017-04-05 16:34:07 -07001158 // Not the SSAID; do a straight lookup
1159 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001160 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001161 owningUserId, name);
1162 }
Svetoslav683914b2015-01-15 14:22:26 -08001163 }
1164
Mark Rathjend891f012017-01-19 04:10:37 +00001165 private boolean isNewSsaidSetting(String name) {
1166 return Settings.Secure.ANDROID_ID.equals(name)
1167 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1168 }
1169
Christopher Tateb218e762017-04-05 16:34:07 -07001170 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001171 // Get uid of caller (key) used to store ssaid value
1172 String name = Integer.toString(
1173 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1174
1175 if (DEBUG) {
1176 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1177 }
1178
1179 // Retrieve the ssaid from the table if present.
1180 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1181 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001182 // If the app is an Instant App use its stored SSAID instead of our own.
1183 final String instantSsaid;
1184 final long token = Binder.clearCallingIdentity();
1185 try {
1186 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1187 owningUserId);
1188 } catch (RemoteException e) {
1189 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1190 return null;
1191 } finally {
1192 Binder.restoreCallingIdentity(token);
1193 }
Svet Ganov96c99462017-05-05 14:27:13 -07001194
1195 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1196 SETTINGS_TYPE_SSAID, owningUserId);
1197
Chad Brubaker0d277a72017-04-12 16:56:53 -07001198 if (instantSsaid != null) {
1199 // Use the stored value if it is still valid.
1200 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001201 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001202 }
1203 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001204 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1205 true, callingPkg.packageName);
1206 if (!success) {
1207 throw new IllegalStateException("Failed to update instant app android id");
1208 }
Svet Ganov96c99462017-05-05 14:27:13 -07001209 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1210 owningUserId, name);
1211 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001212 }
Mark Rathjend891f012017-01-19 04:10:37 +00001213
1214 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001215 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001216 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1217 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001218 }
1219
Svet Ganov96c99462017-05-05 14:27:13 -07001220 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1221 }
1222
1223 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1224 // SSAID settings are located in a dedicated table for internal bookkeeping
1225 // but for the world they reside in the secure table, so adjust the key here.
1226 // We have a special name when looking it up but want the world to see it as
1227 // "android_id".
1228 if (ssaidSetting != null) {
1229 return settingsState.new Setting(ssaidSetting) {
1230 @Override
1231 public int getKey() {
1232 final int userId = getUserIdFromKey(super.getKey());
1233 return makeKey(SETTINGS_TYPE_SECURE, userId);
1234 }
1235
1236 @Override
1237 public String getName() {
1238 return Settings.Secure.ANDROID_ID;
1239 }
1240 };
1241 }
1242 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001243 }
1244
Makoto Onuki0000d322017-11-28 16:31:47 -08001245 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1246 synchronized (mLock) {
1247 final Setting setting = getGlobalSetting(
1248 Global.LOCATION_GLOBAL_KILL_SWITCH);
1249 if (!"1".equals(setting.getValue())) {
1250 return null;
1251 }
1252 // Global kill-switch is enabled. Return an empty value.
1253 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1254 SETTINGS_TYPE_SECURE, owningUserId);
1255 return settingsState.new Setting(
1256 Secure.LOCATION_PROVIDERS_ALLOWED,
1257 "", // value
1258 "", // tag
1259 "", // default value
1260 "", // package name
1261 false, // from system
1262 "0" // id
1263 ) {
1264 @Override
1265 public boolean update(String value, boolean setDefault, String packageName,
1266 String tag, boolean forceNonSystemPackage) {
1267 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1268 return false;
1269 }
1270 };
1271 }
1272 }
1273
Svetoslav Ganove080da92016-12-21 17:10:35 -08001274 private boolean insertSecureSetting(String name, String value, String tag,
1275 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001276 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001277 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001278 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1279 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001280 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001281 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1282 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001283 }
1284
Svet Ganov53a441c2016-04-19 19:38:00 -07001285 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001286 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001287 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1288 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001289 }
1290
Svetoslav Ganove080da92016-12-21 17:10:35 -08001291 return mutateSecureSetting(name, null, null, false, requestingUserId,
1292 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001293 }
1294
Svetoslav Ganove080da92016-12-21 17:10:35 -08001295 private boolean updateSecureSetting(String name, String value, String tag,
1296 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001297 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001298 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001299 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1300 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001301 }
1302
Svetoslav Ganove080da92016-12-21 17:10:35 -08001303 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1304 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001305 }
1306
Svetoslav Ganove080da92016-12-21 17:10:35 -08001307 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1308 if (DEBUG) {
1309 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1310 + mode + ", " + tag + ")");
1311 }
1312
1313 mutateSecureSetting(null, null, tag, false, requestingUserId,
1314 MUTATION_OPERATION_RESET, false, mode);
1315 }
1316
1317 private boolean mutateSecureSetting(String name, String value, String tag,
1318 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1319 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001320 // Make sure the caller can change the settings.
1321 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1322
Svetoslav683914b2015-01-15 14:22:26 -08001323 // Resolve the userId on whose behalf the call is made.
1324 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1325
Makoto Onuki28da2e32015-11-20 11:30:44 -08001326 // If this is a setting that is currently restricted for this user, do not allow
1327 // unrestricting changes.
Yueming Wang348bf622018-02-24 03:30:17 +00001328 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
1329 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001330 return false;
1331 }
1332
1333 // Determine the owning user as some profile settings are cloned from the parent.
1334 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1335
1336 // Only the owning user can change the setting.
1337 if (owningUserId != callingUserId) {
1338 return false;
1339 }
1340
1341 // Special cases for location providers (sigh).
1342 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001343 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1344 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001345 }
1346
1347 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001348 synchronized (mLock) {
1349 switch (operation) {
1350 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001351 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001352 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001353 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001354 }
Svetoslav683914b2015-01-15 14:22:26 -08001355
Svetoslav7ec28e82015-05-20 17:01:10 -07001356 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001357 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001358 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001359 }
Svetoslav683914b2015-01-15 14:22:26 -08001360
Svetoslav7ec28e82015-05-20 17:01:10 -07001361 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001362 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001363 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001364 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001365 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001366
1367 case MUTATION_OPERATION_RESET: {
1368 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1369 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1370 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001371 }
1372 }
1373
1374 return false;
1375 }
1376
Svetoslav7ec28e82015-05-20 17:01:10 -07001377 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001378 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001379 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001380 }
1381
1382 // Resolve the userId on whose behalf the call is made.
1383 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1384
Svetoslav7ec28e82015-05-20 17:01:10 -07001385 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001386 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001387
Svetoslav7ec28e82015-05-20 17:01:10 -07001388 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001389
Svetoslav7ec28e82015-05-20 17:01:10 -07001390 String[] normalizedProjection = normalizeProjection(projection);
1391 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001392
Svetoslav7ec28e82015-05-20 17:01:10 -07001393 for (int i = 0; i < nameCount; i++) {
1394 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001395
Svetoslav7ec28e82015-05-20 17:01:10 -07001396 // Determine the owning user as some profile settings are cloned from the parent.
1397 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1398 name);
Svetoslav683914b2015-01-15 14:22:26 -08001399
Svetoslav7ec28e82015-05-20 17:01:10 -07001400 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001401 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001402 appendSettingToCursor(result, setting);
1403 }
1404
1405 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001406 }
Svetoslav683914b2015-01-15 14:22:26 -08001407 }
1408
Svetoslav7ec28e82015-05-20 17:01:10 -07001409 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001410 if (DEBUG) {
1411 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1412 }
1413
1414 // Resolve the userId on whose behalf the call is made.
1415 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1416
Chad Brubakera6830e72017-04-28 17:34:36 -07001417 // Ensure the caller can access the setting.
1418 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001419
Svetoslav683914b2015-01-15 14:22:26 -08001420 // Determine the owning user as some profile settings are cloned from the parent.
1421 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1422
1423 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001424 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001425 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001426 }
Svetoslav683914b2015-01-15 14:22:26 -08001427 }
1428
Svetoslav7ec28e82015-05-20 17:01:10 -07001429 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001430 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001431 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001432 + requestingUserId + ")");
1433 }
1434
Svetoslav7ec28e82015-05-20 17:01:10 -07001435 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001436 }
1437
Svetoslav7ec28e82015-05-20 17:01:10 -07001438 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001439 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001440 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001441 }
1442
Svetoslav7ec28e82015-05-20 17:01:10 -07001443 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001444 }
1445
Svetoslav7ec28e82015-05-20 17:01:10 -07001446 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001447 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001448 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001449 + requestingUserId + ")");
1450 }
1451
Svetoslav7ec28e82015-05-20 17:01:10 -07001452 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001453 }
1454
Svetoslav7ec28e82015-05-20 17:01:10 -07001455 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001456 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001457 if (!hasWriteSecureSettingsPermission()) {
1458 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1459 // operation is allowed for the calling package through appops.
1460 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1461 Binder.getCallingUid(), getCallingPackage(), true)) {
1462 return false;
1463 }
Svetoslav683914b2015-01-15 14:22:26 -08001464 }
1465
Svetoslav683914b2015-01-15 14:22:26 -08001466 // Resolve the userId on whose behalf the call is made.
1467 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1468
Svetoslavd8d25e02015-11-20 13:09:26 -08001469 // Enforce what the calling package can mutate the system settings.
1470 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1471
Svetoslav683914b2015-01-15 14:22:26 -08001472 // Determine the owning user as some profile settings are cloned from the parent.
1473 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1474
1475 // Only the owning user id can change the setting.
1476 if (owningUserId != callingUserId) {
1477 return false;
1478 }
1479
Jeff Sharkey413573a2016-02-22 17:52:45 -07001480 // Invalidate any relevant cache files
1481 String cacheName = null;
1482 if (Settings.System.RINGTONE.equals(name)) {
1483 cacheName = Settings.System.RINGTONE_CACHE;
1484 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1485 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1486 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1487 cacheName = Settings.System.ALARM_ALERT_CACHE;
1488 }
1489 if (cacheName != null) {
1490 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001491 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001492 cacheFile.delete();
1493 }
1494
Svetoslav683914b2015-01-15 14:22:26 -08001495 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001496 synchronized (mLock) {
1497 switch (operation) {
1498 case MUTATION_OPERATION_INSERT: {
1499 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001500 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001501 owningUserId, name, value, null, false, getCallingPackage(),
1502 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001503 }
1504
1505 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001506 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001507 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001508 }
1509
1510 case MUTATION_OPERATION_UPDATE: {
1511 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001512 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001513 owningUserId, name, value, null, false, getCallingPackage(),
1514 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001515 }
Svetoslav683914b2015-01-15 14:22:26 -08001516 }
1517
Svetoslav7ec28e82015-05-20 17:01:10 -07001518 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001519 }
Svetoslav683914b2015-01-15 14:22:26 -08001520 }
1521
Billy Lau6ad2d662015-07-18 00:26:58 +01001522 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001523 // Write secure settings is a more protected permission. If caller has it we are good.
1524 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1525 == PackageManager.PERMISSION_GRANTED) {
1526 return true;
1527 }
1528
Svetoslavf41334b2015-06-23 12:06:03 -07001529 return false;
1530 }
1531
Svetoslav683914b2015-01-15 14:22:26 -08001532 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001533 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001534 if (validator != null && !validator.validate(value)) {
1535 throw new IllegalArgumentException("Invalid value: " + value
1536 + " for setting: " + name);
1537 }
1538 }
1539
Alex Klyubin1991f572017-03-03 14:08:36 -08001540 /**
1541 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1542 */
1543 private boolean isSecureSettingAccessible(String name, int callingUserId,
1544 int owningUserId) {
1545 // Special case for location (sigh).
1546 // This check is not inside the name-based checks below because this method performs checks
1547 // only if the calling user ID is not the same as the owning user ID.
1548 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1549 return false;
1550 }
1551
1552 switch (name) {
1553 case "bluetooth_address":
1554 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1555 // address in this secure setting. Secure settings can normally be read by any app,
1556 // which thus enables them to bypass the recently introduced restrictions on access
1557 // to device identifiers.
1558 // To mitigate this we make this setting available only to callers privileged to see
1559 // this device's MAC addresses, same as through public API
1560 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1561 return getContext().checkCallingOrSelfPermission(
1562 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1563 default:
1564 return true;
1565 }
1566 }
1567
Svetoslav683914b2015-01-15 14:22:26 -08001568 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1569 int owningUserId) {
1570 // Optimization - location providers are restricted only for managed profiles.
1571 if (callingUserId == owningUserId) {
1572 return false;
1573 }
1574 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1575 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1576 new UserHandle(callingUserId))) {
1577 return true;
1578 }
1579 return false;
1580 }
1581
Yueming Wang348bf622018-02-24 03:30:17 +00001582 /**
1583 * Checks whether changing a setting to a value is prohibited by the corresponding user
1584 * restriction.
1585 *
1586 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1587 * Context, int, String, boolean)}, which should be in sync with this method.
1588 *
1589 * @return true if the change is prohibited, false if the change is allowed.
1590 */
1591 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
1592 String value, int callingUid) {
1593 String restriction;
1594 boolean checkAllUser = false;
1595 switch (setting) {
1596 case Settings.Secure.LOCATION_MODE:
1597 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1598 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1599 // here normally, but we still protect it here from a direct provider write.
1600 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1601 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1602 break;
1603
1604 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1605 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1606 // a provider, which should be allowed even if the user restriction is set.
1607 if (value != null && value.startsWith("-")) return false;
1608 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1609 break;
1610
1611 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1612 if ("0".equals(value)) return false;
1613 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1614 break;
1615
1616 case Settings.Global.ADB_ENABLED:
1617 if ("0".equals(value)) return false;
1618 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1619 break;
1620
1621 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1622 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1623 if ("1".equals(value)) return false;
1624 restriction = UserManager.ENSURE_VERIFY_APPS;
1625 break;
1626
1627 case Settings.Global.PREFERRED_NETWORK_MODE:
1628 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1629 break;
1630
1631 case Settings.Secure.ALWAYS_ON_VPN_APP:
1632 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1633 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
1634 final int appId = UserHandle.getAppId(callingUid);
1635 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
1636 return false;
1637 }
1638 restriction = UserManager.DISALLOW_CONFIG_VPN;
1639 break;
1640
1641 case Settings.Global.SAFE_BOOT_DISALLOWED:
1642 if ("1".equals(value)) return false;
1643 restriction = UserManager.DISALLOW_SAFE_BOOT;
1644 break;
1645
1646 case Settings.Global.AIRPLANE_MODE_ON:
1647 if ("0".equals(value)) return false;
1648 restriction = UserManager.DISALLOW_AIRPLANE_MODE;
1649 break;
1650
1651 case Settings.Secure.DOZE_ENABLED:
1652 case Settings.Secure.DOZE_ALWAYS_ON:
1653 case Settings.Secure.DOZE_PULSE_ON_PICK_UP:
1654 case Settings.Secure.DOZE_PULSE_ON_LONG_PRESS:
1655 case Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP:
1656 if ("0".equals(value)) return false;
1657 restriction = UserManager.DISALLOW_AMBIENT_DISPLAY;
1658 break;
1659
1660 case Global.LOCATION_GLOBAL_KILL_SWITCH:
1661 if ("0".equals(value)) return false;
1662 restriction = UserManager.DISALLOW_CONFIG_LOCATION;
1663 checkAllUser = true;
1664 break;
1665
1666 default:
1667 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
1668 if ("0".equals(value)) return false;
1669 restriction = UserManager.DISALLOW_DATA_ROAMING;
1670 break;
1671 }
1672 return false;
1673 }
1674
1675 if (checkAllUser) {
1676 return mUserManager.hasUserRestrictionOnAnyUser(restriction);
1677 } else {
1678 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
1679 }
1680 }
1681
Svetoslav683914b2015-01-15 14:22:26 -08001682 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1683 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1684 }
1685
1686 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001687 final int parentId;
1688 // Resolves dependency if setting has a dependency and the calling user has a parent
1689 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1690 && (parentId = getGroupParentLocked(userId)) != userId) {
1691 // The setting has a dependency and the profile has a parent
1692 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001693 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1694 final long token = Binder.clearCallingIdentity();
1695 try {
1696 Setting settingObj = getSecureSetting(dependency, userId);
1697 if (settingObj != null && settingObj.getValue().equals("1")) {
1698 return parentId;
1699 }
1700 } finally {
1701 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001702 }
1703 }
Svetoslav683914b2015-01-15 14:22:26 -08001704 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1705 }
1706
1707 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1708 final int parentId = getGroupParentLocked(userId);
1709 if (parentId != userId && keys.contains(name)) {
1710 return parentId;
1711 }
1712 return userId;
1713 }
1714
Svetoslavf41334b2015-06-23 12:06:03 -07001715 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001716 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001717 // System/root/shell can mutate whatever secure settings they want.
1718 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001719 final int appId = UserHandle.getAppId(callingUid);
1720 if (appId == android.os.Process.SYSTEM_UID
1721 || appId == Process.SHELL_UID
1722 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001723 return;
1724 }
1725
1726 switch (operation) {
1727 case MUTATION_OPERATION_INSERT:
1728 // Insert updates.
1729 case MUTATION_OPERATION_UPDATE: {
1730 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1731 return;
1732 }
1733
1734 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001735 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001736
1737 // Privileged apps can do whatever they want.
1738 if ((packageInfo.applicationInfo.privateFlags
1739 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1740 return;
1741 }
1742
1743 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1744 packageInfo.applicationInfo.targetSdkVersion, name);
1745 } break;
1746
1747 case MUTATION_OPERATION_DELETE: {
1748 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1749 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1750 throw new IllegalArgumentException("You cannot delete system defined"
1751 + " secure settings.");
1752 }
1753
1754 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001755 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001756
1757 // Privileged apps can do whatever they want.
1758 if ((packageInfo.applicationInfo.privateFlags &
1759 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1760 return;
1761 }
1762
1763 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1764 packageInfo.applicationInfo.targetSdkVersion, name);
1765 } break;
1766 }
1767 }
1768
Todd Kennedybe0b8892017-02-15 14:13:52 -08001769 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001770 switch (settingsType) {
1771 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001772 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001773 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001774 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001775 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001776 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001777 default:
1778 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1779 }
1780 }
1781
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001782 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1783 switch (settingsType) {
1784 case SETTINGS_TYPE_GLOBAL:
1785 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1786 case SETTINGS_TYPE_SYSTEM:
1787 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1788 case SETTINGS_TYPE_SECURE:
1789 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1790 default:
1791 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1792 }
1793 }
1794
Chad Brubaker97bccee2017-01-05 15:51:41 -08001795 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001796 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1797 // in the current form.
1798 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001799 }
1800
Chad Brubakera6830e72017-04-28 17:34:36 -07001801 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001802 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1803 return;
1804 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001805 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001806 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001807 return;
1808 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001809 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1810 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001811 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1812 // breakage in the current form.
1813 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1814 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001815 }
1816 }
1817
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001818 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1819 // We always use the callingUid for this lookup. This means that if hypothetically an
1820 // app was installed in user A with cross user and in user B as an Instant App
1821 // the app in A would be able to see all the settings in user B. However since cross
1822 // user is a system permission and the app must be uninstalled in B and then installed as
1823 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001824 ApplicationInfo ai = null;
1825 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001826 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1827 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001828 } catch (RemoteException ignored) {
1829 }
1830 if (ai == null) {
1831 throw new IllegalStateException("Failed to lookup info for package "
1832 + getCallingPackage());
1833 }
1834 return ai;
1835 }
1836
Xiaohui Chen43765b72015-08-31 10:57:33 -07001837 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001838 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001839 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1840 getCallingPackage(), 0, userId);
1841 if (packageInfo != null) {
1842 return packageInfo;
1843 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001844 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001845 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001846 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001847 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001848 }
1849
1850 private int getGroupParentLocked(int userId) {
1851 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001852 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001853 return userId;
1854 }
1855 // We are in the same process with the user manager and the returned
1856 // user info is a cached instance, so just look up instead of cache.
1857 final long identity = Binder.clearCallingIdentity();
1858 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001859 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001860 UserInfo userInfo = mUserManager.getProfileParent(userId);
1861 return (userInfo != null) ? userInfo.id : userId;
1862 } finally {
1863 Binder.restoreCallingIdentity(identity);
1864 }
1865 }
1866
Svetoslav683914b2015-01-15 14:22:26 -08001867 private void enforceWritePermission(String permission) {
1868 if (getContext().checkCallingOrSelfPermission(permission)
1869 != PackageManager.PERMISSION_GRANTED) {
1870 throw new SecurityException("Permission denial: writing to settings requires:"
1871 + permission);
1872 }
1873 }
1874
1875 /*
1876 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1877 * This setting contains a list of the currently enabled location providers.
1878 * But helper functions in android.providers.Settings can enable or disable
1879 * a single provider by using a "+" or "-" prefix before the provider name.
1880 *
Yueming Wang348bf622018-02-24 03:30:17 +00001881 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1882 * is set, the said method will only allow values with the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001883 *
Svetoslav683914b2015-01-15 14:22:26 -08001884 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001885 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001886 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1887 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001888 if (TextUtils.isEmpty(value)) {
1889 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001890 }
1891
Svetoslav683914b2015-01-15 14:22:26 -08001892 final char prefix = value.charAt(0);
1893 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001894 if (forceNotify) {
1895 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1896 mSettingsRegistry.notifyForSettingsChange(key,
1897 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1898 }
Svetoslav683914b2015-01-15 14:22:26 -08001899 return false;
1900 }
1901
1902 // skip prefix
1903 value = value.substring(1);
1904
Svetoslav7ec28e82015-05-20 17:01:10 -07001905 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001906 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001907 if (settingValue == null) {
1908 return false;
1909 }
Svetoslav683914b2015-01-15 14:22:26 -08001910
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001911 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001912
1913 int index = oldProviders.indexOf(value);
1914 int end = index + value.length();
1915
1916 // check for commas to avoid matching on partial string
1917 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1918 index = -1;
1919 }
1920
1921 // check for commas to avoid matching on partial string
1922 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1923 index = -1;
1924 }
1925
1926 String newProviders;
1927
1928 if (prefix == '+' && index < 0) {
1929 // append the provider to the list if not present
1930 if (oldProviders.length() == 0) {
1931 newProviders = value;
1932 } else {
1933 newProviders = oldProviders + ',' + value;
1934 }
1935 } else if (prefix == '-' && index >= 0) {
1936 // remove the provider from the list if present
1937 // remove leading or trailing comma
1938 if (index > 0) {
1939 index--;
1940 } else if (end < oldProviders.length()) {
1941 end++;
1942 }
1943
1944 newProviders = oldProviders.substring(0, index);
1945 if (end < oldProviders.length()) {
1946 newProviders += oldProviders.substring(end);
1947 }
1948 } else {
1949 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001950 if (forceNotify) {
1951 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1952 mSettingsRegistry.notifyForSettingsChange(key,
1953 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1954 }
Svetoslav683914b2015-01-15 14:22:26 -08001955 return false;
1956 }
1957
Svet Ganov53a441c2016-04-19 19:38:00 -07001958 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001959 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001960 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001961 }
1962
Svetoslav683914b2015-01-15 14:22:26 -08001963 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1964 int targetSdkVersion, String name) {
1965 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1966 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1967 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1968 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1969 + " This will soon become an error.");
1970 } else {
1971 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1972 + " This will soon become an error.");
1973 }
1974 } else {
1975 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1976 throw new IllegalArgumentException("You cannot change private secure settings.");
1977 } else {
1978 throw new IllegalArgumentException("You cannot keep your settings in"
1979 + " the secure settings.");
1980 }
1981 }
1982 }
1983
1984 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1985 if (requestingUserId == UserHandle.getCallingUserId()) {
1986 return requestingUserId;
1987 }
1988 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1989 Binder.getCallingUid(), requestingUserId, false, true,
1990 "get/set setting for user", null);
1991 }
1992
Svet Ganov53a441c2016-04-19 19:38:00 -07001993 private Bundle packageValueForCallResult(Setting setting,
1994 boolean trackingGeneration) {
1995 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001996 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001997 return NULL_SETTING_BUNDLE;
1998 }
1999 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002000 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002001 Bundle result = new Bundle();
2002 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002003 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002004
Svetoslav Ganove080da92016-12-21 17:10:35 -08002005 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002006 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002007 }
2008
2009 private static int getRequestingUserId(Bundle args) {
2010 final int callingUserId = UserHandle.getCallingUserId();
2011 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2012 : callingUserId;
2013 }
2014
Svet Ganov53a441c2016-04-19 19:38:00 -07002015 private boolean isTrackingGeneration(Bundle args) {
2016 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2017 }
2018
Svetoslav683914b2015-01-15 14:22:26 -08002019 private static String getSettingValue(Bundle args) {
2020 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2021 }
2022
Svetoslav Ganove080da92016-12-21 17:10:35 -08002023 private static String getSettingTag(Bundle args) {
2024 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2025 }
2026
2027 private static boolean getSettingMakeDefault(Bundle args) {
2028 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2029 }
2030
2031 private static int getResetModeEnforcingPermission(Bundle args) {
2032 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2033 switch (mode) {
2034 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2035 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2036 throw new SecurityException("Only system, shell/root on a "
2037 + "debuggable build can reset to untrusted defaults");
2038 }
2039 return mode;
2040 }
2041 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2042 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2043 throw new SecurityException("Only system, shell/root on a "
2044 + "debuggable build can reset untrusted changes");
2045 }
2046 return mode;
2047 }
2048 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2049 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2050 throw new SecurityException("Only system, shell/root on a "
2051 + "debuggable build can reset to trusted defaults");
2052 }
2053 return mode;
2054 }
2055 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2056 return mode;
2057 }
2058 }
2059 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2060 }
2061
2062 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2063 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2064 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2065 && (appId == SHELL_UID || appId == ROOT_UID));
2066 }
2067
Svetoslav683914b2015-01-15 14:22:26 -08002068 private static String getValidTableOrThrow(Uri uri) {
2069 if (uri.getPathSegments().size() > 0) {
2070 String table = uri.getPathSegments().get(0);
2071 if (DatabaseHelper.isValidTable(table)) {
2072 return table;
2073 }
2074 throw new IllegalArgumentException("Bad root path: " + table);
2075 }
2076 throw new IllegalArgumentException("Invalid URI:" + uri);
2077 }
2078
2079 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002080 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002081 return new MatrixCursor(projection, 0);
2082 }
2083 MatrixCursor cursor = new MatrixCursor(projection, 1);
2084 appendSettingToCursor(cursor, setting);
2085 return cursor;
2086 }
2087
2088 private static String[] normalizeProjection(String[] projection) {
2089 if (projection == null) {
2090 return ALL_COLUMNS;
2091 }
2092
2093 final int columnCount = projection.length;
2094 for (int i = 0; i < columnCount; i++) {
2095 String column = projection[i];
2096 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2097 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002098 }
2099 }
2100
Svetoslav683914b2015-01-15 14:22:26 -08002101 return projection;
2102 }
2103
2104 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002105 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002106 return;
2107 }
Svetoslav683914b2015-01-15 14:22:26 -08002108 final int columnCount = cursor.getColumnCount();
2109
2110 String[] values = new String[columnCount];
2111
2112 for (int i = 0; i < columnCount; i++) {
2113 String column = cursor.getColumnName(i);
2114
2115 switch (column) {
2116 case Settings.NameValueTable._ID: {
2117 values[i] = setting.getId();
2118 } break;
2119
2120 case Settings.NameValueTable.NAME: {
2121 values[i] = setting.getName();
2122 } break;
2123
2124 case Settings.NameValueTable.VALUE: {
2125 values[i] = setting.getValue();
2126 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002127 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002128 }
2129
Svetoslav683914b2015-01-15 14:22:26 -08002130 cursor.addRow(values);
2131 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002132
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002133 private static boolean isKeyValid(String key) {
2134 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2135 }
2136
Svetoslav683914b2015-01-15 14:22:26 -08002137 private static final class Arguments {
2138 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2139 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2140
2141 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2142 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2143
2144 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2145 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2146
2147 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2148 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2149
2150 public final String table;
2151 public final String name;
2152
2153 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2154 final int segmentSize = uri.getPathSegments().size();
2155 switch (segmentSize) {
2156 case 1: {
2157 if (where != null
2158 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2159 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2160 && whereArgs.length == 1) {
2161 name = whereArgs[0];
2162 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002163 return;
Svetoslav683914b2015-01-15 14:22:26 -08002164 } else if (where != null
2165 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2166 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2167 final int startIndex = Math.max(where.indexOf("'"),
2168 where.indexOf("\"")) + 1;
2169 final int endIndex = Math.max(where.lastIndexOf("'"),
2170 where.lastIndexOf("\""));
2171 name = where.substring(startIndex, endIndex);
2172 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002173 return;
Svetoslav683914b2015-01-15 14:22:26 -08002174 } else if (supportAll && where == null && whereArgs == null) {
2175 name = null;
2176 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002177 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002178 }
Svetoslav683914b2015-01-15 14:22:26 -08002179 } break;
2180
Svetoslav28494652015-02-12 14:11:42 -08002181 case 2: {
2182 if (where == null && whereArgs == null) {
2183 name = uri.getPathSegments().get(1);
2184 table = computeTableForSetting(uri, name);
2185 return;
2186 }
2187 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002188 }
Svetoslav28494652015-02-12 14:11:42 -08002189
2190 EventLogTags.writeUnsupportedSettingsQuery(
2191 uri.toSafeString(), where, Arrays.toString(whereArgs));
2192 String message = String.format( "Supported SQL:\n"
2193 + " uri content://some_table/some_property with null where and where args\n"
2194 + " uri content://some_table with query name=? and single name as arg\n"
2195 + " uri content://some_table with query name=some_name and null args\n"
2196 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2197 Arrays.toString(whereArgs));
2198 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002199 }
2200
Svetoslav28494652015-02-12 14:11:42 -08002201 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002202 String table = getValidTableOrThrow(uri);
2203
2204 if (name != null) {
2205 if (sSystemMovedToSecureSettings.contains(name)) {
2206 table = TABLE_SECURE;
2207 }
2208
2209 if (sSystemMovedToGlobalSettings.contains(name)) {
2210 table = TABLE_GLOBAL;
2211 }
2212
2213 if (sSecureMovedToGlobalSettings.contains(name)) {
2214 table = TABLE_GLOBAL;
2215 }
2216
2217 if (sGlobalMovedToSecureSettings.contains(name)) {
2218 table = TABLE_SECURE;
2219 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002220 }
Svetoslav683914b2015-01-15 14:22:26 -08002221
2222 return table;
2223 }
2224 }
2225
2226 final class SettingsRegistry {
2227 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2228
Svetoslav683914b2015-01-15 14:22:26 -08002229 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2230 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2231 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002232 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2233
2234 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002235
2236 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2237
Svet Ganov53a441c2016-04-19 19:38:00 -07002238 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002239
Svetoslav7e0683b2015-08-03 16:02:52 -07002240 private final Handler mHandler;
2241
Svet Ganov53a441c2016-04-19 19:38:00 -07002242 private final BackupManager mBackupManager;
2243
Amith Yamasani39452022017-03-21 15:23:47 -07002244 private String mSettingsCreationBuildId;
2245
Svetoslav683914b2015-01-15 14:22:26 -08002246 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002247 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002248 mGenerationRegistry = new GenerationRegistry(mLock);
2249 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002250 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002251 syncSsaidTableOnStart();
2252 }
2253
2254 private void generateUserKeyLocked(int userId) {
2255 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002256 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002257 final SecureRandom rand = new SecureRandom();
2258 rand.nextBytes(keyBytes);
2259
2260 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002261 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002262
2263 // Store the key in the ssaid table.
2264 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2265 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2266 true, SettingsState.SYSTEM_PACKAGE_NAME);
2267
2268 if (!success) {
2269 throw new IllegalStateException("Ssaid settings not accessible");
2270 }
2271 }
2272
Mark Rathjen7599f132017-01-23 14:15:54 -08002273 private byte[] getLengthPrefix(byte[] data) {
2274 return ByteBuffer.allocate(4).putInt(data.length).array();
2275 }
2276
Christopher Tateb218e762017-04-05 16:34:07 -07002277 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002278 // Read the user's key from the ssaid table.
2279 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002280 if (userKeySetting == null || userKeySetting.isNull()
2281 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002282 // Lazy initialize and store the user key.
2283 generateUserKeyLocked(userId);
2284 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002285 if (userKeySetting == null || userKeySetting.isNull()
2286 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002287 throw new IllegalStateException("User key not accessible");
2288 }
2289 }
2290 final String userKey = userKeySetting.getValue();
2291
2292 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002293 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2294
2295 // Validate that the key is of expected length.
2296 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2297 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002298 throw new IllegalStateException("User key invalid");
2299 }
2300
Mark Rathjen7599f132017-01-23 14:15:54 -08002301 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002302 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002303 m = Mac.getInstance("HmacSHA256");
2304 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002305 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002306 throw new IllegalStateException("HmacSHA256 is not available", e);
2307 } catch (InvalidKeyException e) {
2308 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002309 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002310
Mark Rathjenf42dd912017-06-05 19:04:34 -07002311 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002312 for (int i = 0; i < callingPkg.signatures.length; i++) {
2313 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002314 m.update(getLengthPrefix(sig), 0, 4);
2315 m.update(sig);
2316 }
Mark Rathjend891f012017-01-19 04:10:37 +00002317
2318 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002319 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2320 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002321
2322 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002323 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002324 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2325 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002326 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002327
2328 if (!success) {
2329 throw new IllegalStateException("Ssaid settings not accessible");
2330 }
2331
2332 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2333 }
2334
2335 public void syncSsaidTableOnStart() {
2336 synchronized (mLock) {
2337 // Verify that each user's packages and ssaid's are in sync.
2338 for (UserInfo user : mUserManager.getUsers(true)) {
2339 // Get all uids for the user's packages.
2340 final List<PackageInfo> packages;
2341 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002342 packages = mPackageManager.getInstalledPackages(
2343 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2344 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002345 } catch (RemoteException e) {
2346 throw new IllegalStateException("Package manager not available");
2347 }
2348 final Set<String> appUids = new HashSet<>();
2349 for (PackageInfo info : packages) {
2350 appUids.add(Integer.toString(info.applicationInfo.uid));
2351 }
2352
2353 // Get all uids currently stored in the user's ssaid table.
2354 final Set<String> ssaidUids = new HashSet<>(
2355 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2356 ssaidUids.remove(SSAID_USER_KEY);
2357
2358 // Perform a set difference for the appUids and ssaidUids.
2359 ssaidUids.removeAll(appUids);
2360
2361 // If there are ssaidUids left over they need to be removed from the table.
2362 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2363 user.id);
2364 for (String uid : ssaidUids) {
2365 ssaidSettings.deleteSettingLocked(uid);
2366 }
2367 }
2368 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002369 }
2370
Svetoslav683914b2015-01-15 14:22:26 -08002371 public List<String> getSettingsNamesLocked(int type, int userId) {
2372 final int key = makeKey(type, userId);
2373 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002374 if (settingsState == null) {
2375 return new ArrayList<String>();
2376 }
Svetoslav683914b2015-01-15 14:22:26 -08002377 return settingsState.getSettingNamesLocked();
2378 }
2379
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002380 public SparseBooleanArray getKnownUsersLocked() {
2381 SparseBooleanArray users = new SparseBooleanArray();
2382 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2383 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2384 }
2385 return users;
2386 }
2387
Kweku Adamsb0886f32017-10-31 15:32:09 -07002388 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002389 public SettingsState getSettingsLocked(int type, int userId) {
2390 final int key = makeKey(type, userId);
2391 return peekSettingsStateLocked(key);
2392 }
2393
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002394 public boolean ensureSettingsForUserLocked(int userId) {
2395 // First make sure this user actually exists.
2396 if (mUserManager.getUserInfo(userId) == null) {
2397 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2398 return false;
2399 }
2400
Svetoslav683914b2015-01-15 14:22:26 -08002401 // Migrate the setting for this user if needed.
2402 migrateLegacySettingsForUserIfNeededLocked(userId);
2403
2404 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002405 if (userId == UserHandle.USER_SYSTEM) {
2406 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002407 ensureSettingsStateLocked(globalKey);
2408 }
2409
2410 // Ensure secure settings loaded.
2411 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2412 ensureSettingsStateLocked(secureKey);
2413
2414 // Make sure the secure settings have an Android id set.
2415 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2416 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2417
2418 // Ensure system settings loaded.
2419 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2420 ensureSettingsStateLocked(systemKey);
2421
Mark Rathjend891f012017-01-19 04:10:37 +00002422 // Ensure secure settings loaded.
2423 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2424 ensureSettingsStateLocked(ssaidKey);
2425
Svetoslav683914b2015-01-15 14:22:26 -08002426 // Upgrade the settings to the latest version.
2427 UpgradeController upgrader = new UpgradeController(userId);
2428 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002429 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002430 }
2431
2432 private void ensureSettingsStateLocked(int key) {
2433 if (mSettingsStates.get(key) == null) {
2434 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002435 SettingsState settingsState = new SettingsState(getContext(), mLock,
2436 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002437 mSettingsStates.put(key, settingsState);
2438 }
2439 }
2440
2441 public void removeUserStateLocked(int userId, boolean permanently) {
2442 // We always keep the global settings in memory.
2443
2444 // Nuke system settings.
2445 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2446 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2447 if (systemSettingsState != null) {
2448 if (permanently) {
2449 mSettingsStates.remove(systemKey);
2450 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002451 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002452 systemSettingsState.destroyLocked(new Runnable() {
2453 @Override
2454 public void run() {
2455 mSettingsStates.remove(systemKey);
2456 }
2457 });
2458 }
2459 }
2460
2461 // Nuke secure settings.
2462 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2463 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2464 if (secureSettingsState != null) {
2465 if (permanently) {
2466 mSettingsStates.remove(secureKey);
2467 secureSettingsState.destroyLocked(null);
2468 } else {
2469 secureSettingsState.destroyLocked(new Runnable() {
2470 @Override
2471 public void run() {
2472 mSettingsStates.remove(secureKey);
2473 }
2474 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002475 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002476 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002477
Mark Rathjend891f012017-01-19 04:10:37 +00002478 // Nuke ssaid settings.
2479 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2480 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2481 if (ssaidSettingsState != null) {
2482 if (permanently) {
2483 mSettingsStates.remove(ssaidKey);
2484 ssaidSettingsState.destroyLocked(null);
2485 } else {
2486 ssaidSettingsState.destroyLocked(new Runnable() {
2487 @Override
2488 public void run() {
2489 mSettingsStates.remove(ssaidKey);
2490 }
2491 });
2492 }
2493 }
2494
Svet Ganov53a441c2016-04-19 19:38:00 -07002495 // Nuke generation tracking data
2496 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002497 }
2498
Svetoslav683914b2015-01-15 14:22:26 -08002499 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002500 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2501 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002502 final int key = makeKey(type, userId);
2503
Svetoslav Ganove080da92016-12-21 17:10:35 -08002504 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002505 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002506 if (settingsState != null) {
2507 success = settingsState.insertSettingLocked(name, value,
2508 tag, makeDefault, packageName);
2509 }
Svetoslav683914b2015-01-15 14:22:26 -08002510
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002511 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2512 settingsState.persistSyncLocked();
2513 }
2514
Svet Ganov53a441c2016-04-19 19:38:00 -07002515 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002516 notifyForSettingsChange(key, name);
2517 }
2518 return success;
2519 }
2520
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002521 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2522 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002523 final int key = makeKey(type, userId);
2524
Svetoslav Ganove080da92016-12-21 17:10:35 -08002525 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002526 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002527 if (settingsState != null) {
2528 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002529 }
Svetoslav683914b2015-01-15 14:22:26 -08002530
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002531 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2532 settingsState.persistSyncLocked();
2533 }
2534
Svet Ganov53a441c2016-04-19 19:38:00 -07002535 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002536 notifyForSettingsChange(key, name);
2537 }
2538 return success;
2539 }
2540
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002541 public boolean updateSettingLocked(int type, int userId, String name, String value,
2542 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2543 Set<String> criticalSettings) {
2544 final int key = makeKey(type, userId);
2545
2546 boolean success = false;
2547 SettingsState settingsState = peekSettingsStateLocked(key);
2548 if (settingsState != null) {
2549 success = settingsState.updateSettingLocked(name, value, tag,
2550 makeDefault, packageName);
2551 }
2552
2553 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2554 settingsState.persistSyncLocked();
2555 }
2556
2557 if (forceNotify || success) {
2558 notifyForSettingsChange(key, name);
2559 }
2560
2561 return success;
2562 }
2563
Svetoslav683914b2015-01-15 14:22:26 -08002564 public Setting getSettingLocked(int type, int userId, String name) {
2565 final int key = makeKey(type, userId);
2566
2567 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002568 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002569 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002570 }
Mark Rathjend891f012017-01-19 04:10:37 +00002571
2572 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002573 return settingsState.getSettingLocked(name);
2574 }
2575
Svetoslav Ganove080da92016-12-21 17:10:35 -08002576 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2577 String tag) {
2578 final int key = makeKey(type, userId);
2579 SettingsState settingsState = peekSettingsStateLocked(key);
2580 if (settingsState == null) {
2581 return;
2582 }
2583
2584 switch (mode) {
2585 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2586 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002587 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002588 Setting setting = settingsState.getSettingLocked(name);
2589 if (packageName.equals(setting.getPackageName())) {
2590 if (tag != null && !tag.equals(setting.getTag())) {
2591 continue;
2592 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002593 if (settingsState.resetSettingLocked(name)) {
2594 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002595 notifyForSettingsChange(key, name);
2596 }
2597 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002598 if (someSettingChanged) {
2599 settingsState.persistSyncLocked();
2600 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002601 }
2602 } break;
2603
2604 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2605 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002606 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002607 Setting setting = settingsState.getSettingLocked(name);
2608 if (!SettingsState.isSystemPackage(getContext(),
2609 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002610 if (settingsState.resetSettingLocked(name)) {
2611 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002612 notifyForSettingsChange(key, name);
2613 }
2614 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002615 if (someSettingChanged) {
2616 settingsState.persistSyncLocked();
2617 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002618 }
2619 } break;
2620
2621 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2622 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002623 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002624 Setting setting = settingsState.getSettingLocked(name);
2625 if (!SettingsState.isSystemPackage(getContext(),
2626 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002627 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002628 if (settingsState.resetSettingLocked(name)) {
2629 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002630 notifyForSettingsChange(key, name);
2631 }
2632 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002633 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002634 notifyForSettingsChange(key, name);
2635 }
2636 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002637 if (someSettingChanged) {
2638 settingsState.persistSyncLocked();
2639 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002640 }
2641 } break;
2642
2643 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2644 for (String name : settingsState.getSettingNamesLocked()) {
2645 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002646 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002647 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002648 if (settingsState.resetSettingLocked(name)) {
2649 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002650 notifyForSettingsChange(key, name);
2651 }
2652 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002653 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002654 notifyForSettingsChange(key, name);
2655 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002656 if (someSettingChanged) {
2657 settingsState.persistSyncLocked();
2658 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002659 }
2660 } break;
2661 }
2662 }
2663
Svetoslav683914b2015-01-15 14:22:26 -08002664 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002665 // Global and secure settings are signature protected. Apps signed
2666 // by the platform certificate are generally not uninstalled and
2667 // the main exception is tests. We trust components signed
2668 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002669
2670 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2671 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002672 if (systemSettings != null) {
2673 systemSettings.onPackageRemovedLocked(packageName);
2674 }
Svetoslav683914b2015-01-15 14:22:26 -08002675 }
2676
Mark Rathjend891f012017-01-19 04:10:37 +00002677 public void onUidRemovedLocked(int uid) {
2678 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2679 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002680 if (ssaidSettings != null) {
2681 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2682 }
Mark Rathjend891f012017-01-19 04:10:37 +00002683 }
2684
Kweku Adamsb0886f32017-10-31 15:32:09 -07002685 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002686 private SettingsState peekSettingsStateLocked(int key) {
2687 SettingsState settingsState = mSettingsStates.get(key);
2688 if (settingsState != null) {
2689 return settingsState;
2690 }
2691
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002692 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2693 return null;
2694 }
Svetoslav683914b2015-01-15 14:22:26 -08002695 return mSettingsStates.get(key);
2696 }
2697
2698 private void migrateAllLegacySettingsIfNeeded() {
2699 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002700 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002701 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002702 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002703 return;
2704 }
2705
Amith Yamasani39452022017-03-21 15:23:47 -07002706 mSettingsCreationBuildId = Build.ID;
2707
Svetoslav683914b2015-01-15 14:22:26 -08002708 final long identity = Binder.clearCallingIdentity();
2709 try {
2710 List<UserInfo> users = mUserManager.getUsers(true);
2711
2712 final int userCount = users.size();
2713 for (int i = 0; i < userCount; i++) {
2714 final int userId = users.get(i).id;
2715
2716 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2717 SQLiteDatabase database = dbHelper.getWritableDatabase();
2718 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2719
2720 // Upgrade to the latest version.
2721 UpgradeController upgrader = new UpgradeController(userId);
2722 upgrader.upgradeIfNeededLocked();
2723
2724 // Drop from memory if not a running user.
2725 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2726 removeUserStateLocked(userId, false);
2727 }
2728 }
2729 } finally {
2730 Binder.restoreCallingIdentity(identity);
2731 }
2732 }
2733 }
2734
2735 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2736 // Every user has secure settings and if no file we need to migrate.
2737 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2738 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002739 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002740 return;
2741 }
2742
2743 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2744 SQLiteDatabase database = dbHelper.getWritableDatabase();
2745
2746 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2747 }
2748
2749 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2750 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002751 // Move over the system settings.
2752 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2753 ensureSettingsStateLocked(systemKey);
2754 SettingsState systemSettings = mSettingsStates.get(systemKey);
2755 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2756 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002757
2758 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002759 // Do this after System settings, since this is the first thing we check when deciding
2760 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002761 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2762 ensureSettingsStateLocked(secureKey);
2763 SettingsState secureSettings = mSettingsStates.get(secureKey);
2764 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2765 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2766 secureSettings.persistSyncLocked();
2767
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002768 // Move over the global settings if owner.
2769 // Do this last, since this is the first thing we check when deciding
2770 // to skip over migration from db to xml for owner user.
2771 if (userId == UserHandle.USER_SYSTEM) {
2772 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2773 ensureSettingsStateLocked(globalKey);
2774 SettingsState globalSettings = mSettingsStates.get(globalKey);
2775 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002776 // If this was just created
2777 if (mSettingsCreationBuildId != null) {
2778 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2779 mSettingsCreationBuildId, null, true,
2780 SettingsState.SYSTEM_PACKAGE_NAME);
2781 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002782 globalSettings.persistSyncLocked();
2783 }
Svetoslav683914b2015-01-15 14:22:26 -08002784
2785 // Drop the database as now all is moved and persisted.
2786 if (DROP_DATABASE_ON_MIGRATION) {
2787 dbHelper.dropDatabase();
2788 } else {
2789 dbHelper.backupDatabase();
2790 }
2791 }
2792
2793 private void migrateLegacySettingsLocked(SettingsState settingsState,
2794 SQLiteDatabase database, String table) {
2795 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2796 queryBuilder.setTables(table);
2797
2798 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2799 null, null, null, null, null);
2800
2801 if (cursor == null) {
2802 return;
2803 }
2804
2805 try {
2806 if (!cursor.moveToFirst()) {
2807 return;
2808 }
2809
2810 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2811 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2812
2813 settingsState.setVersionLocked(database.getVersion());
2814
2815 while (!cursor.isAfterLast()) {
2816 String name = cursor.getString(nameColumnIdx);
2817 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002818 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002819 SettingsState.SYSTEM_PACKAGE_NAME);
2820 cursor.moveToNext();
2821 }
2822 } finally {
2823 cursor.close();
2824 }
2825 }
2826
2827 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2828 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2829
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002830 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002831 return;
2832 }
2833
2834 final int userId = getUserIdFromKey(secureSettings.mKey);
2835
2836 final UserInfo user;
2837 final long identity = Binder.clearCallingIdentity();
2838 try {
2839 user = mUserManager.getUserInfo(userId);
2840 } finally {
2841 Binder.restoreCallingIdentity(identity);
2842 }
2843 if (user == null) {
2844 // Can happen due to races when deleting users - treat as benign.
2845 return;
2846 }
2847
2848 String androidId = Long.toHexString(new SecureRandom().nextLong());
2849 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002850 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002851
2852 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2853 + "] for user " + userId);
2854
2855 // Write a drop box entry if it's a restricted profile
2856 if (user.isRestricted()) {
2857 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2858 Context.DROPBOX_SERVICE);
2859 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2860 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2861 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2862 }
2863 }
2864 }
2865
2866 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002867 final int userId = getUserIdFromKey(key);
2868 Uri uri = getNotificationUriFor(key, name);
2869
Phil Weaver83fec002016-05-11 10:55:29 -07002870 mGenerationRegistry.incrementGeneration(key);
2871
Svetoslav7e0683b2015-08-03 16:02:52 -07002872 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2873 userId, 0, uri).sendToTarget();
2874
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002875 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002876 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2877 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002878 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2879 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002880 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002881 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2882 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002883 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002884
Svet Ganov53a441c2016-04-19 19:38:00 -07002885 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Makoto Onuki0000d322017-11-28 16:31:47 -08002886
2887 // When the global kill switch is updated, send the change notification for
2888 // the location setting.
2889 if (isGlobalSettingsKey(key) && Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2890 notifyLocationChangeForRunningUsers();
2891 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002892 }
2893
Svet Ganov53a441c2016-04-19 19:38:00 -07002894 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002895 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002896 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002897 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002898 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002899 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002900 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002901 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002902 final int key = makeKey(type, profileId);
2903 mGenerationRegistry.incrementGeneration(key);
2904
2905 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002906 }
2907 }
2908 }
Svetoslav683914b2015-01-15 14:22:26 -08002909 }
2910
Makoto Onuki0000d322017-11-28 16:31:47 -08002911 private void notifyLocationChangeForRunningUsers() {
2912 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2913
2914 for (int i = 0; i < users.size(); i++) {
2915 final int userId = users.get(i).id;
2916
Makoto Onuki8e498252018-01-22 17:00:00 -08002917 // Do we have to increment the generation for users that are not running?
2918 // Yeah let's assume so...
2919 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2920 mGenerationRegistry.incrementGeneration(key);
2921
Makoto Onuki0000d322017-11-28 16:31:47 -08002922 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2923 continue;
2924 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002925 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
2926
2927 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2928 userId, 0, uri).sendToTarget();
2929 }
2930 }
2931
Svetoslav683914b2015-01-15 14:22:26 -08002932 private boolean isGlobalSettingsKey(int key) {
2933 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2934 }
2935
2936 private boolean isSystemSettingsKey(int key) {
2937 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2938 }
2939
2940 private boolean isSecureSettingsKey(int key) {
2941 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2942 }
2943
Mark Rathjend891f012017-01-19 04:10:37 +00002944 private boolean isSsaidSettingsKey(int key) {
2945 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2946 }
2947
Svetoslav683914b2015-01-15 14:22:26 -08002948 private File getSettingsFile(int key) {
2949 if (isGlobalSettingsKey(key)) {
2950 final int userId = getUserIdFromKey(key);
2951 return new File(Environment.getUserSystemDirectory(userId),
2952 SETTINGS_FILE_GLOBAL);
2953 } else if (isSystemSettingsKey(key)) {
2954 final int userId = getUserIdFromKey(key);
2955 return new File(Environment.getUserSystemDirectory(userId),
2956 SETTINGS_FILE_SYSTEM);
2957 } else if (isSecureSettingsKey(key)) {
2958 final int userId = getUserIdFromKey(key);
2959 return new File(Environment.getUserSystemDirectory(userId),
2960 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002961 } else if (isSsaidSettingsKey(key)) {
2962 final int userId = getUserIdFromKey(key);
2963 return new File(Environment.getUserSystemDirectory(userId),
2964 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002965 } else {
2966 throw new IllegalArgumentException("Invalid settings key:" + key);
2967 }
2968 }
2969
2970 private Uri getNotificationUriFor(int key, String name) {
2971 if (isGlobalSettingsKey(key)) {
2972 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2973 : Settings.Global.CONTENT_URI;
2974 } else if (isSecureSettingsKey(key)) {
2975 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2976 : Settings.Secure.CONTENT_URI;
2977 } else if (isSystemSettingsKey(key)) {
2978 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2979 : Settings.System.CONTENT_URI;
2980 } else {
2981 throw new IllegalArgumentException("Invalid settings key:" + key);
2982 }
2983 }
2984
2985 private int getMaxBytesPerPackageForType(int type) {
2986 switch (type) {
2987 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002988 case SETTINGS_TYPE_SECURE:
2989 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002990 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2991 }
2992
2993 default: {
2994 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2995 }
2996 }
2997 }
2998
Svetoslav7e0683b2015-08-03 16:02:52 -07002999 private final class MyHandler extends Handler {
3000 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3001 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3002
3003 public MyHandler(Looper looper) {
3004 super(looper);
3005 }
3006
3007 @Override
3008 public void handleMessage(Message msg) {
3009 switch (msg.what) {
3010 case MSG_NOTIFY_URI_CHANGED: {
3011 final int userId = msg.arg1;
3012 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003013 try {
3014 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3015 } catch (SecurityException e) {
3016 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3017 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003018 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003019 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3020 }
3021 } break;
3022
3023 case MSG_NOTIFY_DATA_CHANGED: {
3024 mBackupManager.dataChanged();
3025 } break;
3026 }
3027 }
3028 }
3029
Svetoslav683914b2015-01-15 14:22:26 -08003030 private final class UpgradeController {
Beverlyda904812018-03-02 09:55:30 -05003031 private static final int SETTINGS_VERSION = 156;
Svetoslav683914b2015-01-15 14:22:26 -08003032
3033 private final int mUserId;
3034
3035 public UpgradeController(int userId) {
3036 mUserId = userId;
3037 }
3038
3039 public void upgradeIfNeededLocked() {
3040 // The version of all settings for a user is the same (all users have secure).
3041 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003042 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003043
3044 // Try an update from the current state.
3045 final int oldVersion = secureSettings.getVersionLocked();
3046 final int newVersion = SETTINGS_VERSION;
3047
Svet Ganovc9755bc2015-03-28 13:21:22 -07003048 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003049 if (oldVersion == newVersion) {
3050 return;
3051 }
3052
3053 // Try to upgrade.
3054 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3055
3056 // If upgrade failed start from scratch and upgrade.
3057 if (curVersion != newVersion) {
3058 // Drop state we have for this user.
3059 removeUserStateLocked(mUserId, true);
3060
3061 // Recreate the database.
3062 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3063 SQLiteDatabase database = dbHelper.getWritableDatabase();
3064 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3065
3066 // Migrate the settings for this user.
3067 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3068
3069 // Now upgrade should work fine.
3070 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003071
3072 // Make a note what happened, so we don't wonder why data was lost
3073 String reason = "Settings rebuilt! Current version: "
3074 + curVersion + " while expected: " + newVersion;
3075 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003076 Settings.Global.DATABASE_DOWNGRADE_REASON,
3077 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003078 }
3079
3080 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003081 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003082 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003083 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003084 globalSettings.setVersionLocked(newVersion);
3085 }
3086
3087 // Set the secure settings version.
3088 secureSettings.setVersionLocked(newVersion);
3089
3090 // Set the system settings version.
3091 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003092 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003093 systemSettings.setVersionLocked(newVersion);
3094 }
3095
3096 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003097 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003098 }
3099
3100 private SettingsState getSecureSettingsLocked(int userId) {
3101 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3102 }
3103
Mark Rathjend891f012017-01-19 04:10:37 +00003104 private SettingsState getSsaidSettingsLocked(int userId) {
3105 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3106 }
3107
Svetoslav683914b2015-01-15 14:22:26 -08003108 private SettingsState getSystemSettingsLocked(int userId) {
3109 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3110 }
3111
Jeff Brown503cffc2015-03-26 18:08:51 -07003112 /**
3113 * You must perform all necessary mutations to bring the settings
3114 * for this user from the old to the new version. When you add a new
3115 * upgrade step you *must* update SETTINGS_VERSION.
3116 *
3117 * This is an example of moving a setting from secure to global.
3118 *
3119 * // v119: Example settings changes.
3120 * if (currentVersion == 118) {
3121 * if (userId == UserHandle.USER_OWNER) {
3122 * // Remove from the secure settings.
3123 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3124 * String name = "example_setting_to_move";
3125 * String value = secureSettings.getSetting(name);
3126 * secureSettings.deleteSetting(name);
3127 *
3128 * // Add to the global settings.
3129 * SettingsState globalSettings = getGlobalSettingsLocked();
3130 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3131 * }
3132 *
3133 * // Update the current version.
3134 * currentVersion = 119;
3135 * }
3136 */
Svetoslav683914b2015-01-15 14:22:26 -08003137 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3138 if (DEBUG) {
3139 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3140 + oldVersion + " to version: " + newVersion);
3141 }
3142
Jeff Brown503cffc2015-03-26 18:08:51 -07003143 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003144
John Spurlocke11ae112015-05-11 16:09:03 -04003145 // v119: Reset zen + ringer mode.
3146 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003147 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003148 final SettingsState globalSettings = getGlobalSettingsLocked();
3149 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003150 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3151 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003152 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003153 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3154 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003155 }
3156 currentVersion = 119;
3157 }
3158
Jason Monk27bbb2d2015-03-31 16:46:39 -04003159 // v120: Add double tap to wake setting.
3160 if (currentVersion == 119) {
3161 SettingsState secureSettings = getSecureSettingsLocked(userId);
3162 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3163 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003164 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003165 SettingsState.SYSTEM_PACKAGE_NAME);
3166
3167 currentVersion = 120;
3168 }
3169
Svetoslav7e0683b2015-08-03 16:02:52 -07003170 if (currentVersion == 120) {
3171 // Before 121, we used a different string encoding logic. We just bump the
3172 // version here; SettingsState knows how to handle pre-version 120 files.
3173 currentVersion = 121;
3174 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003175
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003176 if (currentVersion == 121) {
3177 // Version 122: allow OEMs to set a default payment component in resources.
3178 // Note that we only write the default if no default has been set;
3179 // if there is, we just leave the default at whatever it currently is.
3180 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3181 String defaultComponent = (getContext().getResources().getString(
3182 R.string.def_nfc_payment_component));
3183 Setting currentSetting = secureSettings.getSettingLocked(
3184 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3185 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003186 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003187 secureSettings.insertSettingLocked(
3188 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003189 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003190 }
3191 currentVersion = 122;
3192 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003193
3194 if (currentVersion == 122) {
3195 // Version 123: Adding a default value for the ability to add a user from
3196 // the lock screen.
3197 if (userId == UserHandle.USER_SYSTEM) {
3198 final SettingsState globalSettings = getGlobalSettingsLocked();
3199 Setting currentSetting = globalSettings.getSettingLocked(
3200 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003201 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003202 globalSettings.insertSettingLocked(
3203 Settings.Global.ADD_USERS_WHEN_LOCKED,
3204 getContext().getResources().getBoolean(
3205 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003206 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003207 }
3208 }
3209 currentVersion = 123;
3210 }
Bryce Leebd179282015-12-17 19:01:37 -08003211
3212 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003213 final SettingsState globalSettings = getGlobalSettingsLocked();
3214 String defaultDisabledProfiles = (getContext().getResources().getString(
3215 R.string.def_bluetooth_disabled_profiles));
3216 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003217 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003218 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003219 }
3220
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003221 if (currentVersion == 124) {
3222 // Version 124: allow OEMs to set a default value for whether IME should be
3223 // shown when a physical keyboard is connected.
3224 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3225 Setting currentSetting = secureSettings.getSettingLocked(
3226 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003227 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003228 secureSettings.insertSettingLocked(
3229 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3230 getContext().getResources().getBoolean(
3231 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003232 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003233 }
3234 currentVersion = 125;
3235 }
3236
Ruben Brunk98576cf2016-03-07 18:54:28 -08003237 if (currentVersion == 125) {
3238 // Version 125: Allow OEMs to set the default VR service.
3239 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3240
3241 Setting currentSetting = secureSettings.getSettingLocked(
3242 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003243 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003244 ArraySet<ComponentName> l =
3245 SystemConfig.getInstance().getDefaultVrComponents();
3246
3247 if (l != null && !l.isEmpty()) {
3248 StringBuilder b = new StringBuilder();
3249 boolean start = true;
3250 for (ComponentName c : l) {
3251 if (!start) {
3252 b.append(':');
3253 }
3254 b.append(c.flattenToString());
3255 start = false;
3256 }
3257 secureSettings.insertSettingLocked(
3258 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003259 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003260 }
3261
3262 }
3263 currentVersion = 126;
3264 }
3265
Daniel U02ba6122016-04-01 18:41:42 +01003266 if (currentVersion == 126) {
3267 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3268 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3269 if (mUserManager.isManagedProfile(userId)) {
3270 final SettingsState systemSecureSettings =
3271 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3272
3273 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3274 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003275 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003276 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3277 secureSettings.insertSettingLocked(
3278 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003279 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003280 SettingsState.SYSTEM_PACKAGE_NAME);
3281 }
3282
3283 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3284 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003285 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003286 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3287 secureSettings.insertSettingLocked(
3288 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003289 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003290 SettingsState.SYSTEM_PACKAGE_NAME);
3291 }
3292 }
3293 currentVersion = 127;
3294 }
3295
Steven Ngdc20ba62016-04-26 18:19:04 +01003296 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003297 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003298 currentVersion = 128;
3299 }
3300
Julia Reynolds1f721e12016-07-11 08:50:58 -04003301 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003302 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003303 currentVersion = 129;
3304 }
3305
Dan Sandler71f85e92016-07-20 13:46:05 -04003306 if (currentVersion == 129) {
3307 // default longpress timeout changed from 500 to 400. If unchanged from the old
3308 // default, update to the new default.
3309 final SettingsState systemSecureSettings =
3310 getSecureSettingsLocked(userId);
3311 final String oldValue = systemSecureSettings.getSettingLocked(
3312 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3313 if (TextUtils.equals("500", oldValue)) {
3314 systemSecureSettings.insertSettingLocked(
3315 Settings.Secure.LONG_PRESS_TIMEOUT,
3316 String.valueOf(getContext().getResources().getInteger(
3317 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003318 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003319 }
3320 currentVersion = 130;
3321 }
3322
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003323 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003324 // Split Ambient settings
3325 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3326 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3327 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3328
3329 if (dozeExplicitlyDisabled) {
3330 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003331 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003332 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003333 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003334 }
3335 currentVersion = 131;
3336 }
3337
3338 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003339 // Initialize new multi-press timeout to default value
3340 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3341 final String oldValue = systemSecureSettings.getSettingLocked(
3342 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3343 if (TextUtils.equals(null, oldValue)) {
3344 systemSecureSettings.insertSettingLocked(
3345 Settings.Secure.MULTI_PRESS_TIMEOUT,
3346 String.valueOf(getContext().getResources().getInteger(
3347 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003348 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003349 }
3350
Adrian Roos69741a22016-10-21 14:49:17 -07003351 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003352 }
3353
Adrian Roos69741a22016-10-21 14:49:17 -07003354 if (currentVersion == 132) {
3355 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003356 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3357 String defaultSyncParentSounds = (getContext().getResources()
3358 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3359 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003360 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3361 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003362 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003363 }
3364
Adrian Roos69741a22016-10-21 14:49:17 -07003365 if (currentVersion == 133) {
3366 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003367 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3368 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3369 null) {
3370 String defaultEndButtonBehavior = Integer.toString(getContext()
3371 .getResources().getInteger(R.integer.def_end_button_behavior));
3372 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003373 defaultEndButtonBehavior, null, true,
3374 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003375 }
Adrian Roos69741a22016-10-21 14:49:17 -07003376 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003377 }
3378
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003379 if (currentVersion == 134) {
3380 // Remove setting that specifies if magnification values should be preserved.
3381 // This setting defaulted to true and never has a UI.
3382 getSecureSettingsLocked(userId).deleteSettingLocked(
3383 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3384 currentVersion = 135;
3385 }
3386
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003387 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003388 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003389 currentVersion = 136;
3390 }
3391
Mark Rathjend891f012017-01-19 04:10:37 +00003392 if (currentVersion == 136) {
3393 // Version 136: Store legacy SSAID for all apps currently installed on the
3394 // device as first step in migrating SSAID to be unique per application.
3395
3396 final boolean isUpgrade;
3397 try {
3398 isUpgrade = mPackageManager.isUpgrade();
3399 } catch (RemoteException e) {
3400 throw new IllegalStateException("Package manager not available");
3401 }
3402 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3403 // user data or first boot on a new device should use new ssaid generation.
3404 if (isUpgrade) {
3405 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003406 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3407 userId, Settings.Secure.ANDROID_ID);
3408 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3409 || legacySsaidSetting.getValue() == null) {
3410 throw new IllegalStateException("Legacy ssaid not accessible");
3411 }
3412 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003413
3414 // Fill each uid with the legacy ssaid to be backwards compatible.
3415 final List<PackageInfo> packages;
3416 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003417 packages = mPackageManager.getInstalledPackages(
3418 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3419 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003420 } catch (RemoteException e) {
3421 throw new IllegalStateException("Package manager not available");
3422 }
3423
3424 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3425 for (PackageInfo info : packages) {
3426 // Check if the UID already has an entry in the table.
3427 final String uid = Integer.toString(info.applicationInfo.uid);
3428 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3429
3430 if (ssaid.isNull() || ssaid.getValue() == null) {
3431 // Android Id doesn't exist for this package so create it.
3432 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3433 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003434 if (DEBUG) {
3435 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3436 }
Mark Rathjend891f012017-01-19 04:10:37 +00003437 }
3438 }
3439 }
3440
3441 currentVersion = 137;
3442 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003443 if (currentVersion == 137) {
3444 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3445 // default value set to 1. The user can no longer change the value of this
3446 // setting through the UI.
3447 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3448 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003449 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3450 && secureSetting.getSettingLocked(
3451 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3452
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003453 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3454 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003455 // For managed profiles with profile owners, DevicePolicyManagerService
3456 // may want to set the user restriction in this case
3457 secureSetting.insertSettingLocked(
3458 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3459 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003460 }
3461 currentVersion = 138;
3462 }
Mark Rathjend891f012017-01-19 04:10:37 +00003463
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003464 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003465 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003466 currentVersion = 139;
3467 }
3468
Phil Weaver385912e2017-02-10 10:06:56 -08003469 if (currentVersion == 139) {
3470 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3471 // the user can no longer change the value of this setting through the UI.
3472 // Force to true.
3473 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3474 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3475 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3476 currentVersion = 140;
3477 }
3478
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003479 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003480 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003481 currentVersion = 141;
3482 }
3483
Svet Ganov13701552017-02-23 12:45:17 -08003484 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003485 // This implementation was incorrectly setting the current value of
3486 // settings changed by non-system packages as the default which default
3487 // is set by the system. We add a new upgrade step at the end to properly
3488 // handle this case which would also fix incorrect changes made by the
3489 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003490 currentVersion = 142;
3491 }
3492
Stephen Chen5d0922f2017-03-27 10:28:04 -07003493 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003494 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003495 if (userId == UserHandle.USER_SYSTEM) {
3496 final SettingsState globalSettings = getGlobalSettingsLocked();
3497 Setting currentSetting = globalSettings.getSettingLocked(
3498 Settings.Global.WIFI_WAKEUP_ENABLED);
3499 if (currentSetting.isNull()) {
3500 globalSettings.insertSettingLocked(
3501 Settings.Global.WIFI_WAKEUP_ENABLED,
3502 getContext().getResources().getBoolean(
3503 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3504 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3505 }
3506 }
3507
3508 currentVersion = 143;
3509 }
3510
Felipe Lemeff355092017-04-03 12:55:02 -07003511 if (currentVersion == 143) {
3512 // Version 144: Set a default value for Autofill service.
3513 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3514 final Setting currentSetting = secureSettings
3515 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3516 if (currentSetting.isNull()) {
3517 final String defaultValue = getContext().getResources().getString(
3518 com.android.internal.R.string.config_defaultAutofillService);
3519 if (defaultValue != null) {
3520 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3521 + "for user " + userId);
3522 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3523 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3524 }
3525 }
3526
3527 currentVersion = 144;
3528 }
3529
Jeremy Joslin45caa252017-05-04 11:22:46 -07003530 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003531 // Version 145: Removed
3532 currentVersion = 145;
3533 }
3534
3535 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003536 // Version 146: In step 142 we had a bug where incorrectly
3537 // some settings were considered system set and as a result
3538 // made the default and marked as the default being set by
3539 // the system. Here reevaluate the default and default system
3540 // set flags. This would both fix corruption by the old impl
3541 // of step 142 and also properly handle devices which never
3542 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003543 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003544 SettingsState globalSettings = getGlobalSettingsLocked();
3545 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3546 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003547 }
3548
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003549 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3550 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3551 secureSettings.persistSyncLocked();
3552
3553 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3554 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3555 systemSettings.persistSyncLocked();
3556
Amin Shaikh86367962017-06-07 08:58:22 -07003557 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003558 }
3559
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003560 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003561 // Version 147: Removed. (This version previously allowed showing the
3562 // "wifi_wakeup_available" setting).
3563 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003564 currentVersion = 147;
3565 }
3566
3567 if (currentVersion == 147) {
3568 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003569 if (userId == UserHandle.USER_SYSTEM) {
3570 final SettingsState globalSettings = getGlobalSettingsLocked();
3571 final Setting currentSetting = globalSettings.getSettingLocked(
3572 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3573 if (currentSetting.isNull()) {
3574 globalSettings.insertSettingLocked(
3575 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3576 getContext().getResources().getBoolean(
3577 R.bool.def_restrict_background_data) ? "1" : "0",
3578 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3579 }
3580 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003581 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003582 }
3583
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003584 if (currentVersion == 148) {
3585 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3586 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3587 final String oldValue = systemSecureSettings.getSettingLocked(
3588 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3589 if (TextUtils.equals(null, oldValue)) {
3590 final String defaultValue = getContext().getResources().getString(
3591 R.string.def_backup_manager_constants);
3592 if (!TextUtils.isEmpty(defaultValue)) {
3593 systemSecureSettings.insertSettingLocked(
3594 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3595 true, SettingsState.SYSTEM_PACKAGE_NAME);
3596 }
3597 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003598 currentVersion = 149;
3599 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003600
3601 if (currentVersion == 149) {
3602 // Version 150: Set a default value for mobile data always on
3603 final SettingsState globalSettings = getGlobalSettingsLocked();
3604 final Setting currentSetting = globalSettings.getSettingLocked(
3605 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3606 if (currentSetting.isNull()) {
3607 globalSettings.insertSettingLocked(
3608 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3609 getContext().getResources().getBoolean(
3610 R.bool.def_mobile_data_always_on) ? "1" : "0",
3611 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3612 }
3613
3614 currentVersion = 150;
3615 }
3616
Mike Digman4af4a6f2018-01-16 14:49:38 -08003617 if (currentVersion == 150) {
3618 // Version 151: Reset rotate locked setting for upgrading users
3619 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3620 systemSettings.insertSettingLocked(
3621 Settings.System.ACCELEROMETER_ROTATION,
3622 getContext().getResources().getBoolean(
3623 R.bool.def_accelerometer_rotation) ? "1" : "0",
3624 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3625
3626 currentVersion = 151;
3627 }
3628
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003629 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003630 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3631 // by default but it is now no longer configurable).
3632 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003633 currentVersion = 152;
3634 }
3635
Joe LaPenna250d7842018-01-25 10:19:42 -08003636 if (currentVersion == 152) {
3637 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3638 currentVersion = 153;
3639 }
3640
Ben Linb4df8bc2018-01-29 11:48:20 -08003641 if (currentVersion == 153) {
3642 // Version 154: Read notification badge configuration from config.
3643 // If user has already set the value, don't do anything.
3644 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3645 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3646 Settings.Secure.NOTIFICATION_BADGING);
3647 if (showNotificationBadges.isNull()) {
3648 final boolean defaultValue = getContext().getResources().getBoolean(
3649 com.android.internal.R.bool.config_notificationBadging);
3650 systemSecureSettings.insertSettingLocked(
3651 Secure.NOTIFICATION_BADGING,
3652 defaultValue ? "1" : "0",
3653 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3654 }
3655 currentVersion = 154;
3656 }
3657
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003658 if (currentVersion == 154) {
3659 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3660 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3661 final String oldValue = systemSecureSettings.getSettingLocked(
3662 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3663 if (TextUtils.equals(null, oldValue)) {
3664 final String defaultValue = getContext().getResources().getString(
3665 R.string.def_backup_local_transport_parameters);
3666 if (!TextUtils.isEmpty(defaultValue)) {
3667 systemSecureSettings.insertSettingLocked(
3668 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3669 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3670 }
3671
3672 }
3673 currentVersion = 155;
3674 }
3675
Beverlyda904812018-03-02 09:55:30 -05003676 if (currentVersion == 155) {
3677 // Version 155: Set the default value for CHARGING_STARTED_SOUND.
3678 final SettingsState globalSettings = getGlobalSettingsLocked();
3679 final String oldValue = globalSettings.getSettingLocked(
3680 Global.CHARGING_STARTED_SOUND).getValue();
3681 final String oldDefault = getContext().getResources().getString(
3682 R.string.def_wireless_charging_started_sound);
3683 if (TextUtils.equals(null, oldValue)
3684 || TextUtils.equals(oldValue, oldDefault)) {
3685 final String defaultValue = getContext().getResources().getString(
3686 R.string.def_charging_started_sound);
3687 if (!TextUtils.isEmpty(defaultValue)) {
3688 globalSettings.insertSettingLocked(
3689 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3690 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3691 }
3692
3693 }
3694 currentVersion = 156;
3695 }
3696
3697
Felipe Lemeff355092017-04-03 12:55:02 -07003698 // vXXX: Add new settings above this point.
3699
Dan Sandler71f85e92016-07-20 13:46:05 -04003700 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003701 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003702 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003703 + currentVersion +
3704 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3705 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003706 if (DEBUG) {
3707 throw new RuntimeException("db upgrade error");
3708 }
3709 }
3710
Jeff Brown503cffc2015-03-26 18:08:51 -07003711 // Return the current version.
3712 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003713 }
3714 }
Svet Ganov13701552017-02-23 12:45:17 -08003715
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003716 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3717 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003718 List<String> names = settings.getSettingNamesLocked();
3719 final int nameCount = names.size();
3720 for (int i = 0; i < nameCount; i++) {
3721 String name = names.get(i);
3722 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003723
3724 // In the upgrade case we pretend the call is made from the app
3725 // that made the last change to the setting to properly determine
3726 // whether the call has been made by a system component.
3727 int callingUid = -1;
3728 try {
3729 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3730 } catch (RemoteException e) {
3731 /* ignore - handled below */
3732 }
3733 if (callingUid < 0) {
3734 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3735 continue;
3736 }
3737 try {
3738 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3739 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003740 if (systemSet) {
3741 settings.insertSettingLocked(name, setting.getValue(),
3742 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003743 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3744 // We had a bug where changes by non-system packages were marked
3745 // as system made and as a result set as the default. Therefore, if
3746 // the package changed the setting last is not a system one but the
3747 // setting is marked as its default coming from the system we clear
3748 // the default and clear the system set flag.
3749 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003750 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003751 } catch (IllegalStateException e) {
3752 // If the package goes over its quota during the upgrade, don't
3753 // crash but just log the error as the system does the upgrade.
3754 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3755
Svet Ganov13701552017-02-23 12:45:17 -08003756 }
3757 }
3758 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003759 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003760}