blob: d1459bba90c132c7be505d1e41b9831abcbb9c73 [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
yuemingwc0109512018-01-21 19:21:27 +00001650 case Settings.Secure.DOZE_ENABLED:
1651 case Settings.Secure.DOZE_ALWAYS_ON:
1652 case Settings.Secure.DOZE_PULSE_ON_PICK_UP:
1653 case Settings.Secure.DOZE_PULSE_ON_LONG_PRESS:
1654 case Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP:
1655 if ("0".equals(value)) return false;
1656 restriction = UserManager.DISALLOW_AMBIENT_DISPLAY;
1657 break;
1658
Makoto Onuki28da2e32015-11-20 11:30:44 -08001659 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001660 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001661 if ("0".equals(value)) return false;
1662 restriction = UserManager.DISALLOW_DATA_ROAMING;
1663 break;
1664 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001665 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001666 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001667
1668 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001669 }
1670
1671 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1672 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1673 }
1674
1675 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001676 final int parentId;
1677 // Resolves dependency if setting has a dependency and the calling user has a parent
1678 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1679 && (parentId = getGroupParentLocked(userId)) != userId) {
1680 // The setting has a dependency and the profile has a parent
1681 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001682 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1683 final long token = Binder.clearCallingIdentity();
1684 try {
1685 Setting settingObj = getSecureSetting(dependency, userId);
1686 if (settingObj != null && settingObj.getValue().equals("1")) {
1687 return parentId;
1688 }
1689 } finally {
1690 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001691 }
1692 }
Svetoslav683914b2015-01-15 14:22:26 -08001693 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1694 }
1695
1696 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1697 final int parentId = getGroupParentLocked(userId);
1698 if (parentId != userId && keys.contains(name)) {
1699 return parentId;
1700 }
1701 return userId;
1702 }
1703
Svetoslavf41334b2015-06-23 12:06:03 -07001704 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001705 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001706 // System/root/shell can mutate whatever secure settings they want.
1707 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001708 final int appId = UserHandle.getAppId(callingUid);
1709 if (appId == android.os.Process.SYSTEM_UID
1710 || appId == Process.SHELL_UID
1711 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001712 return;
1713 }
1714
1715 switch (operation) {
1716 case MUTATION_OPERATION_INSERT:
1717 // Insert updates.
1718 case MUTATION_OPERATION_UPDATE: {
1719 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1720 return;
1721 }
1722
1723 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001724 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001725
1726 // Privileged apps can do whatever they want.
1727 if ((packageInfo.applicationInfo.privateFlags
1728 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1729 return;
1730 }
1731
1732 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1733 packageInfo.applicationInfo.targetSdkVersion, name);
1734 } break;
1735
1736 case MUTATION_OPERATION_DELETE: {
1737 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1738 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1739 throw new IllegalArgumentException("You cannot delete system defined"
1740 + " secure settings.");
1741 }
1742
1743 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001744 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001745
1746 // Privileged apps can do whatever they want.
1747 if ((packageInfo.applicationInfo.privateFlags &
1748 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1749 return;
1750 }
1751
1752 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1753 packageInfo.applicationInfo.targetSdkVersion, name);
1754 } break;
1755 }
1756 }
1757
Todd Kennedybe0b8892017-02-15 14:13:52 -08001758 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001759 switch (settingsType) {
1760 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001761 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001762 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001763 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001764 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001765 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001766 default:
1767 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1768 }
1769 }
1770
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001771 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1772 switch (settingsType) {
1773 case SETTINGS_TYPE_GLOBAL:
1774 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1775 case SETTINGS_TYPE_SYSTEM:
1776 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1777 case SETTINGS_TYPE_SECURE:
1778 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1779 default:
1780 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1781 }
1782 }
1783
Chad Brubaker97bccee2017-01-05 15:51:41 -08001784 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001785 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1786 // in the current form.
1787 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001788 }
1789
Chad Brubakera6830e72017-04-28 17:34:36 -07001790 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001791 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1792 return;
1793 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001794 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001795 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001796 return;
1797 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001798 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1799 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001800 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1801 // breakage in the current form.
1802 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1803 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001804 }
1805 }
1806
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001807 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1808 // We always use the callingUid for this lookup. This means that if hypothetically an
1809 // app was installed in user A with cross user and in user B as an Instant App
1810 // the app in A would be able to see all the settings in user B. However since cross
1811 // user is a system permission and the app must be uninstalled in B and then installed as
1812 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001813 ApplicationInfo ai = null;
1814 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001815 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1816 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001817 } catch (RemoteException ignored) {
1818 }
1819 if (ai == null) {
1820 throw new IllegalStateException("Failed to lookup info for package "
1821 + getCallingPackage());
1822 }
1823 return ai;
1824 }
1825
Xiaohui Chen43765b72015-08-31 10:57:33 -07001826 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001827 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001828 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1829 getCallingPackage(), 0, userId);
1830 if (packageInfo != null) {
1831 return packageInfo;
1832 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001833 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001834 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001835 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001836 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001837 }
1838
1839 private int getGroupParentLocked(int userId) {
1840 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001841 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001842 return userId;
1843 }
1844 // We are in the same process with the user manager and the returned
1845 // user info is a cached instance, so just look up instead of cache.
1846 final long identity = Binder.clearCallingIdentity();
1847 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001848 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001849 UserInfo userInfo = mUserManager.getProfileParent(userId);
1850 return (userInfo != null) ? userInfo.id : userId;
1851 } finally {
1852 Binder.restoreCallingIdentity(identity);
1853 }
1854 }
1855
Svetoslav683914b2015-01-15 14:22:26 -08001856 private void enforceWritePermission(String permission) {
1857 if (getContext().checkCallingOrSelfPermission(permission)
1858 != PackageManager.PERMISSION_GRANTED) {
1859 throw new SecurityException("Permission denial: writing to settings requires:"
1860 + permission);
1861 }
1862 }
1863
1864 /*
1865 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1866 * This setting contains a list of the currently enabled location providers.
1867 * But helper functions in android.providers.Settings can enable or disable
1868 * a single provider by using a "+" or "-" prefix before the provider name.
1869 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001870 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1871 * is set, the said method will only allow values with the "-" prefix.
1872 *
Svetoslav683914b2015-01-15 14:22:26 -08001873 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001874 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001875 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1876 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001877 if (TextUtils.isEmpty(value)) {
1878 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001879 }
1880
Svetoslav683914b2015-01-15 14:22:26 -08001881 final char prefix = value.charAt(0);
1882 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001883 if (forceNotify) {
1884 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1885 mSettingsRegistry.notifyForSettingsChange(key,
1886 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1887 }
Svetoslav683914b2015-01-15 14:22:26 -08001888 return false;
1889 }
1890
1891 // skip prefix
1892 value = value.substring(1);
1893
Svetoslav7ec28e82015-05-20 17:01:10 -07001894 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001895 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001896 if (settingValue == null) {
1897 return false;
1898 }
Svetoslav683914b2015-01-15 14:22:26 -08001899
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001900 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001901
1902 int index = oldProviders.indexOf(value);
1903 int end = index + value.length();
1904
1905 // check for commas to avoid matching on partial string
1906 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1907 index = -1;
1908 }
1909
1910 // check for commas to avoid matching on partial string
1911 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1912 index = -1;
1913 }
1914
1915 String newProviders;
1916
1917 if (prefix == '+' && index < 0) {
1918 // append the provider to the list if not present
1919 if (oldProviders.length() == 0) {
1920 newProviders = value;
1921 } else {
1922 newProviders = oldProviders + ',' + value;
1923 }
1924 } else if (prefix == '-' && index >= 0) {
1925 // remove the provider from the list if present
1926 // remove leading or trailing comma
1927 if (index > 0) {
1928 index--;
1929 } else if (end < oldProviders.length()) {
1930 end++;
1931 }
1932
1933 newProviders = oldProviders.substring(0, index);
1934 if (end < oldProviders.length()) {
1935 newProviders += oldProviders.substring(end);
1936 }
1937 } else {
1938 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001939 if (forceNotify) {
1940 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1941 mSettingsRegistry.notifyForSettingsChange(key,
1942 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1943 }
Svetoslav683914b2015-01-15 14:22:26 -08001944 return false;
1945 }
1946
Svet Ganov53a441c2016-04-19 19:38:00 -07001947 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001948 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001949 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001950 }
1951
Svetoslav683914b2015-01-15 14:22:26 -08001952 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1953 int targetSdkVersion, String name) {
1954 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1955 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1956 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1957 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1958 + " This will soon become an error.");
1959 } else {
1960 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1961 + " This will soon become an error.");
1962 }
1963 } else {
1964 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1965 throw new IllegalArgumentException("You cannot change private secure settings.");
1966 } else {
1967 throw new IllegalArgumentException("You cannot keep your settings in"
1968 + " the secure settings.");
1969 }
1970 }
1971 }
1972
1973 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1974 if (requestingUserId == UserHandle.getCallingUserId()) {
1975 return requestingUserId;
1976 }
1977 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1978 Binder.getCallingUid(), requestingUserId, false, true,
1979 "get/set setting for user", null);
1980 }
1981
Svet Ganov53a441c2016-04-19 19:38:00 -07001982 private Bundle packageValueForCallResult(Setting setting,
1983 boolean trackingGeneration) {
1984 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001985 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001986 return NULL_SETTING_BUNDLE;
1987 }
1988 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001989 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001990 Bundle result = new Bundle();
1991 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001992 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001993
Svetoslav Ganove080da92016-12-21 17:10:35 -08001994 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001995 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001996 }
1997
1998 private static int getRequestingUserId(Bundle args) {
1999 final int callingUserId = UserHandle.getCallingUserId();
2000 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2001 : callingUserId;
2002 }
2003
Svet Ganov53a441c2016-04-19 19:38:00 -07002004 private boolean isTrackingGeneration(Bundle args) {
2005 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2006 }
2007
Svetoslav683914b2015-01-15 14:22:26 -08002008 private static String getSettingValue(Bundle args) {
2009 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2010 }
2011
Svetoslav Ganove080da92016-12-21 17:10:35 -08002012 private static String getSettingTag(Bundle args) {
2013 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2014 }
2015
2016 private static boolean getSettingMakeDefault(Bundle args) {
2017 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2018 }
2019
2020 private static int getResetModeEnforcingPermission(Bundle args) {
2021 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2022 switch (mode) {
2023 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2024 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2025 throw new SecurityException("Only system, shell/root on a "
2026 + "debuggable build can reset to untrusted defaults");
2027 }
2028 return mode;
2029 }
2030 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2031 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2032 throw new SecurityException("Only system, shell/root on a "
2033 + "debuggable build can reset untrusted changes");
2034 }
2035 return mode;
2036 }
2037 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2038 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2039 throw new SecurityException("Only system, shell/root on a "
2040 + "debuggable build can reset to trusted defaults");
2041 }
2042 return mode;
2043 }
2044 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2045 return mode;
2046 }
2047 }
2048 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2049 }
2050
2051 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2052 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2053 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2054 && (appId == SHELL_UID || appId == ROOT_UID));
2055 }
2056
Svetoslav683914b2015-01-15 14:22:26 -08002057 private static String getValidTableOrThrow(Uri uri) {
2058 if (uri.getPathSegments().size() > 0) {
2059 String table = uri.getPathSegments().get(0);
2060 if (DatabaseHelper.isValidTable(table)) {
2061 return table;
2062 }
2063 throw new IllegalArgumentException("Bad root path: " + table);
2064 }
2065 throw new IllegalArgumentException("Invalid URI:" + uri);
2066 }
2067
2068 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002069 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002070 return new MatrixCursor(projection, 0);
2071 }
2072 MatrixCursor cursor = new MatrixCursor(projection, 1);
2073 appendSettingToCursor(cursor, setting);
2074 return cursor;
2075 }
2076
2077 private static String[] normalizeProjection(String[] projection) {
2078 if (projection == null) {
2079 return ALL_COLUMNS;
2080 }
2081
2082 final int columnCount = projection.length;
2083 for (int i = 0; i < columnCount; i++) {
2084 String column = projection[i];
2085 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2086 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002087 }
2088 }
2089
Svetoslav683914b2015-01-15 14:22:26 -08002090 return projection;
2091 }
2092
2093 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002094 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002095 return;
2096 }
Svetoslav683914b2015-01-15 14:22:26 -08002097 final int columnCount = cursor.getColumnCount();
2098
2099 String[] values = new String[columnCount];
2100
2101 for (int i = 0; i < columnCount; i++) {
2102 String column = cursor.getColumnName(i);
2103
2104 switch (column) {
2105 case Settings.NameValueTable._ID: {
2106 values[i] = setting.getId();
2107 } break;
2108
2109 case Settings.NameValueTable.NAME: {
2110 values[i] = setting.getName();
2111 } break;
2112
2113 case Settings.NameValueTable.VALUE: {
2114 values[i] = setting.getValue();
2115 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002116 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002117 }
2118
Svetoslav683914b2015-01-15 14:22:26 -08002119 cursor.addRow(values);
2120 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002121
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002122 private static boolean isKeyValid(String key) {
2123 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2124 }
2125
Svetoslav683914b2015-01-15 14:22:26 -08002126 private static final class Arguments {
2127 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2128 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2129
2130 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2131 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2132
2133 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2134 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2135
2136 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2137 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2138
2139 public final String table;
2140 public final String name;
2141
2142 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2143 final int segmentSize = uri.getPathSegments().size();
2144 switch (segmentSize) {
2145 case 1: {
2146 if (where != null
2147 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2148 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2149 && whereArgs.length == 1) {
2150 name = whereArgs[0];
2151 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002152 return;
Svetoslav683914b2015-01-15 14:22:26 -08002153 } else if (where != null
2154 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2155 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2156 final int startIndex = Math.max(where.indexOf("'"),
2157 where.indexOf("\"")) + 1;
2158 final int endIndex = Math.max(where.lastIndexOf("'"),
2159 where.lastIndexOf("\""));
2160 name = where.substring(startIndex, endIndex);
2161 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002162 return;
Svetoslav683914b2015-01-15 14:22:26 -08002163 } else if (supportAll && where == null && whereArgs == null) {
2164 name = null;
2165 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002166 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002167 }
Svetoslav683914b2015-01-15 14:22:26 -08002168 } break;
2169
Svetoslav28494652015-02-12 14:11:42 -08002170 case 2: {
2171 if (where == null && whereArgs == null) {
2172 name = uri.getPathSegments().get(1);
2173 table = computeTableForSetting(uri, name);
2174 return;
2175 }
2176 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002177 }
Svetoslav28494652015-02-12 14:11:42 -08002178
2179 EventLogTags.writeUnsupportedSettingsQuery(
2180 uri.toSafeString(), where, Arrays.toString(whereArgs));
2181 String message = String.format( "Supported SQL:\n"
2182 + " uri content://some_table/some_property with null where and where args\n"
2183 + " uri content://some_table with query name=? and single name as arg\n"
2184 + " uri content://some_table with query name=some_name and null args\n"
2185 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2186 Arrays.toString(whereArgs));
2187 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002188 }
2189
Svetoslav28494652015-02-12 14:11:42 -08002190 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002191 String table = getValidTableOrThrow(uri);
2192
2193 if (name != null) {
2194 if (sSystemMovedToSecureSettings.contains(name)) {
2195 table = TABLE_SECURE;
2196 }
2197
2198 if (sSystemMovedToGlobalSettings.contains(name)) {
2199 table = TABLE_GLOBAL;
2200 }
2201
2202 if (sSecureMovedToGlobalSettings.contains(name)) {
2203 table = TABLE_GLOBAL;
2204 }
2205
2206 if (sGlobalMovedToSecureSettings.contains(name)) {
2207 table = TABLE_SECURE;
2208 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002209 }
Svetoslav683914b2015-01-15 14:22:26 -08002210
2211 return table;
2212 }
2213 }
2214
2215 final class SettingsRegistry {
2216 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2217
Svetoslav683914b2015-01-15 14:22:26 -08002218 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2219 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2220 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002221 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2222
2223 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002224
2225 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2226
Svet Ganov53a441c2016-04-19 19:38:00 -07002227 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002228
Svetoslav7e0683b2015-08-03 16:02:52 -07002229 private final Handler mHandler;
2230
Svet Ganov53a441c2016-04-19 19:38:00 -07002231 private final BackupManager mBackupManager;
2232
Amith Yamasani39452022017-03-21 15:23:47 -07002233 private String mSettingsCreationBuildId;
2234
Svetoslav683914b2015-01-15 14:22:26 -08002235 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002236 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002237 mGenerationRegistry = new GenerationRegistry(mLock);
2238 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002239 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002240 syncSsaidTableOnStart();
2241 }
2242
2243 private void generateUserKeyLocked(int userId) {
2244 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002245 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002246 final SecureRandom rand = new SecureRandom();
2247 rand.nextBytes(keyBytes);
2248
2249 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002250 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002251
2252 // Store the key in the ssaid table.
2253 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2254 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2255 true, SettingsState.SYSTEM_PACKAGE_NAME);
2256
2257 if (!success) {
2258 throw new IllegalStateException("Ssaid settings not accessible");
2259 }
2260 }
2261
Mark Rathjen7599f132017-01-23 14:15:54 -08002262 private byte[] getLengthPrefix(byte[] data) {
2263 return ByteBuffer.allocate(4).putInt(data.length).array();
2264 }
2265
Christopher Tateb218e762017-04-05 16:34:07 -07002266 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002267 // Read the user's key from the ssaid table.
2268 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002269 if (userKeySetting == null || userKeySetting.isNull()
2270 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002271 // Lazy initialize and store the user key.
2272 generateUserKeyLocked(userId);
2273 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002274 if (userKeySetting == null || userKeySetting.isNull()
2275 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002276 throw new IllegalStateException("User key not accessible");
2277 }
2278 }
2279 final String userKey = userKeySetting.getValue();
2280
2281 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002282 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2283
2284 // Validate that the key is of expected length.
2285 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2286 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002287 throw new IllegalStateException("User key invalid");
2288 }
2289
Mark Rathjen7599f132017-01-23 14:15:54 -08002290 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002291 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002292 m = Mac.getInstance("HmacSHA256");
2293 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002294 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002295 throw new IllegalStateException("HmacSHA256 is not available", e);
2296 } catch (InvalidKeyException e) {
2297 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002298 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002299
Mark Rathjenf42dd912017-06-05 19:04:34 -07002300 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002301 for (int i = 0; i < callingPkg.signatures.length; i++) {
2302 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002303 m.update(getLengthPrefix(sig), 0, 4);
2304 m.update(sig);
2305 }
Mark Rathjend891f012017-01-19 04:10:37 +00002306
2307 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002308 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2309 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002310
2311 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002312 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002313 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2314 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002315 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002316
2317 if (!success) {
2318 throw new IllegalStateException("Ssaid settings not accessible");
2319 }
2320
2321 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2322 }
2323
2324 public void syncSsaidTableOnStart() {
2325 synchronized (mLock) {
2326 // Verify that each user's packages and ssaid's are in sync.
2327 for (UserInfo user : mUserManager.getUsers(true)) {
2328 // Get all uids for the user's packages.
2329 final List<PackageInfo> packages;
2330 try {
2331 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2332 } catch (RemoteException e) {
2333 throw new IllegalStateException("Package manager not available");
2334 }
2335 final Set<String> appUids = new HashSet<>();
2336 for (PackageInfo info : packages) {
2337 appUids.add(Integer.toString(info.applicationInfo.uid));
2338 }
2339
2340 // Get all uids currently stored in the user's ssaid table.
2341 final Set<String> ssaidUids = new HashSet<>(
2342 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2343 ssaidUids.remove(SSAID_USER_KEY);
2344
2345 // Perform a set difference for the appUids and ssaidUids.
2346 ssaidUids.removeAll(appUids);
2347
2348 // If there are ssaidUids left over they need to be removed from the table.
2349 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2350 user.id);
2351 for (String uid : ssaidUids) {
2352 ssaidSettings.deleteSettingLocked(uid);
2353 }
2354 }
2355 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002356 }
2357
Svetoslav683914b2015-01-15 14:22:26 -08002358 public List<String> getSettingsNamesLocked(int type, int userId) {
2359 final int key = makeKey(type, userId);
2360 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002361 if (settingsState == null) {
2362 return new ArrayList<String>();
2363 }
Svetoslav683914b2015-01-15 14:22:26 -08002364 return settingsState.getSettingNamesLocked();
2365 }
2366
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002367 public SparseBooleanArray getKnownUsersLocked() {
2368 SparseBooleanArray users = new SparseBooleanArray();
2369 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2370 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2371 }
2372 return users;
2373 }
2374
Kweku Adamsb0886f32017-10-31 15:32:09 -07002375 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002376 public SettingsState getSettingsLocked(int type, int userId) {
2377 final int key = makeKey(type, userId);
2378 return peekSettingsStateLocked(key);
2379 }
2380
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002381 public boolean ensureSettingsForUserLocked(int userId) {
2382 // First make sure this user actually exists.
2383 if (mUserManager.getUserInfo(userId) == null) {
2384 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2385 return false;
2386 }
2387
Svetoslav683914b2015-01-15 14:22:26 -08002388 // Migrate the setting for this user if needed.
2389 migrateLegacySettingsForUserIfNeededLocked(userId);
2390
2391 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002392 if (userId == UserHandle.USER_SYSTEM) {
2393 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002394 ensureSettingsStateLocked(globalKey);
2395 }
2396
2397 // Ensure secure settings loaded.
2398 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2399 ensureSettingsStateLocked(secureKey);
2400
2401 // Make sure the secure settings have an Android id set.
2402 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2403 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2404
2405 // Ensure system settings loaded.
2406 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2407 ensureSettingsStateLocked(systemKey);
2408
Mark Rathjend891f012017-01-19 04:10:37 +00002409 // Ensure secure settings loaded.
2410 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2411 ensureSettingsStateLocked(ssaidKey);
2412
Svetoslav683914b2015-01-15 14:22:26 -08002413 // Upgrade the settings to the latest version.
2414 UpgradeController upgrader = new UpgradeController(userId);
2415 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002416 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002417 }
2418
2419 private void ensureSettingsStateLocked(int key) {
2420 if (mSettingsStates.get(key) == null) {
2421 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002422 SettingsState settingsState = new SettingsState(getContext(), mLock,
2423 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002424 mSettingsStates.put(key, settingsState);
2425 }
2426 }
2427
2428 public void removeUserStateLocked(int userId, boolean permanently) {
2429 // We always keep the global settings in memory.
2430
2431 // Nuke system settings.
2432 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2433 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2434 if (systemSettingsState != null) {
2435 if (permanently) {
2436 mSettingsStates.remove(systemKey);
2437 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002438 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002439 systemSettingsState.destroyLocked(new Runnable() {
2440 @Override
2441 public void run() {
2442 mSettingsStates.remove(systemKey);
2443 }
2444 });
2445 }
2446 }
2447
2448 // Nuke secure settings.
2449 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2450 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2451 if (secureSettingsState != null) {
2452 if (permanently) {
2453 mSettingsStates.remove(secureKey);
2454 secureSettingsState.destroyLocked(null);
2455 } else {
2456 secureSettingsState.destroyLocked(new Runnable() {
2457 @Override
2458 public void run() {
2459 mSettingsStates.remove(secureKey);
2460 }
2461 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002462 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002463 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002464
Mark Rathjend891f012017-01-19 04:10:37 +00002465 // Nuke ssaid settings.
2466 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2467 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2468 if (ssaidSettingsState != null) {
2469 if (permanently) {
2470 mSettingsStates.remove(ssaidKey);
2471 ssaidSettingsState.destroyLocked(null);
2472 } else {
2473 ssaidSettingsState.destroyLocked(new Runnable() {
2474 @Override
2475 public void run() {
2476 mSettingsStates.remove(ssaidKey);
2477 }
2478 });
2479 }
2480 }
2481
Svet Ganov53a441c2016-04-19 19:38:00 -07002482 // Nuke generation tracking data
2483 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002484 }
2485
Svetoslav683914b2015-01-15 14:22:26 -08002486 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002487 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2488 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002489 final int key = makeKey(type, userId);
2490
Svetoslav Ganove080da92016-12-21 17:10:35 -08002491 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002492 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002493 if (settingsState != null) {
2494 success = settingsState.insertSettingLocked(name, value,
2495 tag, makeDefault, packageName);
2496 }
Svetoslav683914b2015-01-15 14:22:26 -08002497
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002498 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2499 settingsState.persistSyncLocked();
2500 }
2501
Svet Ganov53a441c2016-04-19 19:38:00 -07002502 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002503 notifyForSettingsChange(key, name);
2504 }
2505 return success;
2506 }
2507
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002508 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2509 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002510 final int key = makeKey(type, userId);
2511
Svetoslav Ganove080da92016-12-21 17:10:35 -08002512 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002513 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002514 if (settingsState != null) {
2515 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002516 }
Svetoslav683914b2015-01-15 14:22:26 -08002517
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002518 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2519 settingsState.persistSyncLocked();
2520 }
2521
Svet Ganov53a441c2016-04-19 19:38:00 -07002522 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002523 notifyForSettingsChange(key, name);
2524 }
2525 return success;
2526 }
2527
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002528 public boolean updateSettingLocked(int type, int userId, String name, String value,
2529 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2530 Set<String> criticalSettings) {
2531 final int key = makeKey(type, userId);
2532
2533 boolean success = false;
2534 SettingsState settingsState = peekSettingsStateLocked(key);
2535 if (settingsState != null) {
2536 success = settingsState.updateSettingLocked(name, value, tag,
2537 makeDefault, packageName);
2538 }
2539
2540 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2541 settingsState.persistSyncLocked();
2542 }
2543
2544 if (forceNotify || success) {
2545 notifyForSettingsChange(key, name);
2546 }
2547
2548 return success;
2549 }
2550
Svetoslav683914b2015-01-15 14:22:26 -08002551 public Setting getSettingLocked(int type, int userId, String name) {
2552 final int key = makeKey(type, userId);
2553
2554 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002555 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002556 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002557 }
Mark Rathjend891f012017-01-19 04:10:37 +00002558
2559 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002560 return settingsState.getSettingLocked(name);
2561 }
2562
Svetoslav Ganove080da92016-12-21 17:10:35 -08002563 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2564 String tag) {
2565 final int key = makeKey(type, userId);
2566 SettingsState settingsState = peekSettingsStateLocked(key);
2567 if (settingsState == null) {
2568 return;
2569 }
2570
2571 switch (mode) {
2572 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2573 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002574 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002575 Setting setting = settingsState.getSettingLocked(name);
2576 if (packageName.equals(setting.getPackageName())) {
2577 if (tag != null && !tag.equals(setting.getTag())) {
2578 continue;
2579 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002580 if (settingsState.resetSettingLocked(name)) {
2581 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002582 notifyForSettingsChange(key, name);
2583 }
2584 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002585 if (someSettingChanged) {
2586 settingsState.persistSyncLocked();
2587 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002588 }
2589 } break;
2590
2591 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2592 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002593 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002594 Setting setting = settingsState.getSettingLocked(name);
2595 if (!SettingsState.isSystemPackage(getContext(),
2596 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002597 if (settingsState.resetSettingLocked(name)) {
2598 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002599 notifyForSettingsChange(key, name);
2600 }
2601 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002602 if (someSettingChanged) {
2603 settingsState.persistSyncLocked();
2604 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002605 }
2606 } break;
2607
2608 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2609 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002610 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002611 Setting setting = settingsState.getSettingLocked(name);
2612 if (!SettingsState.isSystemPackage(getContext(),
2613 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002614 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002615 if (settingsState.resetSettingLocked(name)) {
2616 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002617 notifyForSettingsChange(key, name);
2618 }
2619 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002620 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002621 notifyForSettingsChange(key, name);
2622 }
2623 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002624 if (someSettingChanged) {
2625 settingsState.persistSyncLocked();
2626 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002627 }
2628 } break;
2629
2630 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2631 for (String name : settingsState.getSettingNamesLocked()) {
2632 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002633 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002634 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002635 if (settingsState.resetSettingLocked(name)) {
2636 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002637 notifyForSettingsChange(key, name);
2638 }
2639 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002640 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002641 notifyForSettingsChange(key, name);
2642 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002643 if (someSettingChanged) {
2644 settingsState.persistSyncLocked();
2645 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002646 }
2647 } break;
2648 }
2649 }
2650
Svetoslav683914b2015-01-15 14:22:26 -08002651 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002652 // Global and secure settings are signature protected. Apps signed
2653 // by the platform certificate are generally not uninstalled and
2654 // the main exception is tests. We trust components signed
2655 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002656
2657 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2658 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002659 if (systemSettings != null) {
2660 systemSettings.onPackageRemovedLocked(packageName);
2661 }
Svetoslav683914b2015-01-15 14:22:26 -08002662 }
2663
Mark Rathjend891f012017-01-19 04:10:37 +00002664 public void onUidRemovedLocked(int uid) {
2665 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2666 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002667 if (ssaidSettings != null) {
2668 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2669 }
Mark Rathjend891f012017-01-19 04:10:37 +00002670 }
2671
Kweku Adamsb0886f32017-10-31 15:32:09 -07002672 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002673 private SettingsState peekSettingsStateLocked(int key) {
2674 SettingsState settingsState = mSettingsStates.get(key);
2675 if (settingsState != null) {
2676 return settingsState;
2677 }
2678
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002679 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2680 return null;
2681 }
Svetoslav683914b2015-01-15 14:22:26 -08002682 return mSettingsStates.get(key);
2683 }
2684
2685 private void migrateAllLegacySettingsIfNeeded() {
2686 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002687 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002688 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002689 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002690 return;
2691 }
2692
Amith Yamasani39452022017-03-21 15:23:47 -07002693 mSettingsCreationBuildId = Build.ID;
2694
Svetoslav683914b2015-01-15 14:22:26 -08002695 final long identity = Binder.clearCallingIdentity();
2696 try {
2697 List<UserInfo> users = mUserManager.getUsers(true);
2698
2699 final int userCount = users.size();
2700 for (int i = 0; i < userCount; i++) {
2701 final int userId = users.get(i).id;
2702
2703 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2704 SQLiteDatabase database = dbHelper.getWritableDatabase();
2705 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2706
2707 // Upgrade to the latest version.
2708 UpgradeController upgrader = new UpgradeController(userId);
2709 upgrader.upgradeIfNeededLocked();
2710
2711 // Drop from memory if not a running user.
2712 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2713 removeUserStateLocked(userId, false);
2714 }
2715 }
2716 } finally {
2717 Binder.restoreCallingIdentity(identity);
2718 }
2719 }
2720 }
2721
2722 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2723 // Every user has secure settings and if no file we need to migrate.
2724 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2725 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002726 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002727 return;
2728 }
2729
2730 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2731 SQLiteDatabase database = dbHelper.getWritableDatabase();
2732
2733 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2734 }
2735
2736 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2737 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002738 // Move over the system settings.
2739 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2740 ensureSettingsStateLocked(systemKey);
2741 SettingsState systemSettings = mSettingsStates.get(systemKey);
2742 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2743 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002744
2745 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002746 // Do this after System settings, since this is the first thing we check when deciding
2747 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002748 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2749 ensureSettingsStateLocked(secureKey);
2750 SettingsState secureSettings = mSettingsStates.get(secureKey);
2751 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2752 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2753 secureSettings.persistSyncLocked();
2754
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002755 // Move over the global settings if owner.
2756 // Do this last, since this is the first thing we check when deciding
2757 // to skip over migration from db to xml for owner user.
2758 if (userId == UserHandle.USER_SYSTEM) {
2759 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2760 ensureSettingsStateLocked(globalKey);
2761 SettingsState globalSettings = mSettingsStates.get(globalKey);
2762 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002763 // If this was just created
2764 if (mSettingsCreationBuildId != null) {
2765 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2766 mSettingsCreationBuildId, null, true,
2767 SettingsState.SYSTEM_PACKAGE_NAME);
2768 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002769 globalSettings.persistSyncLocked();
2770 }
Svetoslav683914b2015-01-15 14:22:26 -08002771
2772 // Drop the database as now all is moved and persisted.
2773 if (DROP_DATABASE_ON_MIGRATION) {
2774 dbHelper.dropDatabase();
2775 } else {
2776 dbHelper.backupDatabase();
2777 }
2778 }
2779
2780 private void migrateLegacySettingsLocked(SettingsState settingsState,
2781 SQLiteDatabase database, String table) {
2782 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2783 queryBuilder.setTables(table);
2784
2785 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2786 null, null, null, null, null);
2787
2788 if (cursor == null) {
2789 return;
2790 }
2791
2792 try {
2793 if (!cursor.moveToFirst()) {
2794 return;
2795 }
2796
2797 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2798 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2799
2800 settingsState.setVersionLocked(database.getVersion());
2801
2802 while (!cursor.isAfterLast()) {
2803 String name = cursor.getString(nameColumnIdx);
2804 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002805 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002806 SettingsState.SYSTEM_PACKAGE_NAME);
2807 cursor.moveToNext();
2808 }
2809 } finally {
2810 cursor.close();
2811 }
2812 }
2813
2814 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2815 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2816
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002817 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002818 return;
2819 }
2820
2821 final int userId = getUserIdFromKey(secureSettings.mKey);
2822
2823 final UserInfo user;
2824 final long identity = Binder.clearCallingIdentity();
2825 try {
2826 user = mUserManager.getUserInfo(userId);
2827 } finally {
2828 Binder.restoreCallingIdentity(identity);
2829 }
2830 if (user == null) {
2831 // Can happen due to races when deleting users - treat as benign.
2832 return;
2833 }
2834
2835 String androidId = Long.toHexString(new SecureRandom().nextLong());
2836 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002837 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002838
2839 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2840 + "] for user " + userId);
2841
2842 // Write a drop box entry if it's a restricted profile
2843 if (user.isRestricted()) {
2844 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2845 Context.DROPBOX_SERVICE);
2846 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2847 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2848 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2849 }
2850 }
2851 }
2852
2853 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002854 final int userId = getUserIdFromKey(key);
2855 Uri uri = getNotificationUriFor(key, name);
2856
Phil Weaver83fec002016-05-11 10:55:29 -07002857 mGenerationRegistry.incrementGeneration(key);
2858
Svetoslav7e0683b2015-08-03 16:02:52 -07002859 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2860 userId, 0, uri).sendToTarget();
2861
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002862 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002863 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2864 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002865 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2866 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002867 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002868 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2869 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002870 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002871
Svet Ganov53a441c2016-04-19 19:38:00 -07002872 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Makoto Onuki0000d322017-11-28 16:31:47 -08002873
2874 // When the global kill switch is updated, send the change notification for
2875 // the location setting.
2876 if (isGlobalSettingsKey(key) && Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2877 notifyLocationChangeForRunningUsers();
2878 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002879 }
2880
Svet Ganov53a441c2016-04-19 19:38:00 -07002881 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002882 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002883 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002884 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002885 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002886 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002887 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002888 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002889 final int key = makeKey(type, profileId);
2890 mGenerationRegistry.incrementGeneration(key);
2891
2892 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002893 }
2894 }
2895 }
Svetoslav683914b2015-01-15 14:22:26 -08002896 }
2897
Makoto Onuki0000d322017-11-28 16:31:47 -08002898 private void notifyLocationChangeForRunningUsers() {
2899 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2900
2901 for (int i = 0; i < users.size(); i++) {
2902 final int userId = users.get(i).id;
2903
Makoto Onuki8e498252018-01-22 17:00:00 -08002904 // Do we have to increment the generation for users that are not running?
2905 // Yeah let's assume so...
2906 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
2907 mGenerationRegistry.incrementGeneration(key);
2908
Makoto Onuki0000d322017-11-28 16:31:47 -08002909 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2910 continue;
2911 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002912 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
2913
2914 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2915 userId, 0, uri).sendToTarget();
2916 }
2917 }
2918
Svetoslav683914b2015-01-15 14:22:26 -08002919 private boolean isGlobalSettingsKey(int key) {
2920 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2921 }
2922
2923 private boolean isSystemSettingsKey(int key) {
2924 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2925 }
2926
2927 private boolean isSecureSettingsKey(int key) {
2928 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2929 }
2930
Mark Rathjend891f012017-01-19 04:10:37 +00002931 private boolean isSsaidSettingsKey(int key) {
2932 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2933 }
2934
Svetoslav683914b2015-01-15 14:22:26 -08002935 private File getSettingsFile(int key) {
2936 if (isGlobalSettingsKey(key)) {
2937 final int userId = getUserIdFromKey(key);
2938 return new File(Environment.getUserSystemDirectory(userId),
2939 SETTINGS_FILE_GLOBAL);
2940 } else if (isSystemSettingsKey(key)) {
2941 final int userId = getUserIdFromKey(key);
2942 return new File(Environment.getUserSystemDirectory(userId),
2943 SETTINGS_FILE_SYSTEM);
2944 } else if (isSecureSettingsKey(key)) {
2945 final int userId = getUserIdFromKey(key);
2946 return new File(Environment.getUserSystemDirectory(userId),
2947 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002948 } else if (isSsaidSettingsKey(key)) {
2949 final int userId = getUserIdFromKey(key);
2950 return new File(Environment.getUserSystemDirectory(userId),
2951 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002952 } else {
2953 throw new IllegalArgumentException("Invalid settings key:" + key);
2954 }
2955 }
2956
2957 private Uri getNotificationUriFor(int key, String name) {
2958 if (isGlobalSettingsKey(key)) {
2959 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2960 : Settings.Global.CONTENT_URI;
2961 } else if (isSecureSettingsKey(key)) {
2962 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2963 : Settings.Secure.CONTENT_URI;
2964 } else if (isSystemSettingsKey(key)) {
2965 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2966 : Settings.System.CONTENT_URI;
2967 } else {
2968 throw new IllegalArgumentException("Invalid settings key:" + key);
2969 }
2970 }
2971
2972 private int getMaxBytesPerPackageForType(int type) {
2973 switch (type) {
2974 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002975 case SETTINGS_TYPE_SECURE:
2976 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002977 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2978 }
2979
2980 default: {
2981 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2982 }
2983 }
2984 }
2985
Svetoslav7e0683b2015-08-03 16:02:52 -07002986 private final class MyHandler extends Handler {
2987 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2988 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2989
2990 public MyHandler(Looper looper) {
2991 super(looper);
2992 }
2993
2994 @Override
2995 public void handleMessage(Message msg) {
2996 switch (msg.what) {
2997 case MSG_NOTIFY_URI_CHANGED: {
2998 final int userId = msg.arg1;
2999 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003000 try {
3001 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3002 } catch (SecurityException e) {
3003 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3004 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003005 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003006 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3007 }
3008 } break;
3009
3010 case MSG_NOTIFY_DATA_CHANGED: {
3011 mBackupManager.dataChanged();
3012 } break;
3013 }
3014 }
3015 }
3016
Svetoslav683914b2015-01-15 14:22:26 -08003017 private final class UpgradeController {
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003018 private static final int SETTINGS_VERSION = 152;
Svetoslav683914b2015-01-15 14:22:26 -08003019
3020 private final int mUserId;
3021
3022 public UpgradeController(int userId) {
3023 mUserId = userId;
3024 }
3025
3026 public void upgradeIfNeededLocked() {
3027 // The version of all settings for a user is the same (all users have secure).
3028 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003029 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003030
3031 // Try an update from the current state.
3032 final int oldVersion = secureSettings.getVersionLocked();
3033 final int newVersion = SETTINGS_VERSION;
3034
Svet Ganovc9755bc2015-03-28 13:21:22 -07003035 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003036 if (oldVersion == newVersion) {
3037 return;
3038 }
3039
3040 // Try to upgrade.
3041 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3042
3043 // If upgrade failed start from scratch and upgrade.
3044 if (curVersion != newVersion) {
3045 // Drop state we have for this user.
3046 removeUserStateLocked(mUserId, true);
3047
3048 // Recreate the database.
3049 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3050 SQLiteDatabase database = dbHelper.getWritableDatabase();
3051 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3052
3053 // Migrate the settings for this user.
3054 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3055
3056 // Now upgrade should work fine.
3057 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003058
3059 // Make a note what happened, so we don't wonder why data was lost
3060 String reason = "Settings rebuilt! Current version: "
3061 + curVersion + " while expected: " + newVersion;
3062 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003063 Settings.Global.DATABASE_DOWNGRADE_REASON,
3064 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003065 }
3066
3067 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003068 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003069 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003070 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003071 globalSettings.setVersionLocked(newVersion);
3072 }
3073
3074 // Set the secure settings version.
3075 secureSettings.setVersionLocked(newVersion);
3076
3077 // Set the system settings version.
3078 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003079 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003080 systemSettings.setVersionLocked(newVersion);
3081 }
3082
3083 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003084 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003085 }
3086
3087 private SettingsState getSecureSettingsLocked(int userId) {
3088 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3089 }
3090
Mark Rathjend891f012017-01-19 04:10:37 +00003091 private SettingsState getSsaidSettingsLocked(int userId) {
3092 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3093 }
3094
Svetoslav683914b2015-01-15 14:22:26 -08003095 private SettingsState getSystemSettingsLocked(int userId) {
3096 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3097 }
3098
Jeff Brown503cffc2015-03-26 18:08:51 -07003099 /**
3100 * You must perform all necessary mutations to bring the settings
3101 * for this user from the old to the new version. When you add a new
3102 * upgrade step you *must* update SETTINGS_VERSION.
3103 *
3104 * This is an example of moving a setting from secure to global.
3105 *
3106 * // v119: Example settings changes.
3107 * if (currentVersion == 118) {
3108 * if (userId == UserHandle.USER_OWNER) {
3109 * // Remove from the secure settings.
3110 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3111 * String name = "example_setting_to_move";
3112 * String value = secureSettings.getSetting(name);
3113 * secureSettings.deleteSetting(name);
3114 *
3115 * // Add to the global settings.
3116 * SettingsState globalSettings = getGlobalSettingsLocked();
3117 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3118 * }
3119 *
3120 * // Update the current version.
3121 * currentVersion = 119;
3122 * }
3123 */
Svetoslav683914b2015-01-15 14:22:26 -08003124 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3125 if (DEBUG) {
3126 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3127 + oldVersion + " to version: " + newVersion);
3128 }
3129
Jeff Brown503cffc2015-03-26 18:08:51 -07003130 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003131
John Spurlocke11ae112015-05-11 16:09:03 -04003132 // v119: Reset zen + ringer mode.
3133 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003134 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003135 final SettingsState globalSettings = getGlobalSettingsLocked();
3136 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003137 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3138 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003139 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003140 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3141 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003142 }
3143 currentVersion = 119;
3144 }
3145
Jason Monk27bbb2d2015-03-31 16:46:39 -04003146 // v120: Add double tap to wake setting.
3147 if (currentVersion == 119) {
3148 SettingsState secureSettings = getSecureSettingsLocked(userId);
3149 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3150 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003151 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003152 SettingsState.SYSTEM_PACKAGE_NAME);
3153
3154 currentVersion = 120;
3155 }
3156
Svetoslav7e0683b2015-08-03 16:02:52 -07003157 if (currentVersion == 120) {
3158 // Before 121, we used a different string encoding logic. We just bump the
3159 // version here; SettingsState knows how to handle pre-version 120 files.
3160 currentVersion = 121;
3161 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003162
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003163 if (currentVersion == 121) {
3164 // Version 122: allow OEMs to set a default payment component in resources.
3165 // Note that we only write the default if no default has been set;
3166 // if there is, we just leave the default at whatever it currently is.
3167 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3168 String defaultComponent = (getContext().getResources().getString(
3169 R.string.def_nfc_payment_component));
3170 Setting currentSetting = secureSettings.getSettingLocked(
3171 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3172 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003173 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003174 secureSettings.insertSettingLocked(
3175 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003176 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003177 }
3178 currentVersion = 122;
3179 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003180
3181 if (currentVersion == 122) {
3182 // Version 123: Adding a default value for the ability to add a user from
3183 // the lock screen.
3184 if (userId == UserHandle.USER_SYSTEM) {
3185 final SettingsState globalSettings = getGlobalSettingsLocked();
3186 Setting currentSetting = globalSettings.getSettingLocked(
3187 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003188 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003189 globalSettings.insertSettingLocked(
3190 Settings.Global.ADD_USERS_WHEN_LOCKED,
3191 getContext().getResources().getBoolean(
3192 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003193 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003194 }
3195 }
3196 currentVersion = 123;
3197 }
Bryce Leebd179282015-12-17 19:01:37 -08003198
3199 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003200 final SettingsState globalSettings = getGlobalSettingsLocked();
3201 String defaultDisabledProfiles = (getContext().getResources().getString(
3202 R.string.def_bluetooth_disabled_profiles));
3203 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003204 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003205 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003206 }
3207
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003208 if (currentVersion == 124) {
3209 // Version 124: allow OEMs to set a default value for whether IME should be
3210 // shown when a physical keyboard is connected.
3211 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3212 Setting currentSetting = secureSettings.getSettingLocked(
3213 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003214 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003215 secureSettings.insertSettingLocked(
3216 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3217 getContext().getResources().getBoolean(
3218 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003219 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003220 }
3221 currentVersion = 125;
3222 }
3223
Ruben Brunk98576cf2016-03-07 18:54:28 -08003224 if (currentVersion == 125) {
3225 // Version 125: Allow OEMs to set the default VR service.
3226 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3227
3228 Setting currentSetting = secureSettings.getSettingLocked(
3229 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003230 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003231 ArraySet<ComponentName> l =
3232 SystemConfig.getInstance().getDefaultVrComponents();
3233
3234 if (l != null && !l.isEmpty()) {
3235 StringBuilder b = new StringBuilder();
3236 boolean start = true;
3237 for (ComponentName c : l) {
3238 if (!start) {
3239 b.append(':');
3240 }
3241 b.append(c.flattenToString());
3242 start = false;
3243 }
3244 secureSettings.insertSettingLocked(
3245 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003246 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003247 }
3248
3249 }
3250 currentVersion = 126;
3251 }
3252
Daniel U02ba6122016-04-01 18:41:42 +01003253 if (currentVersion == 126) {
3254 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3255 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3256 if (mUserManager.isManagedProfile(userId)) {
3257 final SettingsState systemSecureSettings =
3258 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3259
3260 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3261 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003262 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003263 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3264 secureSettings.insertSettingLocked(
3265 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003266 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003267 SettingsState.SYSTEM_PACKAGE_NAME);
3268 }
3269
3270 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3271 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003272 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003273 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3274 secureSettings.insertSettingLocked(
3275 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003276 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003277 SettingsState.SYSTEM_PACKAGE_NAME);
3278 }
3279 }
3280 currentVersion = 127;
3281 }
3282
Steven Ngdc20ba62016-04-26 18:19:04 +01003283 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003284 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003285 currentVersion = 128;
3286 }
3287
Julia Reynolds1f721e12016-07-11 08:50:58 -04003288 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003289 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003290 currentVersion = 129;
3291 }
3292
Dan Sandler71f85e92016-07-20 13:46:05 -04003293 if (currentVersion == 129) {
3294 // default longpress timeout changed from 500 to 400. If unchanged from the old
3295 // default, update to the new default.
3296 final SettingsState systemSecureSettings =
3297 getSecureSettingsLocked(userId);
3298 final String oldValue = systemSecureSettings.getSettingLocked(
3299 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3300 if (TextUtils.equals("500", oldValue)) {
3301 systemSecureSettings.insertSettingLocked(
3302 Settings.Secure.LONG_PRESS_TIMEOUT,
3303 String.valueOf(getContext().getResources().getInteger(
3304 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003305 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003306 }
3307 currentVersion = 130;
3308 }
3309
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003310 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003311 // Split Ambient settings
3312 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3313 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3314 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3315
3316 if (dozeExplicitlyDisabled) {
3317 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003318 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003319 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003320 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003321 }
3322 currentVersion = 131;
3323 }
3324
3325 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003326 // Initialize new multi-press timeout to default value
3327 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3328 final String oldValue = systemSecureSettings.getSettingLocked(
3329 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3330 if (TextUtils.equals(null, oldValue)) {
3331 systemSecureSettings.insertSettingLocked(
3332 Settings.Secure.MULTI_PRESS_TIMEOUT,
3333 String.valueOf(getContext().getResources().getInteger(
3334 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003335 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003336 }
3337
Adrian Roos69741a22016-10-21 14:49:17 -07003338 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003339 }
3340
Adrian Roos69741a22016-10-21 14:49:17 -07003341 if (currentVersion == 132) {
3342 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003343 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3344 String defaultSyncParentSounds = (getContext().getResources()
3345 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3346 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003347 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3348 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003349 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003350 }
3351
Adrian Roos69741a22016-10-21 14:49:17 -07003352 if (currentVersion == 133) {
3353 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003354 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3355 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3356 null) {
3357 String defaultEndButtonBehavior = Integer.toString(getContext()
3358 .getResources().getInteger(R.integer.def_end_button_behavior));
3359 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003360 defaultEndButtonBehavior, null, true,
3361 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003362 }
Adrian Roos69741a22016-10-21 14:49:17 -07003363 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003364 }
3365
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003366 if (currentVersion == 134) {
3367 // Remove setting that specifies if magnification values should be preserved.
3368 // This setting defaulted to true and never has a UI.
3369 getSecureSettingsLocked(userId).deleteSettingLocked(
3370 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3371 currentVersion = 135;
3372 }
3373
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003374 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003375 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003376 currentVersion = 136;
3377 }
3378
Mark Rathjend891f012017-01-19 04:10:37 +00003379 if (currentVersion == 136) {
3380 // Version 136: Store legacy SSAID for all apps currently installed on the
3381 // device as first step in migrating SSAID to be unique per application.
3382
3383 final boolean isUpgrade;
3384 try {
3385 isUpgrade = mPackageManager.isUpgrade();
3386 } catch (RemoteException e) {
3387 throw new IllegalStateException("Package manager not available");
3388 }
3389 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3390 // user data or first boot on a new device should use new ssaid generation.
3391 if (isUpgrade) {
3392 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003393 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3394 userId, Settings.Secure.ANDROID_ID);
3395 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3396 || legacySsaidSetting.getValue() == null) {
3397 throw new IllegalStateException("Legacy ssaid not accessible");
3398 }
3399 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003400
3401 // Fill each uid with the legacy ssaid to be backwards compatible.
3402 final List<PackageInfo> packages;
3403 try {
3404 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3405 } catch (RemoteException e) {
3406 throw new IllegalStateException("Package manager not available");
3407 }
3408
3409 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3410 for (PackageInfo info : packages) {
3411 // Check if the UID already has an entry in the table.
3412 final String uid = Integer.toString(info.applicationInfo.uid);
3413 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3414
3415 if (ssaid.isNull() || ssaid.getValue() == null) {
3416 // Android Id doesn't exist for this package so create it.
3417 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3418 info.packageName);
3419 }
3420 }
3421 }
3422
3423 currentVersion = 137;
3424 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003425 if (currentVersion == 137) {
3426 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3427 // default value set to 1. The user can no longer change the value of this
3428 // setting through the UI.
3429 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3430 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003431 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3432 && secureSetting.getSettingLocked(
3433 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3434
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003435 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3436 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003437 // For managed profiles with profile owners, DevicePolicyManagerService
3438 // may want to set the user restriction in this case
3439 secureSetting.insertSettingLocked(
3440 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3441 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003442 }
3443 currentVersion = 138;
3444 }
Mark Rathjend891f012017-01-19 04:10:37 +00003445
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003446 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003447 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003448 currentVersion = 139;
3449 }
3450
Phil Weaver385912e2017-02-10 10:06:56 -08003451 if (currentVersion == 139) {
3452 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3453 // the user can no longer change the value of this setting through the UI.
3454 // Force to true.
3455 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3456 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3457 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3458 currentVersion = 140;
3459 }
3460
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003461 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003462 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003463 currentVersion = 141;
3464 }
3465
Svet Ganov13701552017-02-23 12:45:17 -08003466 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003467 // This implementation was incorrectly setting the current value of
3468 // settings changed by non-system packages as the default which default
3469 // is set by the system. We add a new upgrade step at the end to properly
3470 // handle this case which would also fix incorrect changes made by the
3471 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003472 currentVersion = 142;
3473 }
3474
Stephen Chen5d0922f2017-03-27 10:28:04 -07003475 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003476 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003477 if (userId == UserHandle.USER_SYSTEM) {
3478 final SettingsState globalSettings = getGlobalSettingsLocked();
3479 Setting currentSetting = globalSettings.getSettingLocked(
3480 Settings.Global.WIFI_WAKEUP_ENABLED);
3481 if (currentSetting.isNull()) {
3482 globalSettings.insertSettingLocked(
3483 Settings.Global.WIFI_WAKEUP_ENABLED,
3484 getContext().getResources().getBoolean(
3485 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3486 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3487 }
3488 }
3489
3490 currentVersion = 143;
3491 }
3492
Felipe Lemeff355092017-04-03 12:55:02 -07003493 if (currentVersion == 143) {
3494 // Version 144: Set a default value for Autofill service.
3495 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3496 final Setting currentSetting = secureSettings
3497 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3498 if (currentSetting.isNull()) {
3499 final String defaultValue = getContext().getResources().getString(
3500 com.android.internal.R.string.config_defaultAutofillService);
3501 if (defaultValue != null) {
3502 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3503 + "for user " + userId);
3504 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3505 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3506 }
3507 }
3508
3509 currentVersion = 144;
3510 }
3511
Jeremy Joslin45caa252017-05-04 11:22:46 -07003512 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003513 // Version 145: Removed
3514 currentVersion = 145;
3515 }
3516
3517 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003518 // Version 146: In step 142 we had a bug where incorrectly
3519 // some settings were considered system set and as a result
3520 // made the default and marked as the default being set by
3521 // the system. Here reevaluate the default and default system
3522 // set flags. This would both fix corruption by the old impl
3523 // of step 142 and also properly handle devices which never
3524 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003525 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003526 SettingsState globalSettings = getGlobalSettingsLocked();
3527 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3528 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003529 }
3530
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003531 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3532 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3533 secureSettings.persistSyncLocked();
3534
3535 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3536 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3537 systemSettings.persistSyncLocked();
3538
Amin Shaikh86367962017-06-07 08:58:22 -07003539 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003540 }
3541
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003542 if (currentVersion == 146) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003543 // Version 147: Set the default value for WIFI_WAKEUP_AVAILABLE.
3544 if (userId == UserHandle.USER_SYSTEM) {
3545 final SettingsState globalSettings = getGlobalSettingsLocked();
3546 final Setting currentSetting = globalSettings.getSettingLocked(
3547 Settings.Global.WIFI_WAKEUP_AVAILABLE);
3548 if (currentSetting.getValue() == null) {
3549 final int defaultValue = getContext().getResources().getInteger(
3550 com.android.internal.R.integer.config_wifi_wakeup_available);
3551 globalSettings.insertSettingLocked(
3552 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3553 String.valueOf(defaultValue),
3554 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3555 }
3556 }
3557
3558 currentVersion = 147;
3559 }
3560
3561 if (currentVersion == 147) {
3562 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003563 if (userId == UserHandle.USER_SYSTEM) {
3564 final SettingsState globalSettings = getGlobalSettingsLocked();
3565 final Setting currentSetting = globalSettings.getSettingLocked(
3566 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3567 if (currentSetting.isNull()) {
3568 globalSettings.insertSettingLocked(
3569 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3570 getContext().getResources().getBoolean(
3571 R.bool.def_restrict_background_data) ? "1" : "0",
3572 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3573 }
3574 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003575 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003576 }
3577
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003578 if (currentVersion == 148) {
3579 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3580 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3581 final String oldValue = systemSecureSettings.getSettingLocked(
3582 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3583 if (TextUtils.equals(null, oldValue)) {
3584 final String defaultValue = getContext().getResources().getString(
3585 R.string.def_backup_manager_constants);
3586 if (!TextUtils.isEmpty(defaultValue)) {
3587 systemSecureSettings.insertSettingLocked(
3588 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3589 true, SettingsState.SYSTEM_PACKAGE_NAME);
3590 }
3591 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003592 currentVersion = 149;
3593 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003594
3595 if (currentVersion == 149) {
3596 // Version 150: Set a default value for mobile data always on
3597 final SettingsState globalSettings = getGlobalSettingsLocked();
3598 final Setting currentSetting = globalSettings.getSettingLocked(
3599 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3600 if (currentSetting.isNull()) {
3601 globalSettings.insertSettingLocked(
3602 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3603 getContext().getResources().getBoolean(
3604 R.bool.def_mobile_data_always_on) ? "1" : "0",
3605 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3606 }
3607
3608 currentVersion = 150;
3609 }
3610
Mike Digman4af4a6f2018-01-16 14:49:38 -08003611 if (currentVersion == 150) {
3612 // Version 151: Reset rotate locked setting for upgrading users
3613 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3614 systemSettings.insertSettingLocked(
3615 Settings.System.ACCELEROMETER_ROTATION,
3616 getContext().getResources().getBoolean(
3617 R.bool.def_accelerometer_rotation) ? "1" : "0",
3618 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3619
3620 currentVersion = 151;
3621 }
3622
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003623 if (currentVersion == 151) {
3624 // Version 152: Reset wifi wake available for upgrading users
3625 final SettingsState globalSettings = getGlobalSettingsLocked();
3626 final int defaultValue = getContext().getResources().getInteger(
3627 com.android.internal.R.integer.config_wifi_wakeup_available);
3628 globalSettings.insertSettingLocked(
3629 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3630 String.valueOf(defaultValue),
3631 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3632
3633 currentVersion = 152;
3634 }
3635
Felipe Lemeff355092017-04-03 12:55:02 -07003636 // vXXX: Add new settings above this point.
3637
Dan Sandler71f85e92016-07-20 13:46:05 -04003638 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003639 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003640 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003641 + currentVersion +
3642 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3643 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003644 if (DEBUG) {
3645 throw new RuntimeException("db upgrade error");
3646 }
3647 }
3648
Jeff Brown503cffc2015-03-26 18:08:51 -07003649 // Return the current version.
3650 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003651 }
3652 }
Svet Ganov13701552017-02-23 12:45:17 -08003653
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003654 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3655 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003656 List<String> names = settings.getSettingNamesLocked();
3657 final int nameCount = names.size();
3658 for (int i = 0; i < nameCount; i++) {
3659 String name = names.get(i);
3660 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003661
3662 // In the upgrade case we pretend the call is made from the app
3663 // that made the last change to the setting to properly determine
3664 // whether the call has been made by a system component.
3665 int callingUid = -1;
3666 try {
3667 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3668 } catch (RemoteException e) {
3669 /* ignore - handled below */
3670 }
3671 if (callingUid < 0) {
3672 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3673 continue;
3674 }
3675 try {
3676 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3677 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003678 if (systemSet) {
3679 settings.insertSettingLocked(name, setting.getValue(),
3680 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003681 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3682 // We had a bug where changes by non-system packages were marked
3683 // as system made and as a result set as the default. Therefore, if
3684 // the package changed the setting last is not a system one but the
3685 // setting is marked as its default coming from the system we clear
3686 // the default and clear the system set flag.
3687 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003688 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003689 } catch (IllegalStateException e) {
3690 // If the package goes over its quota during the upgrade, don't
3691 // crash but just log the error as the system does the upgrade.
3692 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3693
Svet Ganov13701552017-02-23 12:45:17 -08003694 }
3695 }
3696 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003697 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003698}