blob: 2a697b8d503485ebd3d36a84b7b9e9aebc32b201 [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;
Michal Karpinski2c37b082018-01-18 16:14:27 +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
Svetoslav Ganove080da92016-12-21 17:10:35 -0800102import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800103import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800104import 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.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001020 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001021 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.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001328 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001329 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
Makoto Onuki28da2e32015-11-20 11:30:44 -08001582 /**
1583 * Checks whether changing a setting to a value is prohibited by the corresponding user
1584 * restriction.
1585 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001586 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1587 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001588 *
1589 * @return true if the change is prohibited, false if the change is allowed.
1590 */
1591 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001592 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001593 String restriction;
1594 switch (setting) {
1595 case Settings.Secure.LOCATION_MODE:
1596 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1597 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1598 // here normally, but we still protect it here from a direct provider write.
1599 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1600 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1601 break;
1602
1603 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1604 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1605 // a provider, which should be allowed even if the user restriction is set.
1606 if (value != null && value.startsWith("-")) return false;
1607 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1608 break;
1609
1610 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1611 if ("0".equals(value)) return false;
1612 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1613 break;
1614
1615 case Settings.Global.ADB_ENABLED:
1616 if ("0".equals(value)) return false;
1617 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1618 break;
1619
1620 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1621 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1622 if ("1".equals(value)) return false;
1623 restriction = UserManager.ENSURE_VERIFY_APPS;
1624 break;
1625
1626 case Settings.Global.PREFERRED_NETWORK_MODE:
1627 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1628 break;
1629
Victor Chang9c7b7062016-07-12 23:47:29 +01001630 case Settings.Secure.ALWAYS_ON_VPN_APP:
1631 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1632 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001633 final int appId = UserHandle.getAppId(callingUid);
1634 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001635 return false;
1636 }
1637 restriction = UserManager.DISALLOW_CONFIG_VPN;
1638 break;
1639
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001640 case Settings.Global.SAFE_BOOT_DISALLOWED:
1641 if ("1".equals(value)) return false;
1642 restriction = UserManager.DISALLOW_SAFE_BOOT;
1643 break;
1644
yuemingw265c6922018-01-11 18:31:14 +00001645 case Settings.Global.AIRPLANE_MODE_ON:
1646 if ("0".equals(value)) return false;
1647 restriction = UserManager.DISALLOW_AIRPLANE_MODE;
1648 break;
1649
Makoto Onuki28da2e32015-11-20 11:30:44 -08001650 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001651 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001652 if ("0".equals(value)) return false;
1653 restriction = UserManager.DISALLOW_DATA_ROAMING;
1654 break;
1655 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001656 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001657 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001658
1659 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001660 }
1661
1662 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1663 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1664 }
1665
1666 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001667 final int parentId;
1668 // Resolves dependency if setting has a dependency and the calling user has a parent
1669 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1670 && (parentId = getGroupParentLocked(userId)) != userId) {
1671 // The setting has a dependency and the profile has a parent
1672 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001673 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1674 final long token = Binder.clearCallingIdentity();
1675 try {
1676 Setting settingObj = getSecureSetting(dependency, userId);
1677 if (settingObj != null && settingObj.getValue().equals("1")) {
1678 return parentId;
1679 }
1680 } finally {
1681 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001682 }
1683 }
Svetoslav683914b2015-01-15 14:22:26 -08001684 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1685 }
1686
1687 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1688 final int parentId = getGroupParentLocked(userId);
1689 if (parentId != userId && keys.contains(name)) {
1690 return parentId;
1691 }
1692 return userId;
1693 }
1694
Svetoslavf41334b2015-06-23 12:06:03 -07001695 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001696 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001697 // System/root/shell can mutate whatever secure settings they want.
1698 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001699 final int appId = UserHandle.getAppId(callingUid);
1700 if (appId == android.os.Process.SYSTEM_UID
1701 || appId == Process.SHELL_UID
1702 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001703 return;
1704 }
1705
1706 switch (operation) {
1707 case MUTATION_OPERATION_INSERT:
1708 // Insert updates.
1709 case MUTATION_OPERATION_UPDATE: {
1710 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1711 return;
1712 }
1713
1714 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001715 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001716
1717 // Privileged apps can do whatever they want.
1718 if ((packageInfo.applicationInfo.privateFlags
1719 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1720 return;
1721 }
1722
1723 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1724 packageInfo.applicationInfo.targetSdkVersion, name);
1725 } break;
1726
1727 case MUTATION_OPERATION_DELETE: {
1728 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1729 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1730 throw new IllegalArgumentException("You cannot delete system defined"
1731 + " secure settings.");
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 }
1748
Todd Kennedybe0b8892017-02-15 14:13:52 -08001749 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001750 switch (settingsType) {
1751 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001752 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001753 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001754 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001755 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001756 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001757 default:
1758 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1759 }
1760 }
1761
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001762 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1763 switch (settingsType) {
1764 case SETTINGS_TYPE_GLOBAL:
1765 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1766 case SETTINGS_TYPE_SYSTEM:
1767 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1768 case SETTINGS_TYPE_SECURE:
1769 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1770 default:
1771 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1772 }
1773 }
1774
Chad Brubaker97bccee2017-01-05 15:51:41 -08001775 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001776 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1777 // in the current form.
1778 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001779 }
1780
Chad Brubakera6830e72017-04-28 17:34:36 -07001781 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001782 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1783 return;
1784 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001785 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001786 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001787 return;
1788 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001789 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1790 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001791 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1792 // breakage in the current form.
1793 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1794 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001795 }
1796 }
1797
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001798 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1799 // We always use the callingUid for this lookup. This means that if hypothetically an
1800 // app was installed in user A with cross user and in user B as an Instant App
1801 // the app in A would be able to see all the settings in user B. However since cross
1802 // user is a system permission and the app must be uninstalled in B and then installed as
1803 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001804 ApplicationInfo ai = null;
1805 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001806 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1807 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001808 } catch (RemoteException ignored) {
1809 }
1810 if (ai == null) {
1811 throw new IllegalStateException("Failed to lookup info for package "
1812 + getCallingPackage());
1813 }
1814 return ai;
1815 }
1816
Xiaohui Chen43765b72015-08-31 10:57:33 -07001817 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001818 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001819 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1820 getCallingPackage(), 0, userId);
1821 if (packageInfo != null) {
1822 return packageInfo;
1823 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001824 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001825 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001826 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001827 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001828 }
1829
1830 private int getGroupParentLocked(int userId) {
1831 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001832 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001833 return userId;
1834 }
1835 // We are in the same process with the user manager and the returned
1836 // user info is a cached instance, so just look up instead of cache.
1837 final long identity = Binder.clearCallingIdentity();
1838 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001839 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001840 UserInfo userInfo = mUserManager.getProfileParent(userId);
1841 return (userInfo != null) ? userInfo.id : userId;
1842 } finally {
1843 Binder.restoreCallingIdentity(identity);
1844 }
1845 }
1846
Svetoslav683914b2015-01-15 14:22:26 -08001847 private void enforceWritePermission(String permission) {
1848 if (getContext().checkCallingOrSelfPermission(permission)
1849 != PackageManager.PERMISSION_GRANTED) {
1850 throw new SecurityException("Permission denial: writing to settings requires:"
1851 + permission);
1852 }
1853 }
1854
1855 /*
1856 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1857 * This setting contains a list of the currently enabled location providers.
1858 * But helper functions in android.providers.Settings can enable or disable
1859 * a single provider by using a "+" or "-" prefix before the provider name.
1860 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001861 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1862 * is set, the said method will only allow values with the "-" prefix.
1863 *
Svetoslav683914b2015-01-15 14:22:26 -08001864 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001865 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001866 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1867 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001868 if (TextUtils.isEmpty(value)) {
1869 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001870 }
1871
Svetoslav683914b2015-01-15 14:22:26 -08001872 final char prefix = value.charAt(0);
1873 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001874 if (forceNotify) {
1875 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1876 mSettingsRegistry.notifyForSettingsChange(key,
1877 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1878 }
Svetoslav683914b2015-01-15 14:22:26 -08001879 return false;
1880 }
1881
1882 // skip prefix
1883 value = value.substring(1);
1884
Svetoslav7ec28e82015-05-20 17:01:10 -07001885 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001886 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001887 if (settingValue == null) {
1888 return false;
1889 }
Svetoslav683914b2015-01-15 14:22:26 -08001890
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001891 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001892
1893 int index = oldProviders.indexOf(value);
1894 int end = index + value.length();
1895
1896 // check for commas to avoid matching on partial string
1897 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1898 index = -1;
1899 }
1900
1901 // check for commas to avoid matching on partial string
1902 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1903 index = -1;
1904 }
1905
1906 String newProviders;
1907
1908 if (prefix == '+' && index < 0) {
1909 // append the provider to the list if not present
1910 if (oldProviders.length() == 0) {
1911 newProviders = value;
1912 } else {
1913 newProviders = oldProviders + ',' + value;
1914 }
1915 } else if (prefix == '-' && index >= 0) {
1916 // remove the provider from the list if present
1917 // remove leading or trailing comma
1918 if (index > 0) {
1919 index--;
1920 } else if (end < oldProviders.length()) {
1921 end++;
1922 }
1923
1924 newProviders = oldProviders.substring(0, index);
1925 if (end < oldProviders.length()) {
1926 newProviders += oldProviders.substring(end);
1927 }
1928 } else {
1929 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001930 if (forceNotify) {
1931 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1932 mSettingsRegistry.notifyForSettingsChange(key,
1933 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1934 }
Svetoslav683914b2015-01-15 14:22:26 -08001935 return false;
1936 }
1937
Svet Ganov53a441c2016-04-19 19:38:00 -07001938 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001939 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001940 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001941 }
1942
Svetoslav683914b2015-01-15 14:22:26 -08001943 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1944 int targetSdkVersion, String name) {
1945 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1946 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1947 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1948 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1949 + " This will soon become an error.");
1950 } else {
1951 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1952 + " This will soon become an error.");
1953 }
1954 } else {
1955 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1956 throw new IllegalArgumentException("You cannot change private secure settings.");
1957 } else {
1958 throw new IllegalArgumentException("You cannot keep your settings in"
1959 + " the secure settings.");
1960 }
1961 }
1962 }
1963
1964 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1965 if (requestingUserId == UserHandle.getCallingUserId()) {
1966 return requestingUserId;
1967 }
1968 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1969 Binder.getCallingUid(), requestingUserId, false, true,
1970 "get/set setting for user", null);
1971 }
1972
Svet Ganov53a441c2016-04-19 19:38:00 -07001973 private Bundle packageValueForCallResult(Setting setting,
1974 boolean trackingGeneration) {
1975 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001976 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001977 return NULL_SETTING_BUNDLE;
1978 }
1979 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001980 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001981 Bundle result = new Bundle();
1982 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001983 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001984
Svetoslav Ganove080da92016-12-21 17:10:35 -08001985 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001986 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001987 }
1988
1989 private static int getRequestingUserId(Bundle args) {
1990 final int callingUserId = UserHandle.getCallingUserId();
1991 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1992 : callingUserId;
1993 }
1994
Svet Ganov53a441c2016-04-19 19:38:00 -07001995 private boolean isTrackingGeneration(Bundle args) {
1996 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1997 }
1998
Svetoslav683914b2015-01-15 14:22:26 -08001999 private static String getSettingValue(Bundle args) {
2000 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2001 }
2002
Svetoslav Ganove080da92016-12-21 17:10:35 -08002003 private static String getSettingTag(Bundle args) {
2004 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2005 }
2006
2007 private static boolean getSettingMakeDefault(Bundle args) {
2008 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2009 }
2010
2011 private static int getResetModeEnforcingPermission(Bundle args) {
2012 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2013 switch (mode) {
2014 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2015 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2016 throw new SecurityException("Only system, shell/root on a "
2017 + "debuggable build can reset to untrusted defaults");
2018 }
2019 return mode;
2020 }
2021 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2022 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2023 throw new SecurityException("Only system, shell/root on a "
2024 + "debuggable build can reset untrusted changes");
2025 }
2026 return mode;
2027 }
2028 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2029 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2030 throw new SecurityException("Only system, shell/root on a "
2031 + "debuggable build can reset to trusted defaults");
2032 }
2033 return mode;
2034 }
2035 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2036 return mode;
2037 }
2038 }
2039 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2040 }
2041
2042 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2043 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2044 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2045 && (appId == SHELL_UID || appId == ROOT_UID));
2046 }
2047
Svetoslav683914b2015-01-15 14:22:26 -08002048 private static String getValidTableOrThrow(Uri uri) {
2049 if (uri.getPathSegments().size() > 0) {
2050 String table = uri.getPathSegments().get(0);
2051 if (DatabaseHelper.isValidTable(table)) {
2052 return table;
2053 }
2054 throw new IllegalArgumentException("Bad root path: " + table);
2055 }
2056 throw new IllegalArgumentException("Invalid URI:" + uri);
2057 }
2058
2059 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002060 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002061 return new MatrixCursor(projection, 0);
2062 }
2063 MatrixCursor cursor = new MatrixCursor(projection, 1);
2064 appendSettingToCursor(cursor, setting);
2065 return cursor;
2066 }
2067
2068 private static String[] normalizeProjection(String[] projection) {
2069 if (projection == null) {
2070 return ALL_COLUMNS;
2071 }
2072
2073 final int columnCount = projection.length;
2074 for (int i = 0; i < columnCount; i++) {
2075 String column = projection[i];
2076 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2077 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002078 }
2079 }
2080
Svetoslav683914b2015-01-15 14:22:26 -08002081 return projection;
2082 }
2083
2084 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002085 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002086 return;
2087 }
Svetoslav683914b2015-01-15 14:22:26 -08002088 final int columnCount = cursor.getColumnCount();
2089
2090 String[] values = new String[columnCount];
2091
2092 for (int i = 0; i < columnCount; i++) {
2093 String column = cursor.getColumnName(i);
2094
2095 switch (column) {
2096 case Settings.NameValueTable._ID: {
2097 values[i] = setting.getId();
2098 } break;
2099
2100 case Settings.NameValueTable.NAME: {
2101 values[i] = setting.getName();
2102 } break;
2103
2104 case Settings.NameValueTable.VALUE: {
2105 values[i] = setting.getValue();
2106 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002107 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002108 }
2109
Svetoslav683914b2015-01-15 14:22:26 -08002110 cursor.addRow(values);
2111 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002112
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002113 private static boolean isKeyValid(String key) {
2114 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2115 }
2116
Svetoslav683914b2015-01-15 14:22:26 -08002117 private static final class Arguments {
2118 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2119 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2120
2121 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2122 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2123
2124 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2125 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2126
2127 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2128 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2129
2130 public final String table;
2131 public final String name;
2132
2133 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2134 final int segmentSize = uri.getPathSegments().size();
2135 switch (segmentSize) {
2136 case 1: {
2137 if (where != null
2138 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2139 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2140 && whereArgs.length == 1) {
2141 name = whereArgs[0];
2142 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002143 return;
Svetoslav683914b2015-01-15 14:22:26 -08002144 } else if (where != null
2145 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2146 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2147 final int startIndex = Math.max(where.indexOf("'"),
2148 where.indexOf("\"")) + 1;
2149 final int endIndex = Math.max(where.lastIndexOf("'"),
2150 where.lastIndexOf("\""));
2151 name = where.substring(startIndex, endIndex);
2152 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002153 return;
Svetoslav683914b2015-01-15 14:22:26 -08002154 } else if (supportAll && where == null && whereArgs == null) {
2155 name = null;
2156 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002157 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002158 }
Svetoslav683914b2015-01-15 14:22:26 -08002159 } break;
2160
Svetoslav28494652015-02-12 14:11:42 -08002161 case 2: {
2162 if (where == null && whereArgs == null) {
2163 name = uri.getPathSegments().get(1);
2164 table = computeTableForSetting(uri, name);
2165 return;
2166 }
2167 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002168 }
Svetoslav28494652015-02-12 14:11:42 -08002169
2170 EventLogTags.writeUnsupportedSettingsQuery(
2171 uri.toSafeString(), where, Arrays.toString(whereArgs));
2172 String message = String.format( "Supported SQL:\n"
2173 + " uri content://some_table/some_property with null where and where args\n"
2174 + " uri content://some_table with query name=? and single name as arg\n"
2175 + " uri content://some_table with query name=some_name and null args\n"
2176 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2177 Arrays.toString(whereArgs));
2178 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002179 }
2180
Svetoslav28494652015-02-12 14:11:42 -08002181 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002182 String table = getValidTableOrThrow(uri);
2183
2184 if (name != null) {
2185 if (sSystemMovedToSecureSettings.contains(name)) {
2186 table = TABLE_SECURE;
2187 }
2188
2189 if (sSystemMovedToGlobalSettings.contains(name)) {
2190 table = TABLE_GLOBAL;
2191 }
2192
2193 if (sSecureMovedToGlobalSettings.contains(name)) {
2194 table = TABLE_GLOBAL;
2195 }
2196
2197 if (sGlobalMovedToSecureSettings.contains(name)) {
2198 table = TABLE_SECURE;
2199 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002200 }
Svetoslav683914b2015-01-15 14:22:26 -08002201
2202 return table;
2203 }
2204 }
2205
2206 final class SettingsRegistry {
2207 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2208
Svetoslav683914b2015-01-15 14:22:26 -08002209 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2210 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2211 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002212 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2213
2214 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002215
2216 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2217
Svet Ganov53a441c2016-04-19 19:38:00 -07002218 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002219
Svetoslav7e0683b2015-08-03 16:02:52 -07002220 private final Handler mHandler;
2221
Svet Ganov53a441c2016-04-19 19:38:00 -07002222 private final BackupManager mBackupManager;
2223
Amith Yamasani39452022017-03-21 15:23:47 -07002224 private String mSettingsCreationBuildId;
2225
Svetoslav683914b2015-01-15 14:22:26 -08002226 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002227 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002228 mGenerationRegistry = new GenerationRegistry(mLock);
2229 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002230 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002231 syncSsaidTableOnStart();
2232 }
2233
2234 private void generateUserKeyLocked(int userId) {
2235 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002236 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002237 final SecureRandom rand = new SecureRandom();
2238 rand.nextBytes(keyBytes);
2239
2240 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002241 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002242
2243 // Store the key in the ssaid table.
2244 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2245 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2246 true, SettingsState.SYSTEM_PACKAGE_NAME);
2247
2248 if (!success) {
2249 throw new IllegalStateException("Ssaid settings not accessible");
2250 }
2251 }
2252
Mark Rathjen7599f132017-01-23 14:15:54 -08002253 private byte[] getLengthPrefix(byte[] data) {
2254 return ByteBuffer.allocate(4).putInt(data.length).array();
2255 }
2256
Christopher Tateb218e762017-04-05 16:34:07 -07002257 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002258 // Read the user's key from the ssaid table.
2259 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002260 if (userKeySetting == null || userKeySetting.isNull()
2261 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002262 // Lazy initialize and store the user key.
2263 generateUserKeyLocked(userId);
2264 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002265 if (userKeySetting == null || userKeySetting.isNull()
2266 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002267 throw new IllegalStateException("User key not accessible");
2268 }
2269 }
2270 final String userKey = userKeySetting.getValue();
2271
2272 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002273 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2274
2275 // Validate that the key is of expected length.
2276 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2277 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002278 throw new IllegalStateException("User key invalid");
2279 }
2280
Mark Rathjen7599f132017-01-23 14:15:54 -08002281 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002282 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002283 m = Mac.getInstance("HmacSHA256");
2284 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002285 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002286 throw new IllegalStateException("HmacSHA256 is not available", e);
2287 } catch (InvalidKeyException e) {
2288 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002289 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002290
Mark Rathjenf42dd912017-06-05 19:04:34 -07002291 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002292 for (int i = 0; i < callingPkg.signatures.length; i++) {
2293 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002294 m.update(getLengthPrefix(sig), 0, 4);
2295 m.update(sig);
2296 }
Mark Rathjend891f012017-01-19 04:10:37 +00002297
2298 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002299 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2300 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002301
2302 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002303 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002304 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2305 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002306 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002307
2308 if (!success) {
2309 throw new IllegalStateException("Ssaid settings not accessible");
2310 }
2311
2312 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2313 }
2314
2315 public void syncSsaidTableOnStart() {
2316 synchronized (mLock) {
2317 // Verify that each user's packages and ssaid's are in sync.
2318 for (UserInfo user : mUserManager.getUsers(true)) {
2319 // Get all uids for the user's packages.
2320 final List<PackageInfo> packages;
2321 try {
2322 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2323 } catch (RemoteException e) {
2324 throw new IllegalStateException("Package manager not available");
2325 }
2326 final Set<String> appUids = new HashSet<>();
2327 for (PackageInfo info : packages) {
2328 appUids.add(Integer.toString(info.applicationInfo.uid));
2329 }
2330
2331 // Get all uids currently stored in the user's ssaid table.
2332 final Set<String> ssaidUids = new HashSet<>(
2333 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2334 ssaidUids.remove(SSAID_USER_KEY);
2335
2336 // Perform a set difference for the appUids and ssaidUids.
2337 ssaidUids.removeAll(appUids);
2338
2339 // If there are ssaidUids left over they need to be removed from the table.
2340 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2341 user.id);
2342 for (String uid : ssaidUids) {
2343 ssaidSettings.deleteSettingLocked(uid);
2344 }
2345 }
2346 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002347 }
2348
Svetoslav683914b2015-01-15 14:22:26 -08002349 public List<String> getSettingsNamesLocked(int type, int userId) {
2350 final int key = makeKey(type, userId);
2351 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002352 if (settingsState == null) {
2353 return new ArrayList<String>();
2354 }
Svetoslav683914b2015-01-15 14:22:26 -08002355 return settingsState.getSettingNamesLocked();
2356 }
2357
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002358 public SparseBooleanArray getKnownUsersLocked() {
2359 SparseBooleanArray users = new SparseBooleanArray();
2360 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2361 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2362 }
2363 return users;
2364 }
2365
Kweku Adamsb0886f32017-10-31 15:32:09 -07002366 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002367 public SettingsState getSettingsLocked(int type, int userId) {
2368 final int key = makeKey(type, userId);
2369 return peekSettingsStateLocked(key);
2370 }
2371
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002372 public boolean ensureSettingsForUserLocked(int userId) {
2373 // First make sure this user actually exists.
2374 if (mUserManager.getUserInfo(userId) == null) {
2375 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2376 return false;
2377 }
2378
Svetoslav683914b2015-01-15 14:22:26 -08002379 // Migrate the setting for this user if needed.
2380 migrateLegacySettingsForUserIfNeededLocked(userId);
2381
2382 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002383 if (userId == UserHandle.USER_SYSTEM) {
2384 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002385 ensureSettingsStateLocked(globalKey);
2386 }
2387
2388 // Ensure secure settings loaded.
2389 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2390 ensureSettingsStateLocked(secureKey);
2391
2392 // Make sure the secure settings have an Android id set.
2393 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2394 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2395
2396 // Ensure system settings loaded.
2397 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2398 ensureSettingsStateLocked(systemKey);
2399
Mark Rathjend891f012017-01-19 04:10:37 +00002400 // Ensure secure settings loaded.
2401 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2402 ensureSettingsStateLocked(ssaidKey);
2403
Svetoslav683914b2015-01-15 14:22:26 -08002404 // Upgrade the settings to the latest version.
2405 UpgradeController upgrader = new UpgradeController(userId);
2406 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002407 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002408 }
2409
2410 private void ensureSettingsStateLocked(int key) {
2411 if (mSettingsStates.get(key) == null) {
2412 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002413 SettingsState settingsState = new SettingsState(getContext(), mLock,
2414 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002415 mSettingsStates.put(key, settingsState);
2416 }
2417 }
2418
2419 public void removeUserStateLocked(int userId, boolean permanently) {
2420 // We always keep the global settings in memory.
2421
2422 // Nuke system settings.
2423 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2424 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2425 if (systemSettingsState != null) {
2426 if (permanently) {
2427 mSettingsStates.remove(systemKey);
2428 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002429 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002430 systemSettingsState.destroyLocked(new Runnable() {
2431 @Override
2432 public void run() {
2433 mSettingsStates.remove(systemKey);
2434 }
2435 });
2436 }
2437 }
2438
2439 // Nuke secure settings.
2440 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2441 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2442 if (secureSettingsState != null) {
2443 if (permanently) {
2444 mSettingsStates.remove(secureKey);
2445 secureSettingsState.destroyLocked(null);
2446 } else {
2447 secureSettingsState.destroyLocked(new Runnable() {
2448 @Override
2449 public void run() {
2450 mSettingsStates.remove(secureKey);
2451 }
2452 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002453 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002454 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002455
Mark Rathjend891f012017-01-19 04:10:37 +00002456 // Nuke ssaid settings.
2457 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2458 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2459 if (ssaidSettingsState != null) {
2460 if (permanently) {
2461 mSettingsStates.remove(ssaidKey);
2462 ssaidSettingsState.destroyLocked(null);
2463 } else {
2464 ssaidSettingsState.destroyLocked(new Runnable() {
2465 @Override
2466 public void run() {
2467 mSettingsStates.remove(ssaidKey);
2468 }
2469 });
2470 }
2471 }
2472
Svet Ganov53a441c2016-04-19 19:38:00 -07002473 // Nuke generation tracking data
2474 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002475 }
2476
Svetoslav683914b2015-01-15 14:22:26 -08002477 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002478 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2479 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002480 final int key = makeKey(type, userId);
2481
Svetoslav Ganove080da92016-12-21 17:10:35 -08002482 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002483 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002484 if (settingsState != null) {
2485 success = settingsState.insertSettingLocked(name, value,
2486 tag, makeDefault, packageName);
2487 }
Svetoslav683914b2015-01-15 14:22:26 -08002488
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002489 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2490 settingsState.persistSyncLocked();
2491 }
2492
Svet Ganov53a441c2016-04-19 19:38:00 -07002493 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002494 notifyForSettingsChange(key, name);
2495 }
2496 return success;
2497 }
2498
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002499 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2500 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002501 final int key = makeKey(type, userId);
2502
Svetoslav Ganove080da92016-12-21 17:10:35 -08002503 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002504 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002505 if (settingsState != null) {
2506 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002507 }
Svetoslav683914b2015-01-15 14:22:26 -08002508
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002509 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2510 settingsState.persistSyncLocked();
2511 }
2512
Svet Ganov53a441c2016-04-19 19:38:00 -07002513 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002514 notifyForSettingsChange(key, name);
2515 }
2516 return success;
2517 }
2518
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002519 public boolean updateSettingLocked(int type, int userId, String name, String value,
2520 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2521 Set<String> criticalSettings) {
2522 final int key = makeKey(type, userId);
2523
2524 boolean success = false;
2525 SettingsState settingsState = peekSettingsStateLocked(key);
2526 if (settingsState != null) {
2527 success = settingsState.updateSettingLocked(name, value, tag,
2528 makeDefault, packageName);
2529 }
2530
2531 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2532 settingsState.persistSyncLocked();
2533 }
2534
2535 if (forceNotify || success) {
2536 notifyForSettingsChange(key, name);
2537 }
2538
2539 return success;
2540 }
2541
Svetoslav683914b2015-01-15 14:22:26 -08002542 public Setting getSettingLocked(int type, int userId, String name) {
2543 final int key = makeKey(type, userId);
2544
2545 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002546 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002547 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002548 }
Mark Rathjend891f012017-01-19 04:10:37 +00002549
2550 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002551 return settingsState.getSettingLocked(name);
2552 }
2553
Svetoslav Ganove080da92016-12-21 17:10:35 -08002554 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2555 String tag) {
2556 final int key = makeKey(type, userId);
2557 SettingsState settingsState = peekSettingsStateLocked(key);
2558 if (settingsState == null) {
2559 return;
2560 }
2561
2562 switch (mode) {
2563 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2564 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002565 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002566 Setting setting = settingsState.getSettingLocked(name);
2567 if (packageName.equals(setting.getPackageName())) {
2568 if (tag != null && !tag.equals(setting.getTag())) {
2569 continue;
2570 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002571 if (settingsState.resetSettingLocked(name)) {
2572 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002573 notifyForSettingsChange(key, name);
2574 }
2575 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002576 if (someSettingChanged) {
2577 settingsState.persistSyncLocked();
2578 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002579 }
2580 } break;
2581
2582 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2583 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002584 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002585 Setting setting = settingsState.getSettingLocked(name);
2586 if (!SettingsState.isSystemPackage(getContext(),
2587 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002588 if (settingsState.resetSettingLocked(name)) {
2589 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002590 notifyForSettingsChange(key, name);
2591 }
2592 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002593 if (someSettingChanged) {
2594 settingsState.persistSyncLocked();
2595 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002596 }
2597 } break;
2598
2599 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2600 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002601 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002602 Setting setting = settingsState.getSettingLocked(name);
2603 if (!SettingsState.isSystemPackage(getContext(),
2604 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002605 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002606 if (settingsState.resetSettingLocked(name)) {
2607 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002608 notifyForSettingsChange(key, name);
2609 }
2610 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002611 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_TRUSTED_DEFAULTS: {
2622 for (String name : settingsState.getSettingNamesLocked()) {
2623 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002624 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002625 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002626 if (settingsState.resetSettingLocked(name)) {
2627 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002628 notifyForSettingsChange(key, name);
2629 }
2630 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002631 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002632 notifyForSettingsChange(key, name);
2633 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002634 if (someSettingChanged) {
2635 settingsState.persistSyncLocked();
2636 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002637 }
2638 } break;
2639 }
2640 }
2641
Svetoslav683914b2015-01-15 14:22:26 -08002642 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002643 // Global and secure settings are signature protected. Apps signed
2644 // by the platform certificate are generally not uninstalled and
2645 // the main exception is tests. We trust components signed
2646 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002647
2648 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2649 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002650 if (systemSettings != null) {
2651 systemSettings.onPackageRemovedLocked(packageName);
2652 }
Svetoslav683914b2015-01-15 14:22:26 -08002653 }
2654
Mark Rathjend891f012017-01-19 04:10:37 +00002655 public void onUidRemovedLocked(int uid) {
2656 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2657 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002658 if (ssaidSettings != null) {
2659 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2660 }
Mark Rathjend891f012017-01-19 04:10:37 +00002661 }
2662
Kweku Adamsb0886f32017-10-31 15:32:09 -07002663 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002664 private SettingsState peekSettingsStateLocked(int key) {
2665 SettingsState settingsState = mSettingsStates.get(key);
2666 if (settingsState != null) {
2667 return settingsState;
2668 }
2669
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002670 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2671 return null;
2672 }
Svetoslav683914b2015-01-15 14:22:26 -08002673 return mSettingsStates.get(key);
2674 }
2675
2676 private void migrateAllLegacySettingsIfNeeded() {
2677 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002678 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002679 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002680 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002681 return;
2682 }
2683
Amith Yamasani39452022017-03-21 15:23:47 -07002684 mSettingsCreationBuildId = Build.ID;
2685
Svetoslav683914b2015-01-15 14:22:26 -08002686 final long identity = Binder.clearCallingIdentity();
2687 try {
2688 List<UserInfo> users = mUserManager.getUsers(true);
2689
2690 final int userCount = users.size();
2691 for (int i = 0; i < userCount; i++) {
2692 final int userId = users.get(i).id;
2693
2694 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2695 SQLiteDatabase database = dbHelper.getWritableDatabase();
2696 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2697
2698 // Upgrade to the latest version.
2699 UpgradeController upgrader = new UpgradeController(userId);
2700 upgrader.upgradeIfNeededLocked();
2701
2702 // Drop from memory if not a running user.
2703 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2704 removeUserStateLocked(userId, false);
2705 }
2706 }
2707 } finally {
2708 Binder.restoreCallingIdentity(identity);
2709 }
2710 }
2711 }
2712
2713 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2714 // Every user has secure settings and if no file we need to migrate.
2715 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2716 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002717 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002718 return;
2719 }
2720
2721 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2722 SQLiteDatabase database = dbHelper.getWritableDatabase();
2723
2724 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2725 }
2726
2727 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2728 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002729 // Move over the system settings.
2730 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2731 ensureSettingsStateLocked(systemKey);
2732 SettingsState systemSettings = mSettingsStates.get(systemKey);
2733 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2734 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002735
2736 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002737 // Do this after System settings, since this is the first thing we check when deciding
2738 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002739 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2740 ensureSettingsStateLocked(secureKey);
2741 SettingsState secureSettings = mSettingsStates.get(secureKey);
2742 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2743 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2744 secureSettings.persistSyncLocked();
2745
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002746 // Move over the global settings if owner.
2747 // Do this last, since this is the first thing we check when deciding
2748 // to skip over migration from db to xml for owner user.
2749 if (userId == UserHandle.USER_SYSTEM) {
2750 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2751 ensureSettingsStateLocked(globalKey);
2752 SettingsState globalSettings = mSettingsStates.get(globalKey);
2753 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002754 // If this was just created
2755 if (mSettingsCreationBuildId != null) {
2756 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2757 mSettingsCreationBuildId, null, true,
2758 SettingsState.SYSTEM_PACKAGE_NAME);
2759 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002760 globalSettings.persistSyncLocked();
2761 }
Svetoslav683914b2015-01-15 14:22:26 -08002762
2763 // Drop the database as now all is moved and persisted.
2764 if (DROP_DATABASE_ON_MIGRATION) {
2765 dbHelper.dropDatabase();
2766 } else {
2767 dbHelper.backupDatabase();
2768 }
2769 }
2770
2771 private void migrateLegacySettingsLocked(SettingsState settingsState,
2772 SQLiteDatabase database, String table) {
2773 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2774 queryBuilder.setTables(table);
2775
2776 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2777 null, null, null, null, null);
2778
2779 if (cursor == null) {
2780 return;
2781 }
2782
2783 try {
2784 if (!cursor.moveToFirst()) {
2785 return;
2786 }
2787
2788 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2789 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2790
2791 settingsState.setVersionLocked(database.getVersion());
2792
2793 while (!cursor.isAfterLast()) {
2794 String name = cursor.getString(nameColumnIdx);
2795 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002796 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002797 SettingsState.SYSTEM_PACKAGE_NAME);
2798 cursor.moveToNext();
2799 }
2800 } finally {
2801 cursor.close();
2802 }
2803 }
2804
2805 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2806 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2807
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002808 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002809 return;
2810 }
2811
2812 final int userId = getUserIdFromKey(secureSettings.mKey);
2813
2814 final UserInfo user;
2815 final long identity = Binder.clearCallingIdentity();
2816 try {
2817 user = mUserManager.getUserInfo(userId);
2818 } finally {
2819 Binder.restoreCallingIdentity(identity);
2820 }
2821 if (user == null) {
2822 // Can happen due to races when deleting users - treat as benign.
2823 return;
2824 }
2825
2826 String androidId = Long.toHexString(new SecureRandom().nextLong());
2827 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002828 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002829
2830 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2831 + "] for user " + userId);
2832
2833 // Write a drop box entry if it's a restricted profile
2834 if (user.isRestricted()) {
2835 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2836 Context.DROPBOX_SERVICE);
2837 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2838 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2839 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2840 }
2841 }
2842 }
2843
2844 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002845 final int userId = getUserIdFromKey(key);
2846 Uri uri = getNotificationUriFor(key, name);
2847
Phil Weaver83fec002016-05-11 10:55:29 -07002848 mGenerationRegistry.incrementGeneration(key);
2849
Svetoslav7e0683b2015-08-03 16:02:52 -07002850 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2851 userId, 0, uri).sendToTarget();
2852
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002853 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002854 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2855 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002856 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2857 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002858 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002859 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2860 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002861 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002862
Svet Ganov53a441c2016-04-19 19:38:00 -07002863 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Makoto Onuki0000d322017-11-28 16:31:47 -08002864
2865 // When the global kill switch is updated, send the change notification for
2866 // the location setting.
2867 if (isGlobalSettingsKey(key) && Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2868 notifyLocationChangeForRunningUsers();
2869 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002870 }
2871
Svet Ganov53a441c2016-04-19 19:38:00 -07002872 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002873 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002874 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002875 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002876 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002877 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002878 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002879 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002880 final int key = makeKey(type, profileId);
2881 mGenerationRegistry.incrementGeneration(key);
2882
2883 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002884 }
2885 }
2886 }
Svetoslav683914b2015-01-15 14:22:26 -08002887 }
2888
Makoto Onuki0000d322017-11-28 16:31:47 -08002889 private void notifyLocationChangeForRunningUsers() {
2890 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2891
2892 for (int i = 0; i < users.size(); i++) {
2893 final int userId = users.get(i).id;
2894
2895 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2896 continue;
2897 }
2898
2899 final int key = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2900 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
2901
2902 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2903 userId, 0, uri).sendToTarget();
2904 }
2905 }
2906
Svetoslav683914b2015-01-15 14:22:26 -08002907 private boolean isGlobalSettingsKey(int key) {
2908 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2909 }
2910
2911 private boolean isSystemSettingsKey(int key) {
2912 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2913 }
2914
2915 private boolean isSecureSettingsKey(int key) {
2916 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2917 }
2918
Mark Rathjend891f012017-01-19 04:10:37 +00002919 private boolean isSsaidSettingsKey(int key) {
2920 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2921 }
2922
Svetoslav683914b2015-01-15 14:22:26 -08002923 private File getSettingsFile(int key) {
2924 if (isGlobalSettingsKey(key)) {
2925 final int userId = getUserIdFromKey(key);
2926 return new File(Environment.getUserSystemDirectory(userId),
2927 SETTINGS_FILE_GLOBAL);
2928 } else if (isSystemSettingsKey(key)) {
2929 final int userId = getUserIdFromKey(key);
2930 return new File(Environment.getUserSystemDirectory(userId),
2931 SETTINGS_FILE_SYSTEM);
2932 } else if (isSecureSettingsKey(key)) {
2933 final int userId = getUserIdFromKey(key);
2934 return new File(Environment.getUserSystemDirectory(userId),
2935 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002936 } else if (isSsaidSettingsKey(key)) {
2937 final int userId = getUserIdFromKey(key);
2938 return new File(Environment.getUserSystemDirectory(userId),
2939 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002940 } else {
2941 throw new IllegalArgumentException("Invalid settings key:" + key);
2942 }
2943 }
2944
2945 private Uri getNotificationUriFor(int key, String name) {
2946 if (isGlobalSettingsKey(key)) {
2947 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2948 : Settings.Global.CONTENT_URI;
2949 } else if (isSecureSettingsKey(key)) {
2950 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2951 : Settings.Secure.CONTENT_URI;
2952 } else if (isSystemSettingsKey(key)) {
2953 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2954 : Settings.System.CONTENT_URI;
2955 } else {
2956 throw new IllegalArgumentException("Invalid settings key:" + key);
2957 }
2958 }
2959
2960 private int getMaxBytesPerPackageForType(int type) {
2961 switch (type) {
2962 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002963 case SETTINGS_TYPE_SECURE:
2964 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002965 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2966 }
2967
2968 default: {
2969 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2970 }
2971 }
2972 }
2973
Svetoslav7e0683b2015-08-03 16:02:52 -07002974 private final class MyHandler extends Handler {
2975 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2976 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2977
2978 public MyHandler(Looper looper) {
2979 super(looper);
2980 }
2981
2982 @Override
2983 public void handleMessage(Message msg) {
2984 switch (msg.what) {
2985 case MSG_NOTIFY_URI_CHANGED: {
2986 final int userId = msg.arg1;
2987 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002988 try {
2989 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2990 } catch (SecurityException e) {
2991 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2992 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002993 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002994 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2995 }
2996 } break;
2997
2998 case MSG_NOTIFY_DATA_CHANGED: {
2999 mBackupManager.dataChanged();
3000 } break;
3001 }
3002 }
3003 }
3004
Svetoslav683914b2015-01-15 14:22:26 -08003005 private final class UpgradeController {
Mike Digman4af4a6f2018-01-16 14:49:38 -08003006 private static final int SETTINGS_VERSION = 151;
Svetoslav683914b2015-01-15 14:22:26 -08003007
3008 private final int mUserId;
3009
3010 public UpgradeController(int userId) {
3011 mUserId = userId;
3012 }
3013
3014 public void upgradeIfNeededLocked() {
3015 // The version of all settings for a user is the same (all users have secure).
3016 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003017 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003018
3019 // Try an update from the current state.
3020 final int oldVersion = secureSettings.getVersionLocked();
3021 final int newVersion = SETTINGS_VERSION;
3022
Svet Ganovc9755bc2015-03-28 13:21:22 -07003023 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003024 if (oldVersion == newVersion) {
3025 return;
3026 }
3027
3028 // Try to upgrade.
3029 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3030
3031 // If upgrade failed start from scratch and upgrade.
3032 if (curVersion != newVersion) {
3033 // Drop state we have for this user.
3034 removeUserStateLocked(mUserId, true);
3035
3036 // Recreate the database.
3037 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3038 SQLiteDatabase database = dbHelper.getWritableDatabase();
3039 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3040
3041 // Migrate the settings for this user.
3042 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3043
3044 // Now upgrade should work fine.
3045 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003046
3047 // Make a note what happened, so we don't wonder why data was lost
3048 String reason = "Settings rebuilt! Current version: "
3049 + curVersion + " while expected: " + newVersion;
3050 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003051 Settings.Global.DATABASE_DOWNGRADE_REASON,
3052 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003053 }
3054
3055 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003056 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003057 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003058 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003059 globalSettings.setVersionLocked(newVersion);
3060 }
3061
3062 // Set the secure settings version.
3063 secureSettings.setVersionLocked(newVersion);
3064
3065 // Set the system settings version.
3066 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003067 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003068 systemSettings.setVersionLocked(newVersion);
3069 }
3070
3071 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003072 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003073 }
3074
3075 private SettingsState getSecureSettingsLocked(int userId) {
3076 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3077 }
3078
Mark Rathjend891f012017-01-19 04:10:37 +00003079 private SettingsState getSsaidSettingsLocked(int userId) {
3080 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3081 }
3082
Svetoslav683914b2015-01-15 14:22:26 -08003083 private SettingsState getSystemSettingsLocked(int userId) {
3084 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3085 }
3086
Jeff Brown503cffc2015-03-26 18:08:51 -07003087 /**
3088 * You must perform all necessary mutations to bring the settings
3089 * for this user from the old to the new version. When you add a new
3090 * upgrade step you *must* update SETTINGS_VERSION.
3091 *
3092 * This is an example of moving a setting from secure to global.
3093 *
3094 * // v119: Example settings changes.
3095 * if (currentVersion == 118) {
3096 * if (userId == UserHandle.USER_OWNER) {
3097 * // Remove from the secure settings.
3098 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3099 * String name = "example_setting_to_move";
3100 * String value = secureSettings.getSetting(name);
3101 * secureSettings.deleteSetting(name);
3102 *
3103 * // Add to the global settings.
3104 * SettingsState globalSettings = getGlobalSettingsLocked();
3105 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3106 * }
3107 *
3108 * // Update the current version.
3109 * currentVersion = 119;
3110 * }
3111 */
Svetoslav683914b2015-01-15 14:22:26 -08003112 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3113 if (DEBUG) {
3114 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3115 + oldVersion + " to version: " + newVersion);
3116 }
3117
Jeff Brown503cffc2015-03-26 18:08:51 -07003118 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003119
John Spurlocke11ae112015-05-11 16:09:03 -04003120 // v119: Reset zen + ringer mode.
3121 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003122 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003123 final SettingsState globalSettings = getGlobalSettingsLocked();
3124 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003125 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3126 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003127 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003128 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3129 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003130 }
3131 currentVersion = 119;
3132 }
3133
Jason Monk27bbb2d2015-03-31 16:46:39 -04003134 // v120: Add double tap to wake setting.
3135 if (currentVersion == 119) {
3136 SettingsState secureSettings = getSecureSettingsLocked(userId);
3137 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3138 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003139 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003140 SettingsState.SYSTEM_PACKAGE_NAME);
3141
3142 currentVersion = 120;
3143 }
3144
Svetoslav7e0683b2015-08-03 16:02:52 -07003145 if (currentVersion == 120) {
3146 // Before 121, we used a different string encoding logic. We just bump the
3147 // version here; SettingsState knows how to handle pre-version 120 files.
3148 currentVersion = 121;
3149 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003150
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003151 if (currentVersion == 121) {
3152 // Version 122: allow OEMs to set a default payment component in resources.
3153 // Note that we only write the default if no default has been set;
3154 // if there is, we just leave the default at whatever it currently is.
3155 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3156 String defaultComponent = (getContext().getResources().getString(
3157 R.string.def_nfc_payment_component));
3158 Setting currentSetting = secureSettings.getSettingLocked(
3159 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3160 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003161 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003162 secureSettings.insertSettingLocked(
3163 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003164 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003165 }
3166 currentVersion = 122;
3167 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003168
3169 if (currentVersion == 122) {
3170 // Version 123: Adding a default value for the ability to add a user from
3171 // the lock screen.
3172 if (userId == UserHandle.USER_SYSTEM) {
3173 final SettingsState globalSettings = getGlobalSettingsLocked();
3174 Setting currentSetting = globalSettings.getSettingLocked(
3175 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003176 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003177 globalSettings.insertSettingLocked(
3178 Settings.Global.ADD_USERS_WHEN_LOCKED,
3179 getContext().getResources().getBoolean(
3180 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003181 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003182 }
3183 }
3184 currentVersion = 123;
3185 }
Bryce Leebd179282015-12-17 19:01:37 -08003186
3187 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003188 final SettingsState globalSettings = getGlobalSettingsLocked();
3189 String defaultDisabledProfiles = (getContext().getResources().getString(
3190 R.string.def_bluetooth_disabled_profiles));
3191 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003192 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003193 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003194 }
3195
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003196 if (currentVersion == 124) {
3197 // Version 124: allow OEMs to set a default value for whether IME should be
3198 // shown when a physical keyboard is connected.
3199 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3200 Setting currentSetting = secureSettings.getSettingLocked(
3201 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003202 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003203 secureSettings.insertSettingLocked(
3204 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3205 getContext().getResources().getBoolean(
3206 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003207 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003208 }
3209 currentVersion = 125;
3210 }
3211
Ruben Brunk98576cf2016-03-07 18:54:28 -08003212 if (currentVersion == 125) {
3213 // Version 125: Allow OEMs to set the default VR service.
3214 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3215
3216 Setting currentSetting = secureSettings.getSettingLocked(
3217 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003218 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003219 ArraySet<ComponentName> l =
3220 SystemConfig.getInstance().getDefaultVrComponents();
3221
3222 if (l != null && !l.isEmpty()) {
3223 StringBuilder b = new StringBuilder();
3224 boolean start = true;
3225 for (ComponentName c : l) {
3226 if (!start) {
3227 b.append(':');
3228 }
3229 b.append(c.flattenToString());
3230 start = false;
3231 }
3232 secureSettings.insertSettingLocked(
3233 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003234 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003235 }
3236
3237 }
3238 currentVersion = 126;
3239 }
3240
Daniel U02ba6122016-04-01 18:41:42 +01003241 if (currentVersion == 126) {
3242 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3243 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3244 if (mUserManager.isManagedProfile(userId)) {
3245 final SettingsState systemSecureSettings =
3246 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3247
3248 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3249 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003250 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003251 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3252 secureSettings.insertSettingLocked(
3253 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003254 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003255 SettingsState.SYSTEM_PACKAGE_NAME);
3256 }
3257
3258 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3259 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003260 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003261 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3262 secureSettings.insertSettingLocked(
3263 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003264 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003265 SettingsState.SYSTEM_PACKAGE_NAME);
3266 }
3267 }
3268 currentVersion = 127;
3269 }
3270
Steven Ngdc20ba62016-04-26 18:19:04 +01003271 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003272 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003273 currentVersion = 128;
3274 }
3275
Julia Reynolds1f721e12016-07-11 08:50:58 -04003276 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003277 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003278 currentVersion = 129;
3279 }
3280
Dan Sandler71f85e92016-07-20 13:46:05 -04003281 if (currentVersion == 129) {
3282 // default longpress timeout changed from 500 to 400. If unchanged from the old
3283 // default, update to the new default.
3284 final SettingsState systemSecureSettings =
3285 getSecureSettingsLocked(userId);
3286 final String oldValue = systemSecureSettings.getSettingLocked(
3287 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3288 if (TextUtils.equals("500", oldValue)) {
3289 systemSecureSettings.insertSettingLocked(
3290 Settings.Secure.LONG_PRESS_TIMEOUT,
3291 String.valueOf(getContext().getResources().getInteger(
3292 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003293 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003294 }
3295 currentVersion = 130;
3296 }
3297
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003298 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003299 // Split Ambient settings
3300 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3301 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3302 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3303
3304 if (dozeExplicitlyDisabled) {
3305 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003306 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003307 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003308 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003309 }
3310 currentVersion = 131;
3311 }
3312
3313 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003314 // Initialize new multi-press timeout to default value
3315 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3316 final String oldValue = systemSecureSettings.getSettingLocked(
3317 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3318 if (TextUtils.equals(null, oldValue)) {
3319 systemSecureSettings.insertSettingLocked(
3320 Settings.Secure.MULTI_PRESS_TIMEOUT,
3321 String.valueOf(getContext().getResources().getInteger(
3322 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003323 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003324 }
3325
Adrian Roos69741a22016-10-21 14:49:17 -07003326 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003327 }
3328
Adrian Roos69741a22016-10-21 14:49:17 -07003329 if (currentVersion == 132) {
3330 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003331 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3332 String defaultSyncParentSounds = (getContext().getResources()
3333 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3334 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003335 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3336 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003337 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003338 }
3339
Adrian Roos69741a22016-10-21 14:49:17 -07003340 if (currentVersion == 133) {
3341 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003342 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3343 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3344 null) {
3345 String defaultEndButtonBehavior = Integer.toString(getContext()
3346 .getResources().getInteger(R.integer.def_end_button_behavior));
3347 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003348 defaultEndButtonBehavior, null, true,
3349 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003350 }
Adrian Roos69741a22016-10-21 14:49:17 -07003351 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003352 }
3353
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003354 if (currentVersion == 134) {
3355 // Remove setting that specifies if magnification values should be preserved.
3356 // This setting defaulted to true and never has a UI.
3357 getSecureSettingsLocked(userId).deleteSettingLocked(
3358 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3359 currentVersion = 135;
3360 }
3361
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003362 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003363 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003364 currentVersion = 136;
3365 }
3366
Mark Rathjend891f012017-01-19 04:10:37 +00003367 if (currentVersion == 136) {
3368 // Version 136: Store legacy SSAID for all apps currently installed on the
3369 // device as first step in migrating SSAID to be unique per application.
3370
3371 final boolean isUpgrade;
3372 try {
3373 isUpgrade = mPackageManager.isUpgrade();
3374 } catch (RemoteException e) {
3375 throw new IllegalStateException("Package manager not available");
3376 }
3377 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3378 // user data or first boot on a new device should use new ssaid generation.
3379 if (isUpgrade) {
3380 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003381 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3382 userId, Settings.Secure.ANDROID_ID);
3383 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3384 || legacySsaidSetting.getValue() == null) {
3385 throw new IllegalStateException("Legacy ssaid not accessible");
3386 }
3387 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003388
3389 // Fill each uid with the legacy ssaid to be backwards compatible.
3390 final List<PackageInfo> packages;
3391 try {
3392 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3393 } catch (RemoteException e) {
3394 throw new IllegalStateException("Package manager not available");
3395 }
3396
3397 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3398 for (PackageInfo info : packages) {
3399 // Check if the UID already has an entry in the table.
3400 final String uid = Integer.toString(info.applicationInfo.uid);
3401 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3402
3403 if (ssaid.isNull() || ssaid.getValue() == null) {
3404 // Android Id doesn't exist for this package so create it.
3405 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3406 info.packageName);
3407 }
3408 }
3409 }
3410
3411 currentVersion = 137;
3412 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003413 if (currentVersion == 137) {
3414 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3415 // default value set to 1. The user can no longer change the value of this
3416 // setting through the UI.
3417 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3418 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003419 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3420 && secureSetting.getSettingLocked(
3421 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3422
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003423 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3424 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003425 // For managed profiles with profile owners, DevicePolicyManagerService
3426 // may want to set the user restriction in this case
3427 secureSetting.insertSettingLocked(
3428 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3429 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003430 }
3431 currentVersion = 138;
3432 }
Mark Rathjend891f012017-01-19 04:10:37 +00003433
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003434 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003435 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003436 currentVersion = 139;
3437 }
3438
Phil Weaver385912e2017-02-10 10:06:56 -08003439 if (currentVersion == 139) {
3440 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3441 // the user can no longer change the value of this setting through the UI.
3442 // Force to true.
3443 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3444 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3445 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3446 currentVersion = 140;
3447 }
3448
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003449 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003450 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003451 currentVersion = 141;
3452 }
3453
Svet Ganov13701552017-02-23 12:45:17 -08003454 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003455 // This implementation was incorrectly setting the current value of
3456 // settings changed by non-system packages as the default which default
3457 // is set by the system. We add a new upgrade step at the end to properly
3458 // handle this case which would also fix incorrect changes made by the
3459 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003460 currentVersion = 142;
3461 }
3462
Stephen Chen5d0922f2017-03-27 10:28:04 -07003463 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003464 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003465 if (userId == UserHandle.USER_SYSTEM) {
3466 final SettingsState globalSettings = getGlobalSettingsLocked();
3467 Setting currentSetting = globalSettings.getSettingLocked(
3468 Settings.Global.WIFI_WAKEUP_ENABLED);
3469 if (currentSetting.isNull()) {
3470 globalSettings.insertSettingLocked(
3471 Settings.Global.WIFI_WAKEUP_ENABLED,
3472 getContext().getResources().getBoolean(
3473 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3474 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3475 }
3476 }
3477
3478 currentVersion = 143;
3479 }
3480
Felipe Lemeff355092017-04-03 12:55:02 -07003481 if (currentVersion == 143) {
3482 // Version 144: Set a default value for Autofill service.
3483 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3484 final Setting currentSetting = secureSettings
3485 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3486 if (currentSetting.isNull()) {
3487 final String defaultValue = getContext().getResources().getString(
3488 com.android.internal.R.string.config_defaultAutofillService);
3489 if (defaultValue != null) {
3490 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3491 + "for user " + userId);
3492 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3493 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3494 }
3495 }
3496
3497 currentVersion = 144;
3498 }
3499
Jeremy Joslin45caa252017-05-04 11:22:46 -07003500 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003501 // Version 145: Removed
3502 currentVersion = 145;
3503 }
3504
3505 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003506 // Version 146: In step 142 we had a bug where incorrectly
3507 // some settings were considered system set and as a result
3508 // made the default and marked as the default being set by
3509 // the system. Here reevaluate the default and default system
3510 // set flags. This would both fix corruption by the old impl
3511 // of step 142 and also properly handle devices which never
3512 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003513 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003514 SettingsState globalSettings = getGlobalSettingsLocked();
3515 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3516 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003517 }
3518
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003519 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3520 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3521 secureSettings.persistSyncLocked();
3522
3523 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3524 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3525 systemSettings.persistSyncLocked();
3526
Amin Shaikh86367962017-06-07 08:58:22 -07003527 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003528 }
3529
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003530 if (currentVersion == 146) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003531 // Version 147: Set the default value for WIFI_WAKEUP_AVAILABLE.
3532 if (userId == UserHandle.USER_SYSTEM) {
3533 final SettingsState globalSettings = getGlobalSettingsLocked();
3534 final Setting currentSetting = globalSettings.getSettingLocked(
3535 Settings.Global.WIFI_WAKEUP_AVAILABLE);
3536 if (currentSetting.getValue() == null) {
3537 final int defaultValue = getContext().getResources().getInteger(
3538 com.android.internal.R.integer.config_wifi_wakeup_available);
3539 globalSettings.insertSettingLocked(
3540 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3541 String.valueOf(defaultValue),
3542 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3543 }
3544 }
3545
3546 currentVersion = 147;
3547 }
3548
3549 if (currentVersion == 147) {
3550 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003551 if (userId == UserHandle.USER_SYSTEM) {
3552 final SettingsState globalSettings = getGlobalSettingsLocked();
3553 final Setting currentSetting = globalSettings.getSettingLocked(
3554 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3555 if (currentSetting.isNull()) {
3556 globalSettings.insertSettingLocked(
3557 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3558 getContext().getResources().getBoolean(
3559 R.bool.def_restrict_background_data) ? "1" : "0",
3560 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3561 }
3562 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003563 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003564 }
3565
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003566 if (currentVersion == 148) {
3567 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3568 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3569 final String oldValue = systemSecureSettings.getSettingLocked(
3570 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3571 if (TextUtils.equals(null, oldValue)) {
3572 final String defaultValue = getContext().getResources().getString(
3573 R.string.def_backup_manager_constants);
3574 if (!TextUtils.isEmpty(defaultValue)) {
3575 systemSecureSettings.insertSettingLocked(
3576 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3577 true, SettingsState.SYSTEM_PACKAGE_NAME);
3578 }
3579 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003580 currentVersion = 149;
3581 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003582
3583 if (currentVersion == 149) {
3584 // Version 150: Set a default value for mobile data always on
3585 final SettingsState globalSettings = getGlobalSettingsLocked();
3586 final Setting currentSetting = globalSettings.getSettingLocked(
3587 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3588 if (currentSetting.isNull()) {
3589 globalSettings.insertSettingLocked(
3590 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3591 getContext().getResources().getBoolean(
3592 R.bool.def_mobile_data_always_on) ? "1" : "0",
3593 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3594 }
3595
3596 currentVersion = 150;
3597 }
3598
Mike Digman4af4a6f2018-01-16 14:49:38 -08003599 if (currentVersion == 150) {
3600 // Version 151: Reset rotate locked setting for upgrading users
3601 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3602 systemSettings.insertSettingLocked(
3603 Settings.System.ACCELEROMETER_ROTATION,
3604 getContext().getResources().getBoolean(
3605 R.bool.def_accelerometer_rotation) ? "1" : "0",
3606 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3607
3608 currentVersion = 151;
3609 }
3610
Felipe Lemeff355092017-04-03 12:55:02 -07003611 // vXXX: Add new settings above this point.
3612
Dan Sandler71f85e92016-07-20 13:46:05 -04003613 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003614 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003615 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003616 + currentVersion +
3617 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3618 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003619 if (DEBUG) {
3620 throw new RuntimeException("db upgrade error");
3621 }
3622 }
3623
Jeff Brown503cffc2015-03-26 18:08:51 -07003624 // Return the current version.
3625 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003626 }
3627 }
Svet Ganov13701552017-02-23 12:45:17 -08003628
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003629 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3630 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003631 List<String> names = settings.getSettingNamesLocked();
3632 final int nameCount = names.size();
3633 for (int i = 0; i < nameCount; i++) {
3634 String name = names.get(i);
3635 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003636
3637 // In the upgrade case we pretend the call is made from the app
3638 // that made the last change to the setting to properly determine
3639 // whether the call has been made by a system component.
3640 int callingUid = -1;
3641 try {
3642 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3643 } catch (RemoteException e) {
3644 /* ignore - handled below */
3645 }
3646 if (callingUid < 0) {
3647 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3648 continue;
3649 }
3650 try {
3651 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3652 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003653 if (systemSet) {
3654 settings.insertSettingLocked(name, setting.getValue(),
3655 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003656 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3657 // We had a bug where changes by non-system packages were marked
3658 // as system made and as a result set as the default. Therefore, if
3659 // the package changed the setting last is not a system one but the
3660 // setting is marked as its default coming from the system we clear
3661 // the default and clear the system set flag.
3662 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003663 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003664 } catch (IllegalStateException e) {
3665 // If the package goes over its quota during the upgrade, don't
3666 // crash but just log the error as the system does the upgrade.
3667 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3668
Svet Ganov13701552017-02-23 12:45:17 -08003669 }
3670 }
3671 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003672 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003673}