blob: 15e6e4594699fdf493f8727ebb419e4f1a63b83d [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;
Christopher Tated5fe1472012-09-10 15:48:38 -070021import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070022import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080023import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070024import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080025import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070026import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070027import android.content.ContentValues;
28import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.Intent;
30import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080031import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070032import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080033import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070035import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070036import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.database.sqlite.SQLiteDatabase;
40import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080041import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040042import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070044import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080045import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080046import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070047import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080048import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070049import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070050import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070051import android.os.Looper;
52import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070053import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070054import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070055import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070056import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070057import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070058import android.os.UserHandle;
59import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070060import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010062import android.provider.Settings.Global;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010064import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080065import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000066import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070067import android.util.Slog;
68import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070069import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080070import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040071
Svetoslav683914b2015-01-15 14:22:26 -080072import com.android.internal.annotations.GuardedBy;
73import com.android.internal.content.PackageMonitor;
74import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080075import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070076import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080077import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080080import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080081import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080082import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080083import java.nio.ByteBuffer;
84import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000085import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080086import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070087import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000089import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000090import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080092import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010093import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080094import java.util.Set;
95import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080096import javax.crypto.Mac;
97import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070098
Svetoslav Ganove080da92016-12-21 17:10:35 -080099import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800100import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800101import static android.os.Process.SYSTEM_UID;
102
Svetoslav Ganove080da92016-12-21 17:10:35 -0800103
Svetoslav683914b2015-01-15 14:22:26 -0800104/**
105 * <p>
106 * This class is a content provider that publishes the system settings.
107 * It can be accessed via the content provider APIs or via custom call
108 * commands. The latter is a bit faster and is the preferred way to access
109 * the platform settings.
110 * </p>
111 * <p>
112 * There are three settings types, global (with signature level protection
113 * and shared across users), secure (with signature permission level
114 * protection and per user), and system (with dangerous permission level
115 * protection and per user). Global settings are stored under the device owner.
116 * Each of these settings is represented by a {@link
117 * com.android.providers.settings.SettingsState} object mapped to an integer
118 * key derived from the setting type in the most significant bits and user
119 * id in the least significant bits. Settings are synchronously loaded on
120 * instantiation of a SettingsState and asynchronously persisted on mutation.
121 * Settings are stored in the user specific system directory.
122 * </p>
123 * <p>
124 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
125 * and get a warning. Targeting higher API version prohibits this as the
126 * system settings are not a place for apps to save their state. When a package
127 * is removed the settings it added are deleted. Apps cannot delete system
128 * settings added by the platform. System settings values are validated to
129 * ensure the clients do not put bad values. Global and secure settings are
130 * changed only by trusted parties, therefore no validation is performed. Also
131 * there is a limit on the amount of app specific settings that can be added
132 * to prevent unlimited growth of the system process memory footprint.
133 * </p>
134 */
135@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700137 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700139 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800140
141 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700142
Christopher Tate06efb532012-08-24 15:29:27 -0700143 private static final String TABLE_SYSTEM = "system";
144 private static final String TABLE_SECURE = "secure";
145 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800146
147 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final String TABLE_FAVORITES = "favorites";
149 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800150 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
151 private static final String TABLE_BOOKMARKS = "bookmarks";
152 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Svetoslav683914b2015-01-15 14:22:26 -0800154 // The set of removed legacy tables.
155 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700156 static {
Svetoslav683914b2015-01-15 14:22:26 -0800157 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
158 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
159 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
160 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
161 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
162 }
Christopher Tate06efb532012-08-24 15:29:27 -0700163
Svetoslav683914b2015-01-15 14:22:26 -0800164 private static final int MUTATION_OPERATION_INSERT = 1;
165 private static final int MUTATION_OPERATION_DELETE = 2;
166 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800167 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400168
Svetoslav683914b2015-01-15 14:22:26 -0800169 private static final String[] ALL_COLUMNS = new String[] {
170 Settings.NameValueTable._ID,
171 Settings.NameValueTable.NAME,
172 Settings.NameValueTable.VALUE
173 };
174
Svet Ganov53a441c2016-04-19 19:38:00 -0700175 public static final int SETTINGS_TYPE_GLOBAL = 0;
176 public static final int SETTINGS_TYPE_SYSTEM = 1;
177 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000178 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800179
Svet Ganov53a441c2016-04-19 19:38:00 -0700180 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
181 public static final int SETTINGS_TYPE_SHIFT = 28;
182
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) {
279 return (type << SETTINGS_TYPE_SHIFT) | userId;
280 }
281
282 public static int getTypeFromKey(int key) {
283 return key >>> SETTINGS_TYPE_SHIFT;
284 }
285
286 public static int getUserIdFromKey(int key) {
287 return key & ~SETTINGS_TYPE_MASK;
288 }
289
290 public static String settingTypeToString(int type) {
291 switch (type) {
292 case SETTINGS_TYPE_GLOBAL: {
293 return "SETTINGS_GLOBAL";
294 }
295 case SETTINGS_TYPE_SECURE: {
296 return "SETTINGS_SECURE";
297 }
298 case SETTINGS_TYPE_SYSTEM: {
299 return "SETTINGS_SYSTEM";
300 }
Mark Rathjend891f012017-01-19 04:10:37 +0000301 case SETTINGS_TYPE_SSAID: {
302 return "SETTINGS_SSAID";
303 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 default: {
305 return "UNKNOWN";
306 }
307 }
308 }
309
310 public static String keyToString(int key) {
311 return "Key[user=" + getUserIdFromKey(key) + ";type="
312 + settingTypeToString(getTypeFromKey(key)) + "]";
313 }
314
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700315 @Override
316 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800317 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800318 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700319 mUserManager = UserManager.get(getContext());
320 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700321 mHandlerThread = new HandlerThread(LOG_TAG,
322 Process.THREAD_PRIORITY_BACKGROUND);
323 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700324 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800325 mSettingsRegistry = new SettingsRegistry();
326 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700327 mHandler.post(() -> {
328 registerBroadcastReceivers();
329 startWatchingUserRestrictionChanges();
330 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700331 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332 return true;
333 }
334
Svetoslav683914b2015-01-15 14:22:26 -0800335 @Override
336 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700337 final int requestingUserId = getRequestingUserId(args);
338 switch (method) {
339 case Settings.CALL_METHOD_GET_GLOBAL: {
340 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700341 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800342 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700343
344 case Settings.CALL_METHOD_GET_SECURE: {
345 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700346 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700347 }
348
349 case Settings.CALL_METHOD_GET_SYSTEM: {
350 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700351 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700352 }
353
354 case Settings.CALL_METHOD_PUT_GLOBAL: {
355 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800356 String tag = getSettingTag(args);
357 final boolean makeDefault = getSettingMakeDefault(args);
358 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700359 break;
360 }
361
362 case Settings.CALL_METHOD_PUT_SECURE: {
363 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800364 String tag = getSettingTag(args);
365 final boolean makeDefault = getSettingMakeDefault(args);
366 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700367 break;
368 }
369
370 case Settings.CALL_METHOD_PUT_SYSTEM: {
371 String value = getSettingValue(args);
372 insertSystemSetting(name, value, requestingUserId);
373 break;
374 }
375
Svetoslav Ganove080da92016-12-21 17:10:35 -0800376 case Settings.CALL_METHOD_RESET_GLOBAL: {
377 final int mode = getResetModeEnforcingPermission(args);
378 String tag = getSettingTag(args);
379 resetGlobalSetting(requestingUserId, mode, tag);
380 break;
381 }
382
383 case Settings.CALL_METHOD_RESET_SECURE: {
384 final int mode = getResetModeEnforcingPermission(args);
385 String tag = getSettingTag(args);
386 resetSecureSetting(requestingUserId, mode, tag);
387 break;
388 }
389
Svetoslav7ec28e82015-05-20 17:01:10 -0700390 default: {
391 Slog.w(LOG_TAG, "call() with invalid method: " + method);
392 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700393 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700394
Christopher Tate06efb532012-08-24 15:29:27 -0700395 return null;
396 }
397
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800398 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800399 public String getType(Uri uri) {
400 Arguments args = new Arguments(uri, null, null, true);
401 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700402 return "vnd.android.cursor.dir/" + args.table;
403 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700404 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700405 }
406 }
407
408 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800409 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
410 String order) {
411 if (DEBUG) {
412 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700413 }
414
Svetoslav683914b2015-01-15 14:22:26 -0800415 Arguments args = new Arguments(uri, where, whereArgs, true);
416 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700417
Svetoslav683914b2015-01-15 14:22:26 -0800418 // If a legacy table that is gone, done.
419 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
420 return new MatrixCursor(normalizedProjection, 0);
421 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700422
Svetoslav7ec28e82015-05-20 17:01:10 -0700423 switch (args.table) {
424 case TABLE_GLOBAL: {
425 if (args.name != null) {
426 Setting setting = getGlobalSetting(args.name);
427 return packageSettingForQuery(setting, normalizedProjection);
428 } else {
429 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700430 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700431 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700432
Svetoslav7ec28e82015-05-20 17:01:10 -0700433 case TABLE_SECURE: {
434 final int userId = UserHandle.getCallingUserId();
435 if (args.name != null) {
436 Setting setting = getSecureSetting(args.name, userId);
437 return packageSettingForQuery(setting, normalizedProjection);
438 } else {
439 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800440 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700441 }
Svetoslav683914b2015-01-15 14:22:26 -0800442
Svetoslav7ec28e82015-05-20 17:01:10 -0700443 case TABLE_SYSTEM: {
444 final int userId = UserHandle.getCallingUserId();
445 if (args.name != null) {
446 Setting setting = getSystemSetting(args.name, userId);
447 return packageSettingForQuery(setting, normalizedProjection);
448 } else {
449 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800450 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700451 }
Svetoslav683914b2015-01-15 14:22:26 -0800452
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 default: {
454 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700455 }
456 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700457 }
458
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700459 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800460 public Uri insert(Uri uri, ContentValues values) {
461 if (DEBUG) {
462 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700463 }
464
Svetoslav683914b2015-01-15 14:22:26 -0800465 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700466
Svetoslav683914b2015-01-15 14:22:26 -0800467 // If a legacy table that is gone, done.
468 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 return null;
470 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700471
Svetoslav683914b2015-01-15 14:22:26 -0800472 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700473 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800474 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700475 }
476
Svetoslav683914b2015-01-15 14:22:26 -0800477 String value = values.getAsString(Settings.Secure.VALUE);
478
Svetoslav7ec28e82015-05-20 17:01:10 -0700479 switch (table) {
480 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800481 if (insertGlobalSetting(name, value, null, false,
482 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700483 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700484 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700485 } break;
486
487 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800488 if (insertSecureSetting(name, value, null, false,
489 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700490 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
491 }
492 } break;
493
494 case TABLE_SYSTEM: {
495 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
496 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
497 }
498 } break;
499
500 default: {
501 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700502 }
503 }
504
Svetoslav683914b2015-01-15 14:22:26 -0800505 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506 }
507
508 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800509 public int bulkInsert(Uri uri, ContentValues[] allValues) {
510 if (DEBUG) {
511 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513
Svetoslav683914b2015-01-15 14:22:26 -0800514 int insertionCount = 0;
515 final int valuesCount = allValues.length;
516 for (int i = 0; i < valuesCount; i++) {
517 ContentValues values = allValues[i];
518 if (insert(uri, values) != null) {
519 insertionCount++;
520 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700521 }
Svetoslav683914b2015-01-15 14:22:26 -0800522
523 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700524 }
525
526 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800527 public int delete(Uri uri, String where, String[] whereArgs) {
528 if (DEBUG) {
529 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531
Svetoslav683914b2015-01-15 14:22:26 -0800532 Arguments args = new Arguments(uri, where, whereArgs, false);
533
534 // If a legacy table that is gone, done.
535 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
536 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700537 }
Svetoslav683914b2015-01-15 14:22:26 -0800538
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700539 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800540 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700541 }
Svetoslav683914b2015-01-15 14:22:26 -0800542
Svetoslav7ec28e82015-05-20 17:01:10 -0700543 switch (args.table) {
544 case TABLE_GLOBAL: {
545 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700546 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700547 }
Svetoslav683914b2015-01-15 14:22:26 -0800548
Svetoslav7ec28e82015-05-20 17:01:10 -0700549 case TABLE_SECURE: {
550 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700551 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 }
Svetoslav683914b2015-01-15 14:22:26 -0800553
Svetoslav7ec28e82015-05-20 17:01:10 -0700554 case TABLE_SYSTEM: {
555 final int userId = UserHandle.getCallingUserId();
556 return deleteSystemSetting(args.name, userId) ? 1 : 0;
557 }
558
559 default: {
560 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800561 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700562 }
Svetoslav683914b2015-01-15 14:22:26 -0800563 }
564
565 @Override
566 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
567 if (DEBUG) {
568 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700569 }
Svetoslav683914b2015-01-15 14:22:26 -0800570
571 Arguments args = new Arguments(uri, where, whereArgs, false);
572
573 // If a legacy table that is gone, done.
574 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
575 return 0;
576 }
577
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700578 String name = values.getAsString(Settings.Secure.NAME);
579 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800580 return 0;
581 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700582 String value = values.getAsString(Settings.Secure.VALUE);
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();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800587 return updateGlobalSetting(args.name, value, null, false,
588 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700589 }
Svetoslav683914b2015-01-15 14:22:26 -0800590
Svetoslav7ec28e82015-05-20 17:01:10 -0700591 case TABLE_SECURE: {
592 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800593 return updateSecureSetting(args.name, value, null, false,
594 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700595 }
Svetoslav683914b2015-01-15 14:22:26 -0800596
Svetoslav7ec28e82015-05-20 17:01:10 -0700597 case TABLE_SYSTEM: {
598 final int userId = UserHandle.getCallingUserId();
599 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
600 }
Svetoslav683914b2015-01-15 14:22:26 -0800601
Svetoslav7ec28e82015-05-20 17:01:10 -0700602 default: {
603 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800604 }
605 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700606 }
607
608 @Override
609 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100610 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
611 if (userId != UserHandle.getCallingUserId()) {
612 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
613 "Access files from the settings of another user");
614 }
615 uri = ContentProvider.getUriWithoutUserId(uri);
616
Andre Lago3fa139c2016-08-04 13:53:44 +0100617 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700618 final String cacheName;
619 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100620 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700621 cacheName = Settings.System.RINGTONE_CACHE;
622 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100623 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700624 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
625 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100626 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700627 cacheName = Settings.System.ALARM_ALERT_CACHE;
628 } else {
629 throw new FileNotFoundException("Direct file access no longer supported; "
630 + "ringtone playback is available through android.media.Ringtone");
631 }
632
Andre Lago3fa139c2016-08-04 13:53:44 +0100633 int actualCacheOwner;
634 // Redirect cache to parent if ringtone setting is owned by profile parent
635 synchronized (mLock) {
636 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
637 cacheRingtoneSetting);
638 }
639 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700640 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
641 }
642
643 private File getRingtoneCacheDir(int userId) {
644 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
645 cacheDir.mkdir();
646 SELinux.restorecon(cacheDir);
647 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700648 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800649
Eugene Suslad72c3972016-12-27 15:49:30 -0800650 /**
651 * Dump all settings as a proto buf.
652 *
653 * @param fd The file to dump to
654 */
655 void dumpProto(@NonNull FileDescriptor fd) {
656 ProtoOutputStream proto = new ProtoOutputStream(fd);
657
658 synchronized (mLock) {
659 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
660
661 }
662
663 proto.flush();
664 }
665
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700666 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800667 synchronized (mLock) {
668 final long identity = Binder.clearCallingIdentity();
669 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700670 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800671 final int userCount = users.size();
672 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700673 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800674 }
675 } finally {
676 Binder.restoreCallingIdentity(identity);
677 }
678 }
679 }
680
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700681 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700682 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800683 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700684 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
685 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700686 if (globalSettings != null) {
687 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800688 pw.println();
689 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700690 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800691 }
692
693 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700694 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
695 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700696 if (secureSettings != null) {
697 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800698 pw.println();
699 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700700 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700701
Svetoslavb505ccc2015-02-17 12:41:04 -0800702 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700703 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
704 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700705 if (systemSettings != null) {
706 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800707 pw.println();
708 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700709 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800710 }
711
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700712 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
713 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800714
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700715 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800716
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700717 for (int i = 0; i < nameCount; i++) {
718 String name = names.get(i);
719 Setting setting = settingsState.getSettingLocked(name);
720 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
721 pw.print(" name:"); pw.print(toDumpString(name));
722 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800723 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700724 }
725 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800726 if (setting.getDefaultValue() != null) {
727 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800728 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800729 }
730 if (setting.getTag() != null) {
731 pw.print(" tag:"); pw.print(setting.getTag());
732 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800733 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700734 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800735 }
736
Svetoslav7e0683b2015-08-03 16:02:52 -0700737 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700738 if (s != null) {
739 return s;
740 }
741 return "{null}";
742 }
743
Svetoslav683914b2015-01-15 14:22:26 -0800744 private void registerBroadcastReceivers() {
745 IntentFilter userFilter = new IntentFilter();
746 userFilter.addAction(Intent.ACTION_USER_REMOVED);
747 userFilter.addAction(Intent.ACTION_USER_STOPPED);
748
749 getContext().registerReceiver(new BroadcastReceiver() {
750 @Override
751 public void onReceive(Context context, Intent intent) {
752 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700753 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800754
755 switch (intent.getAction()) {
756 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700757 synchronized (mLock) {
758 mSettingsRegistry.removeUserStateLocked(userId, true);
759 }
Svetoslav683914b2015-01-15 14:22:26 -0800760 } break;
761
762 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700763 synchronized (mLock) {
764 mSettingsRegistry.removeUserStateLocked(userId, false);
765 }
Svetoslav683914b2015-01-15 14:22:26 -0800766 } break;
767 }
768 }
769 }, userFilter);
770
771 PackageMonitor monitor = new PackageMonitor() {
772 @Override
773 public void onPackageRemoved(String packageName, int uid) {
774 synchronized (mLock) {
775 mSettingsRegistry.onPackageRemovedLocked(packageName,
776 UserHandle.getUserId(uid));
777 }
778 }
Mark Rathjend891f012017-01-19 04:10:37 +0000779
780 @Override
781 public void onUidRemoved(int uid) {
782 synchronized (mLock) {
783 mSettingsRegistry.onUidRemovedLocked(uid);
784 }
785 }
Svetoslav683914b2015-01-15 14:22:26 -0800786 };
787
788 // package changes
789 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
790 UserHandle.ALL, true);
791 }
792
Svet Ganov53a441c2016-04-19 19:38:00 -0700793 private void startWatchingUserRestrictionChanges() {
794 // TODO: The current design of settings looking different based on user restrictions
795 // should be reworked to keep them separate and system code should check the setting
796 // first followed by checking the user restriction before performing an operation.
797 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
798 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
799 Bundle prevRestrictions) -> {
800 // We are changing the settings affected by restrictions to their current
801 // value with a forced update to ensure that all cross profile dependencies
802 // are taken into account. Also make sure the settings update to.. the same
803 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800804 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
805 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700806 final long identity = Binder.clearCallingIdentity();
807 try {
808 synchronized (mLock) {
809 Setting setting = getSecureSetting(
810 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
811 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800812 setting != null ? setting.getValue() : null, null,
813 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700814 }
815 } finally {
816 Binder.restoreCallingIdentity(identity);
817 }
818 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800819 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
820 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700821 final long identity = Binder.clearCallingIdentity();
822 try {
823 synchronized (mLock) {
824 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800825 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700826 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800827 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700828 }
829 } finally {
830 Binder.restoreCallingIdentity(identity);
831 }
832 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800833 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
834 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700835 final long identity = Binder.clearCallingIdentity();
836 try {
837 synchronized (mLock) {
838 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800839 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700840 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800841 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700842 }
843 } finally {
844 Binder.restoreCallingIdentity(identity);
845 }
846 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800847 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
848 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700849 final long identity = Binder.clearCallingIdentity();
850 try {
851 synchronized (mLock) {
852 Setting enable = getGlobalSetting(
853 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800854 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700855 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700857 Setting include = getGlobalSetting(
858 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800859 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700860 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800861 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700862 }
863 } finally {
864 Binder.restoreCallingIdentity(identity);
865 }
866 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800867 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
868 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700869 final long identity = Binder.clearCallingIdentity();
870 try {
871 synchronized (mLock) {
872 Setting setting = getGlobalSetting(
873 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800874 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700875 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800876 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700877 }
878 } finally {
879 Binder.restoreCallingIdentity(identity);
880 }
881 }
882 });
883 }
884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800886 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800888 }
889
Svetoslav7ec28e82015-05-20 17:01:10 -0700890 synchronized (mLock) {
891 // Get the settings.
892 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700893 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800894
Chad Brubaker97bccee2017-01-05 15:51:41 -0800895 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
896 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800897
Svetoslav7ec28e82015-05-20 17:01:10 -0700898 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800899
Svetoslav7ec28e82015-05-20 17:01:10 -0700900 String[] normalizedProjection = normalizeProjection(projection);
901 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800902
Svetoslav7ec28e82015-05-20 17:01:10 -0700903 // Anyone can get the global settings, so no security checks.
904 for (int i = 0; i < nameCount; i++) {
905 String name = names.get(i);
906 Setting setting = settingsState.getSettingLocked(name);
907 appendSettingToCursor(result, setting);
908 }
909
910 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800911 }
Svetoslav683914b2015-01-15 14:22:26 -0800912 }
913
Svetoslav7ec28e82015-05-20 17:01:10 -0700914 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800915 if (DEBUG) {
916 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
917 }
918
Chad Brubakera6830e72017-04-28 17:34:36 -0700919 // Ensure the caller can access the setting.
920 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
921
Svetoslav683914b2015-01-15 14:22:26 -0800922 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700923 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700924 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700925 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800926 }
Svetoslav683914b2015-01-15 14:22:26 -0800927 }
928
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 private boolean updateGlobalSetting(String name, String value, String tag,
930 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800931 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800932 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
933 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
934 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800935 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800936 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
937 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800938 }
939
Svetoslav Ganove080da92016-12-21 17:10:35 -0800940 private boolean insertGlobalSetting(String name, String value, String tag,
941 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700942 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800943 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
944 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
945 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700946 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800947 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
948 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700949 }
950
Svet Ganov53a441c2016-04-19 19:38:00 -0700951 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800952 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800953 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
954 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800955 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800956 return mutateGlobalSetting(name, null, null, false, requestingUserId,
957 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800958 }
959
Svetoslav Ganove080da92016-12-21 17:10:35 -0800960 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
961 if (DEBUG) {
962 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
963 + mode + ", " + tag + ")");
964 }
965 mutateGlobalSetting(null, null, tag, false, requestingUserId,
966 MUTATION_OPERATION_RESET, false, mode);
967 }
968
969 private boolean mutateGlobalSetting(String name, String value, String tag,
970 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
971 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800972 // Make sure the caller can change the settings - treated as secure.
973 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
974
Svetoslav683914b2015-01-15 14:22:26 -0800975 // Resolve the userId on whose behalf the call is made.
976 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
977
Makoto Onuki28da2e32015-11-20 11:30:44 -0800978 // If this is a setting that is currently restricted for this user, do not allow
979 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800980 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100981 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800982 return false;
983 }
984
985 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700986 synchronized (mLock) {
987 switch (operation) {
988 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800989 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
990 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800991 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700992 }
Svetoslav683914b2015-01-15 14:22:26 -0800993
Svetoslav7ec28e82015-05-20 17:01:10 -0700994 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700995 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800996 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 }
Svetoslav683914b2015-01-15 14:22:26 -0800998
Svetoslav7ec28e82015-05-20 17:01:10 -0700999 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1001 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001002 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001003 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001004
1005 case MUTATION_OPERATION_RESET: {
1006 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1007 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1008 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001009 }
1010 }
1011
1012 return false;
1013 }
1014
Christopher Tateb218e762017-04-05 16:34:07 -07001015 private PackageInfo getCallingPackageInfo(int userId) {
1016 try {
1017 return mPackageManager.getPackageInfo(getCallingPackage(),
1018 PackageManager.GET_SIGNATURES, userId);
1019 } catch (RemoteException e) {
1020 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1021 }
1022 }
1023
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001025 if (DEBUG) {
1026 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1027 }
1028
1029 // Resolve the userId on whose behalf the call is made.
1030 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1031
Christopher Tateb218e762017-04-05 16:34:07 -07001032 // The relevant "calling package" userId will be the owning userId for some
1033 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1034 // up front who the effective "new SSAID" user ID for that settings name will be.
1035 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1036 Settings.Secure.ANDROID_ID);
1037 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1038
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001040 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001041
Svetoslav7ec28e82015-05-20 17:01:10 -07001042 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001043
Svetoslav7ec28e82015-05-20 17:01:10 -07001044 String[] normalizedProjection = normalizeProjection(projection);
1045 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001046
Svetoslav7ec28e82015-05-20 17:01:10 -07001047 for (int i = 0; i < nameCount; i++) {
1048 String name = names.get(i);
1049 // Determine the owning user as some profile settings are cloned from the parent.
1050 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1051 name);
Svetoslav683914b2015-01-15 14:22:26 -08001052
Alex Klyubin1991f572017-03-03 14:08:36 -08001053 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1054 // This caller is not permitted to access this setting. Pretend the setting
1055 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001056 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001057 }
Svetoslav683914b2015-01-15 14:22:26 -08001058
Mark Rathjen7599f132017-01-23 14:15:54 -08001059 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001060 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1061 final Setting setting;
1062 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001063 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001064 } else {
1065 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1066 name);
1067 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001068 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001069 }
1070
Svetoslav7ec28e82015-05-20 17:01:10 -07001071 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001072 }
Svetoslav683914b2015-01-15 14:22:26 -08001073 }
1074
Svetoslav7ec28e82015-05-20 17:01:10 -07001075 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001076 if (DEBUG) {
1077 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1078 }
1079
1080 // Resolve the userId on whose behalf the call is made.
1081 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1082
Chad Brubakera6830e72017-04-28 17:34:36 -07001083 // Ensure the caller can access the setting.
1084 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1085
Svetoslav683914b2015-01-15 14:22:26 -08001086 // Determine the owning user as some profile settings are cloned from the parent.
1087 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1088
Alex Klyubin1991f572017-03-03 14:08:36 -08001089 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1090 // This caller is not permitted to access this setting. Pretend the setting doesn't
1091 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001092 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1093 owningUserId);
1094 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001095 }
1096
Christopher Tateb218e762017-04-05 16:34:07 -07001097 // As of Android O, the SSAID is read from an app-specific entry in table
1098 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1099 if (isNewSsaidSetting(name)) {
1100 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1101 synchronized (mLock) {
1102 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001103 }
Christopher Tateb218e762017-04-05 16:34:07 -07001104 }
Mark Rathjend891f012017-01-19 04:10:37 +00001105
Christopher Tateb218e762017-04-05 16:34:07 -07001106 // Not the SSAID; do a straight lookup
1107 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001108 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001109 owningUserId, name);
1110 }
Svetoslav683914b2015-01-15 14:22:26 -08001111 }
1112
Mark Rathjend891f012017-01-19 04:10:37 +00001113 private boolean isNewSsaidSetting(String name) {
1114 return Settings.Secure.ANDROID_ID.equals(name)
1115 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1116 }
1117
Christopher Tateb218e762017-04-05 16:34:07 -07001118 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001119 // Get uid of caller (key) used to store ssaid value
1120 String name = Integer.toString(
1121 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1122
1123 if (DEBUG) {
1124 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1125 }
1126
1127 // Retrieve the ssaid from the table if present.
1128 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1129 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001130 // If the app is an Instant App use its stored SSAID instead of our own.
1131 final String instantSsaid;
1132 final long token = Binder.clearCallingIdentity();
1133 try {
1134 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1135 owningUserId);
1136 } catch (RemoteException e) {
1137 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1138 return null;
1139 } finally {
1140 Binder.restoreCallingIdentity(token);
1141 }
Svet Ganov96c99462017-05-05 14:27:13 -07001142
1143 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1144 SETTINGS_TYPE_SSAID, owningUserId);
1145
Chad Brubaker0d277a72017-04-12 16:56:53 -07001146 if (instantSsaid != null) {
1147 // Use the stored value if it is still valid.
1148 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001149 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001150 }
1151 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001152 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1153 true, callingPkg.packageName);
1154 if (!success) {
1155 throw new IllegalStateException("Failed to update instant app android id");
1156 }
Svet Ganov96c99462017-05-05 14:27:13 -07001157 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1158 owningUserId, name);
1159 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001160 }
Mark Rathjend891f012017-01-19 04:10:37 +00001161
1162 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001163 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001164 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1165 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001166 }
1167
Svet Ganov96c99462017-05-05 14:27:13 -07001168 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1169 }
1170
1171 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1172 // SSAID settings are located in a dedicated table for internal bookkeeping
1173 // but for the world they reside in the secure table, so adjust the key here.
1174 // We have a special name when looking it up but want the world to see it as
1175 // "android_id".
1176 if (ssaidSetting != null) {
1177 return settingsState.new Setting(ssaidSetting) {
1178 @Override
1179 public int getKey() {
1180 final int userId = getUserIdFromKey(super.getKey());
1181 return makeKey(SETTINGS_TYPE_SECURE, userId);
1182 }
1183
1184 @Override
1185 public String getName() {
1186 return Settings.Secure.ANDROID_ID;
1187 }
1188 };
1189 }
1190 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001191 }
1192
Svetoslav Ganove080da92016-12-21 17:10:35 -08001193 private boolean insertSecureSetting(String name, String value, String tag,
1194 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001195 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001196 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001197 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1198 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001200 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1201 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001202 }
1203
Svet Ganov53a441c2016-04-19 19:38:00 -07001204 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001205 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001206 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1207 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001208 }
1209
Svetoslav Ganove080da92016-12-21 17:10:35 -08001210 return mutateSecureSetting(name, null, null, false, requestingUserId,
1211 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001212 }
1213
Svetoslav Ganove080da92016-12-21 17:10:35 -08001214 private boolean updateSecureSetting(String name, String value, String tag,
1215 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001216 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001217 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001218 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1219 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001220 }
1221
Svetoslav Ganove080da92016-12-21 17:10:35 -08001222 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1223 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001224 }
1225
Svetoslav Ganove080da92016-12-21 17:10:35 -08001226 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1227 if (DEBUG) {
1228 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1229 + mode + ", " + tag + ")");
1230 }
1231
1232 mutateSecureSetting(null, null, tag, false, requestingUserId,
1233 MUTATION_OPERATION_RESET, false, mode);
1234 }
1235
1236 private boolean mutateSecureSetting(String name, String value, String tag,
1237 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1238 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001239 // Make sure the caller can change the settings.
1240 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1241
Svetoslav683914b2015-01-15 14:22:26 -08001242 // Resolve the userId on whose behalf the call is made.
1243 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1244
Makoto Onuki28da2e32015-11-20 11:30:44 -08001245 // If this is a setting that is currently restricted for this user, do not allow
1246 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001247 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001248 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001249 return false;
1250 }
1251
1252 // Determine the owning user as some profile settings are cloned from the parent.
1253 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1254
1255 // Only the owning user can change the setting.
1256 if (owningUserId != callingUserId) {
1257 return false;
1258 }
1259
1260 // Special cases for location providers (sigh).
1261 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001262 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1263 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001264 }
1265
1266 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001267 synchronized (mLock) {
1268 switch (operation) {
1269 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001270 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001271 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001272 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001273 }
Svetoslav683914b2015-01-15 14:22:26 -08001274
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001276 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001277 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001278 }
Svetoslav683914b2015-01-15 14:22:26 -08001279
Svetoslav7ec28e82015-05-20 17:01:10 -07001280 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001281 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001282 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001283 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001284 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001285
1286 case MUTATION_OPERATION_RESET: {
1287 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1288 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1289 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001290 }
1291 }
1292
1293 return false;
1294 }
1295
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001297 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001298 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001299 }
1300
1301 // Resolve the userId on whose behalf the call is made.
1302 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1303
Svetoslav7ec28e82015-05-20 17:01:10 -07001304 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001305 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001306
Svetoslav7ec28e82015-05-20 17:01:10 -07001307 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001308
Svetoslav7ec28e82015-05-20 17:01:10 -07001309 String[] normalizedProjection = normalizeProjection(projection);
1310 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001311
Svetoslav7ec28e82015-05-20 17:01:10 -07001312 for (int i = 0; i < nameCount; i++) {
1313 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001314
Svetoslav7ec28e82015-05-20 17:01:10 -07001315 // Determine the owning user as some profile settings are cloned from the parent.
1316 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1317 name);
Svetoslav683914b2015-01-15 14:22:26 -08001318
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001320 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001321 appendSettingToCursor(result, setting);
1322 }
1323
1324 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001325 }
Svetoslav683914b2015-01-15 14:22:26 -08001326 }
1327
Svetoslav7ec28e82015-05-20 17:01:10 -07001328 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001329 if (DEBUG) {
1330 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1331 }
1332
1333 // Resolve the userId on whose behalf the call is made.
1334 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1335
Chad Brubakera6830e72017-04-28 17:34:36 -07001336 // Ensure the caller can access the setting.
1337 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001338
Svetoslav683914b2015-01-15 14:22:26 -08001339 // Determine the owning user as some profile settings are cloned from the parent.
1340 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1341
1342 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001343 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001344 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001345 }
Svetoslav683914b2015-01-15 14:22:26 -08001346 }
1347
Svetoslav7ec28e82015-05-20 17:01:10 -07001348 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001349 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001350 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001351 + requestingUserId + ")");
1352 }
1353
Svetoslav7ec28e82015-05-20 17:01:10 -07001354 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001355 }
1356
Svetoslav7ec28e82015-05-20 17:01:10 -07001357 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001358 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001359 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001360 }
1361
Svetoslav7ec28e82015-05-20 17:01:10 -07001362 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001363 }
1364
Svetoslav7ec28e82015-05-20 17:01:10 -07001365 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001366 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001367 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001368 + requestingUserId + ")");
1369 }
1370
Svetoslav7ec28e82015-05-20 17:01:10 -07001371 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001372 }
1373
Svetoslav7ec28e82015-05-20 17:01:10 -07001374 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001375 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001376 if (!hasWriteSecureSettingsPermission()) {
1377 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1378 // operation is allowed for the calling package through appops.
1379 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1380 Binder.getCallingUid(), getCallingPackage(), true)) {
1381 return false;
1382 }
Svetoslav683914b2015-01-15 14:22:26 -08001383 }
1384
Svetoslav683914b2015-01-15 14:22:26 -08001385 // Resolve the userId on whose behalf the call is made.
1386 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1387
Svetoslavd8d25e02015-11-20 13:09:26 -08001388 // Enforce what the calling package can mutate the system settings.
1389 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1390
Svetoslav683914b2015-01-15 14:22:26 -08001391 // Determine the owning user as some profile settings are cloned from the parent.
1392 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1393
1394 // Only the owning user id can change the setting.
1395 if (owningUserId != callingUserId) {
1396 return false;
1397 }
1398
Jeff Sharkey413573a2016-02-22 17:52:45 -07001399 // Invalidate any relevant cache files
1400 String cacheName = null;
1401 if (Settings.System.RINGTONE.equals(name)) {
1402 cacheName = Settings.System.RINGTONE_CACHE;
1403 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1404 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1405 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1406 cacheName = Settings.System.ALARM_ALERT_CACHE;
1407 }
1408 if (cacheName != null) {
1409 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001410 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001411 cacheFile.delete();
1412 }
1413
Svetoslav683914b2015-01-15 14:22:26 -08001414 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001415 synchronized (mLock) {
1416 switch (operation) {
1417 case MUTATION_OPERATION_INSERT: {
1418 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001419 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001420 owningUserId, name, value, null, false, getCallingPackage(),
1421 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001422 }
1423
1424 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001425 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001426 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001427 }
1428
1429 case MUTATION_OPERATION_UPDATE: {
1430 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001431 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001432 owningUserId, name, value, null, false, getCallingPackage(),
1433 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001434 }
Svetoslav683914b2015-01-15 14:22:26 -08001435 }
1436
Svetoslav7ec28e82015-05-20 17:01:10 -07001437 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001438 }
Svetoslav683914b2015-01-15 14:22:26 -08001439 }
1440
Billy Lau6ad2d662015-07-18 00:26:58 +01001441 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001442 // Write secure settings is a more protected permission. If caller has it we are good.
1443 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1444 == PackageManager.PERMISSION_GRANTED) {
1445 return true;
1446 }
1447
Svetoslavf41334b2015-06-23 12:06:03 -07001448 return false;
1449 }
1450
Svetoslav683914b2015-01-15 14:22:26 -08001451 private void validateSystemSettingValue(String name, String value) {
1452 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1453 if (validator != null && !validator.validate(value)) {
1454 throw new IllegalArgumentException("Invalid value: " + value
1455 + " for setting: " + name);
1456 }
1457 }
1458
Alex Klyubin1991f572017-03-03 14:08:36 -08001459 /**
1460 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1461 */
1462 private boolean isSecureSettingAccessible(String name, int callingUserId,
1463 int owningUserId) {
1464 // Special case for location (sigh).
1465 // This check is not inside the name-based checks below because this method performs checks
1466 // only if the calling user ID is not the same as the owning user ID.
1467 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1468 return false;
1469 }
1470
1471 switch (name) {
1472 case "bluetooth_address":
1473 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1474 // address in this secure setting. Secure settings can normally be read by any app,
1475 // which thus enables them to bypass the recently introduced restrictions on access
1476 // to device identifiers.
1477 // To mitigate this we make this setting available only to callers privileged to see
1478 // this device's MAC addresses, same as through public API
1479 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1480 return getContext().checkCallingOrSelfPermission(
1481 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1482 default:
1483 return true;
1484 }
1485 }
1486
Svetoslav683914b2015-01-15 14:22:26 -08001487 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1488 int owningUserId) {
1489 // Optimization - location providers are restricted only for managed profiles.
1490 if (callingUserId == owningUserId) {
1491 return false;
1492 }
1493 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1494 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1495 new UserHandle(callingUserId))) {
1496 return true;
1497 }
1498 return false;
1499 }
1500
Makoto Onuki28da2e32015-11-20 11:30:44 -08001501 /**
1502 * Checks whether changing a setting to a value is prohibited by the corresponding user
1503 * restriction.
1504 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001505 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1506 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001507 *
1508 * @return true if the change is prohibited, false if the change is allowed.
1509 */
1510 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001511 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001512 String restriction;
1513 switch (setting) {
1514 case Settings.Secure.LOCATION_MODE:
1515 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1516 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1517 // here normally, but we still protect it here from a direct provider write.
1518 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1519 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1520 break;
1521
1522 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1523 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1524 // a provider, which should be allowed even if the user restriction is set.
1525 if (value != null && value.startsWith("-")) return false;
1526 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1527 break;
1528
1529 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1530 if ("0".equals(value)) return false;
1531 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1532 break;
1533
1534 case Settings.Global.ADB_ENABLED:
1535 if ("0".equals(value)) return false;
1536 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1537 break;
1538
1539 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1540 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1541 if ("1".equals(value)) return false;
1542 restriction = UserManager.ENSURE_VERIFY_APPS;
1543 break;
1544
1545 case Settings.Global.PREFERRED_NETWORK_MODE:
1546 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1547 break;
1548
Victor Chang9c7b7062016-07-12 23:47:29 +01001549 case Settings.Secure.ALWAYS_ON_VPN_APP:
1550 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1551 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001552 final int appId = UserHandle.getAppId(callingUid);
1553 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001554 return false;
1555 }
1556 restriction = UserManager.DISALLOW_CONFIG_VPN;
1557 break;
1558
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001559 case Settings.Global.SAFE_BOOT_DISALLOWED:
1560 if ("1".equals(value)) return false;
1561 restriction = UserManager.DISALLOW_SAFE_BOOT;
1562 break;
1563
Makoto Onuki28da2e32015-11-20 11:30:44 -08001564 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001565 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001566 if ("0".equals(value)) return false;
1567 restriction = UserManager.DISALLOW_DATA_ROAMING;
1568 break;
1569 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001570 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001571 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001572
1573 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001574 }
1575
1576 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1577 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1578 }
1579
1580 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001581 final int parentId;
1582 // Resolves dependency if setting has a dependency and the calling user has a parent
1583 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1584 && (parentId = getGroupParentLocked(userId)) != userId) {
1585 // The setting has a dependency and the profile has a parent
1586 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001587 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1588 final long token = Binder.clearCallingIdentity();
1589 try {
1590 Setting settingObj = getSecureSetting(dependency, userId);
1591 if (settingObj != null && settingObj.getValue().equals("1")) {
1592 return parentId;
1593 }
1594 } finally {
1595 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001596 }
1597 }
Svetoslav683914b2015-01-15 14:22:26 -08001598 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1599 }
1600
1601 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1602 final int parentId = getGroupParentLocked(userId);
1603 if (parentId != userId && keys.contains(name)) {
1604 return parentId;
1605 }
1606 return userId;
1607 }
1608
Svetoslavf41334b2015-06-23 12:06:03 -07001609 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001610 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001611 // System/root/shell can mutate whatever secure settings they want.
1612 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001613 final int appId = UserHandle.getAppId(callingUid);
1614 if (appId == android.os.Process.SYSTEM_UID
1615 || appId == Process.SHELL_UID
1616 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001617 return;
1618 }
1619
1620 switch (operation) {
1621 case MUTATION_OPERATION_INSERT:
1622 // Insert updates.
1623 case MUTATION_OPERATION_UPDATE: {
1624 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1625 return;
1626 }
1627
1628 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001629 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001630
1631 // Privileged apps can do whatever they want.
1632 if ((packageInfo.applicationInfo.privateFlags
1633 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1634 return;
1635 }
1636
1637 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1638 packageInfo.applicationInfo.targetSdkVersion, name);
1639 } break;
1640
1641 case MUTATION_OPERATION_DELETE: {
1642 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1643 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1644 throw new IllegalArgumentException("You cannot delete system defined"
1645 + " secure settings.");
1646 }
1647
1648 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001649 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001650
1651 // Privileged apps can do whatever they want.
1652 if ((packageInfo.applicationInfo.privateFlags &
1653 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1654 return;
1655 }
1656
1657 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1658 packageInfo.applicationInfo.targetSdkVersion, name);
1659 } break;
1660 }
1661 }
1662
Todd Kennedybe0b8892017-02-15 14:13:52 -08001663 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001664 switch (settingsType) {
1665 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001666 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001667 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001668 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001669 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001670 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001671 default:
1672 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1673 }
1674 }
1675
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001676 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1677 switch (settingsType) {
1678 case SETTINGS_TYPE_GLOBAL:
1679 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1680 case SETTINGS_TYPE_SYSTEM:
1681 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1682 case SETTINGS_TYPE_SECURE:
1683 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1684 default:
1685 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1686 }
1687 }
1688
Chad Brubaker97bccee2017-01-05 15:51:41 -08001689 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001690 boolean instantApp;
1691 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1692 instantApp = false;
1693 } else {
1694 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1695 instantApp = ai.isInstantApp();
1696 }
1697 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001698 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001699 } else {
1700 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1701 }
1702 }
1703
Chad Brubakera6830e72017-04-28 17:34:36 -07001704 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001705 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1706 return;
1707 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001708 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001709 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001710 return;
1711 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001712 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1713 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001714 throw new SecurityException("Setting " + settingName + " is not accessible from"
1715 + " ephemeral package " + getCallingPackage());
1716 }
1717 }
1718
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001719 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1720 // We always use the callingUid for this lookup. This means that if hypothetically an
1721 // app was installed in user A with cross user and in user B as an Instant App
1722 // the app in A would be able to see all the settings in user B. However since cross
1723 // user is a system permission and the app must be uninstalled in B and then installed as
1724 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001725 ApplicationInfo ai = null;
1726 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001727 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1728 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001729 } catch (RemoteException ignored) {
1730 }
1731 if (ai == null) {
1732 throw new IllegalStateException("Failed to lookup info for package "
1733 + getCallingPackage());
1734 }
1735 return ai;
1736 }
1737
Xiaohui Chen43765b72015-08-31 10:57:33 -07001738 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001739 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001740 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1741 getCallingPackage(), 0, userId);
1742 if (packageInfo != null) {
1743 return packageInfo;
1744 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001745 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001746 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001747 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001748 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001749 }
1750
1751 private int getGroupParentLocked(int userId) {
1752 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001753 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001754 return userId;
1755 }
1756 // We are in the same process with the user manager and the returned
1757 // user info is a cached instance, so just look up instead of cache.
1758 final long identity = Binder.clearCallingIdentity();
1759 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001760 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001761 UserInfo userInfo = mUserManager.getProfileParent(userId);
1762 return (userInfo != null) ? userInfo.id : userId;
1763 } finally {
1764 Binder.restoreCallingIdentity(identity);
1765 }
1766 }
1767
Svetoslav683914b2015-01-15 14:22:26 -08001768 private void enforceWritePermission(String permission) {
1769 if (getContext().checkCallingOrSelfPermission(permission)
1770 != PackageManager.PERMISSION_GRANTED) {
1771 throw new SecurityException("Permission denial: writing to settings requires:"
1772 + permission);
1773 }
1774 }
1775
1776 /*
1777 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1778 * This setting contains a list of the currently enabled location providers.
1779 * But helper functions in android.providers.Settings can enable or disable
1780 * a single provider by using a "+" or "-" prefix before the provider name.
1781 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001782 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1783 * is set, the said method will only allow values with the "-" prefix.
1784 *
Svetoslav683914b2015-01-15 14:22:26 -08001785 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001786 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001787 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1788 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001789 if (TextUtils.isEmpty(value)) {
1790 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001791 }
1792
Svetoslav683914b2015-01-15 14:22:26 -08001793 final char prefix = value.charAt(0);
1794 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001795 if (forceNotify) {
1796 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1797 mSettingsRegistry.notifyForSettingsChange(key,
1798 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1799 }
Svetoslav683914b2015-01-15 14:22:26 -08001800 return false;
1801 }
1802
1803 // skip prefix
1804 value = value.substring(1);
1805
Svetoslav7ec28e82015-05-20 17:01:10 -07001806 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001807 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001808 if (settingValue == null) {
1809 return false;
1810 }
Svetoslav683914b2015-01-15 14:22:26 -08001811
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001812 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001813
1814 int index = oldProviders.indexOf(value);
1815 int end = index + value.length();
1816
1817 // check for commas to avoid matching on partial string
1818 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1819 index = -1;
1820 }
1821
1822 // check for commas to avoid matching on partial string
1823 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1824 index = -1;
1825 }
1826
1827 String newProviders;
1828
1829 if (prefix == '+' && index < 0) {
1830 // append the provider to the list if not present
1831 if (oldProviders.length() == 0) {
1832 newProviders = value;
1833 } else {
1834 newProviders = oldProviders + ',' + value;
1835 }
1836 } else if (prefix == '-' && index >= 0) {
1837 // remove the provider from the list if present
1838 // remove leading or trailing comma
1839 if (index > 0) {
1840 index--;
1841 } else if (end < oldProviders.length()) {
1842 end++;
1843 }
1844
1845 newProviders = oldProviders.substring(0, index);
1846 if (end < oldProviders.length()) {
1847 newProviders += oldProviders.substring(end);
1848 }
1849 } else {
1850 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001851 if (forceNotify) {
1852 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1853 mSettingsRegistry.notifyForSettingsChange(key,
1854 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1855 }
Svetoslav683914b2015-01-15 14:22:26 -08001856 return false;
1857 }
1858
Svet Ganov53a441c2016-04-19 19:38:00 -07001859 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001860 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001861 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001862 }
1863
Svetoslav683914b2015-01-15 14:22:26 -08001864 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1865 int targetSdkVersion, String name) {
1866 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1867 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1868 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1869 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1870 + " This will soon become an error.");
1871 } else {
1872 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1873 + " This will soon become an error.");
1874 }
1875 } else {
1876 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1877 throw new IllegalArgumentException("You cannot change private secure settings.");
1878 } else {
1879 throw new IllegalArgumentException("You cannot keep your settings in"
1880 + " the secure settings.");
1881 }
1882 }
1883 }
1884
1885 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1886 if (requestingUserId == UserHandle.getCallingUserId()) {
1887 return requestingUserId;
1888 }
1889 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1890 Binder.getCallingUid(), requestingUserId, false, true,
1891 "get/set setting for user", null);
1892 }
1893
Svet Ganov53a441c2016-04-19 19:38:00 -07001894 private Bundle packageValueForCallResult(Setting setting,
1895 boolean trackingGeneration) {
1896 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001897 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001898 return NULL_SETTING_BUNDLE;
1899 }
1900 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001901 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001902 Bundle result = new Bundle();
1903 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001904 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001905
Svetoslav Ganove080da92016-12-21 17:10:35 -08001906 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001907 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001908 }
1909
1910 private static int getRequestingUserId(Bundle args) {
1911 final int callingUserId = UserHandle.getCallingUserId();
1912 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1913 : callingUserId;
1914 }
1915
Svet Ganov53a441c2016-04-19 19:38:00 -07001916 private boolean isTrackingGeneration(Bundle args) {
1917 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1918 }
1919
Svetoslav683914b2015-01-15 14:22:26 -08001920 private static String getSettingValue(Bundle args) {
1921 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1922 }
1923
Svetoslav Ganove080da92016-12-21 17:10:35 -08001924 private static String getSettingTag(Bundle args) {
1925 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1926 }
1927
1928 private static boolean getSettingMakeDefault(Bundle args) {
1929 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1930 }
1931
1932 private static int getResetModeEnforcingPermission(Bundle args) {
1933 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1934 switch (mode) {
1935 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1936 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1937 throw new SecurityException("Only system, shell/root on a "
1938 + "debuggable build can reset to untrusted defaults");
1939 }
1940 return mode;
1941 }
1942 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1943 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1944 throw new SecurityException("Only system, shell/root on a "
1945 + "debuggable build can reset untrusted changes");
1946 }
1947 return mode;
1948 }
1949 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1950 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1951 throw new SecurityException("Only system, shell/root on a "
1952 + "debuggable build can reset to trusted defaults");
1953 }
1954 return mode;
1955 }
1956 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1957 return mode;
1958 }
1959 }
1960 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1961 }
1962
1963 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1964 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1965 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1966 && (appId == SHELL_UID || appId == ROOT_UID));
1967 }
1968
Svetoslav683914b2015-01-15 14:22:26 -08001969 private static String getValidTableOrThrow(Uri uri) {
1970 if (uri.getPathSegments().size() > 0) {
1971 String table = uri.getPathSegments().get(0);
1972 if (DatabaseHelper.isValidTable(table)) {
1973 return table;
1974 }
1975 throw new IllegalArgumentException("Bad root path: " + table);
1976 }
1977 throw new IllegalArgumentException("Invalid URI:" + uri);
1978 }
1979
1980 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001981 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001982 return new MatrixCursor(projection, 0);
1983 }
1984 MatrixCursor cursor = new MatrixCursor(projection, 1);
1985 appendSettingToCursor(cursor, setting);
1986 return cursor;
1987 }
1988
1989 private static String[] normalizeProjection(String[] projection) {
1990 if (projection == null) {
1991 return ALL_COLUMNS;
1992 }
1993
1994 final int columnCount = projection.length;
1995 for (int i = 0; i < columnCount; i++) {
1996 String column = projection[i];
1997 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1998 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001999 }
2000 }
2001
Svetoslav683914b2015-01-15 14:22:26 -08002002 return projection;
2003 }
2004
2005 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002006 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002007 return;
2008 }
Svetoslav683914b2015-01-15 14:22:26 -08002009 final int columnCount = cursor.getColumnCount();
2010
2011 String[] values = new String[columnCount];
2012
2013 for (int i = 0; i < columnCount; i++) {
2014 String column = cursor.getColumnName(i);
2015
2016 switch (column) {
2017 case Settings.NameValueTable._ID: {
2018 values[i] = setting.getId();
2019 } break;
2020
2021 case Settings.NameValueTable.NAME: {
2022 values[i] = setting.getName();
2023 } break;
2024
2025 case Settings.NameValueTable.VALUE: {
2026 values[i] = setting.getValue();
2027 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002028 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002029 }
2030
Svetoslav683914b2015-01-15 14:22:26 -08002031 cursor.addRow(values);
2032 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002033
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002034 private static boolean isKeyValid(String key) {
2035 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2036 }
2037
Svetoslav683914b2015-01-15 14:22:26 -08002038 private static final class Arguments {
2039 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2040 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2041
2042 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2043 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2044
2045 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2046 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2047
2048 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2049 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2050
2051 public final String table;
2052 public final String name;
2053
2054 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2055 final int segmentSize = uri.getPathSegments().size();
2056 switch (segmentSize) {
2057 case 1: {
2058 if (where != null
2059 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2060 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2061 && whereArgs.length == 1) {
2062 name = whereArgs[0];
2063 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002064 return;
Svetoslav683914b2015-01-15 14:22:26 -08002065 } else if (where != null
2066 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2067 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2068 final int startIndex = Math.max(where.indexOf("'"),
2069 where.indexOf("\"")) + 1;
2070 final int endIndex = Math.max(where.lastIndexOf("'"),
2071 where.lastIndexOf("\""));
2072 name = where.substring(startIndex, endIndex);
2073 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002074 return;
Svetoslav683914b2015-01-15 14:22:26 -08002075 } else if (supportAll && where == null && whereArgs == null) {
2076 name = null;
2077 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002078 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002079 }
Svetoslav683914b2015-01-15 14:22:26 -08002080 } break;
2081
Svetoslav28494652015-02-12 14:11:42 -08002082 case 2: {
2083 if (where == null && whereArgs == null) {
2084 name = uri.getPathSegments().get(1);
2085 table = computeTableForSetting(uri, name);
2086 return;
2087 }
2088 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002089 }
Svetoslav28494652015-02-12 14:11:42 -08002090
2091 EventLogTags.writeUnsupportedSettingsQuery(
2092 uri.toSafeString(), where, Arrays.toString(whereArgs));
2093 String message = String.format( "Supported SQL:\n"
2094 + " uri content://some_table/some_property with null where and where args\n"
2095 + " uri content://some_table with query name=? and single name as arg\n"
2096 + " uri content://some_table with query name=some_name and null args\n"
2097 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2098 Arrays.toString(whereArgs));
2099 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002100 }
2101
Svetoslav28494652015-02-12 14:11:42 -08002102 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002103 String table = getValidTableOrThrow(uri);
2104
2105 if (name != null) {
2106 if (sSystemMovedToSecureSettings.contains(name)) {
2107 table = TABLE_SECURE;
2108 }
2109
2110 if (sSystemMovedToGlobalSettings.contains(name)) {
2111 table = TABLE_GLOBAL;
2112 }
2113
2114 if (sSecureMovedToGlobalSettings.contains(name)) {
2115 table = TABLE_GLOBAL;
2116 }
2117
2118 if (sGlobalMovedToSecureSettings.contains(name)) {
2119 table = TABLE_SECURE;
2120 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002121 }
Svetoslav683914b2015-01-15 14:22:26 -08002122
2123 return table;
2124 }
2125 }
2126
2127 final class SettingsRegistry {
2128 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2129
Svetoslav683914b2015-01-15 14:22:26 -08002130 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2131 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2132 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002133 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2134
2135 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002136
2137 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2138
Svet Ganov53a441c2016-04-19 19:38:00 -07002139 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002140
Svetoslav7e0683b2015-08-03 16:02:52 -07002141 private final Handler mHandler;
2142
Svet Ganov53a441c2016-04-19 19:38:00 -07002143 private final BackupManager mBackupManager;
2144
Amith Yamasani39452022017-03-21 15:23:47 -07002145 private String mSettingsCreationBuildId;
2146
Svetoslav683914b2015-01-15 14:22:26 -08002147 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002148 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002149 mGenerationRegistry = new GenerationRegistry(mLock);
2150 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002151 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002152 syncSsaidTableOnStart();
2153 }
2154
2155 private void generateUserKeyLocked(int userId) {
2156 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002157 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002158 final SecureRandom rand = new SecureRandom();
2159 rand.nextBytes(keyBytes);
2160
2161 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002162 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002163
2164 // Store the key in the ssaid table.
2165 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2166 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2167 true, SettingsState.SYSTEM_PACKAGE_NAME);
2168
2169 if (!success) {
2170 throw new IllegalStateException("Ssaid settings not accessible");
2171 }
2172 }
2173
Mark Rathjen7599f132017-01-23 14:15:54 -08002174 private byte[] getLengthPrefix(byte[] data) {
2175 return ByteBuffer.allocate(4).putInt(data.length).array();
2176 }
2177
Christopher Tateb218e762017-04-05 16:34:07 -07002178 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002179 // Read the user's key from the ssaid table.
2180 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002181 if (userKeySetting == null || userKeySetting.isNull()
2182 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002183 // Lazy initialize and store the user key.
2184 generateUserKeyLocked(userId);
2185 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002186 if (userKeySetting == null || userKeySetting.isNull()
2187 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002188 throw new IllegalStateException("User key not accessible");
2189 }
2190 }
2191 final String userKey = userKeySetting.getValue();
2192
2193 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002194 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2195
2196 // Validate that the key is of expected length.
2197 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2198 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002199 throw new IllegalStateException("User key invalid");
2200 }
2201
Mark Rathjen7599f132017-01-23 14:15:54 -08002202 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002203 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002204 m = Mac.getInstance("HmacSHA256");
2205 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002206 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002207 throw new IllegalStateException("HmacSHA256 is not available", e);
2208 } catch (InvalidKeyException e) {
2209 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002210 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002211
Mark Rathjenf42dd912017-06-05 19:04:34 -07002212 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002213 for (int i = 0; i < callingPkg.signatures.length; i++) {
2214 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002215 m.update(getLengthPrefix(sig), 0, 4);
2216 m.update(sig);
2217 }
Mark Rathjend891f012017-01-19 04:10:37 +00002218
2219 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002220 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2221 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002222
2223 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002224 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002225 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2226 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002227 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002228
2229 if (!success) {
2230 throw new IllegalStateException("Ssaid settings not accessible");
2231 }
2232
2233 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2234 }
2235
2236 public void syncSsaidTableOnStart() {
2237 synchronized (mLock) {
2238 // Verify that each user's packages and ssaid's are in sync.
2239 for (UserInfo user : mUserManager.getUsers(true)) {
2240 // Get all uids for the user's packages.
2241 final List<PackageInfo> packages;
2242 try {
2243 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2244 } catch (RemoteException e) {
2245 throw new IllegalStateException("Package manager not available");
2246 }
2247 final Set<String> appUids = new HashSet<>();
2248 for (PackageInfo info : packages) {
2249 appUids.add(Integer.toString(info.applicationInfo.uid));
2250 }
2251
2252 // Get all uids currently stored in the user's ssaid table.
2253 final Set<String> ssaidUids = new HashSet<>(
2254 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2255 ssaidUids.remove(SSAID_USER_KEY);
2256
2257 // Perform a set difference for the appUids and ssaidUids.
2258 ssaidUids.removeAll(appUids);
2259
2260 // If there are ssaidUids left over they need to be removed from the table.
2261 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2262 user.id);
2263 for (String uid : ssaidUids) {
2264 ssaidSettings.deleteSettingLocked(uid);
2265 }
2266 }
2267 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002268 }
2269
Svetoslav683914b2015-01-15 14:22:26 -08002270 public List<String> getSettingsNamesLocked(int type, int userId) {
2271 final int key = makeKey(type, userId);
2272 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002273 if (settingsState == null) {
2274 return new ArrayList<String>();
2275 }
Svetoslav683914b2015-01-15 14:22:26 -08002276 return settingsState.getSettingNamesLocked();
2277 }
2278
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002279 public SparseBooleanArray getKnownUsersLocked() {
2280 SparseBooleanArray users = new SparseBooleanArray();
2281 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2282 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2283 }
2284 return users;
2285 }
2286
Svetoslav683914b2015-01-15 14:22:26 -08002287 public SettingsState getSettingsLocked(int type, int userId) {
2288 final int key = makeKey(type, userId);
2289 return peekSettingsStateLocked(key);
2290 }
2291
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002292 public boolean ensureSettingsForUserLocked(int userId) {
2293 // First make sure this user actually exists.
2294 if (mUserManager.getUserInfo(userId) == null) {
2295 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2296 return false;
2297 }
2298
Svetoslav683914b2015-01-15 14:22:26 -08002299 // Migrate the setting for this user if needed.
2300 migrateLegacySettingsForUserIfNeededLocked(userId);
2301
2302 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002303 if (userId == UserHandle.USER_SYSTEM) {
2304 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002305 ensureSettingsStateLocked(globalKey);
2306 }
2307
2308 // Ensure secure settings loaded.
2309 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2310 ensureSettingsStateLocked(secureKey);
2311
2312 // Make sure the secure settings have an Android id set.
2313 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2314 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2315
2316 // Ensure system settings loaded.
2317 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2318 ensureSettingsStateLocked(systemKey);
2319
Mark Rathjend891f012017-01-19 04:10:37 +00002320 // Ensure secure settings loaded.
2321 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2322 ensureSettingsStateLocked(ssaidKey);
2323
Svetoslav683914b2015-01-15 14:22:26 -08002324 // Upgrade the settings to the latest version.
2325 UpgradeController upgrader = new UpgradeController(userId);
2326 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002327 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002328 }
2329
2330 private void ensureSettingsStateLocked(int key) {
2331 if (mSettingsStates.get(key) == null) {
2332 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002333 SettingsState settingsState = new SettingsState(getContext(), mLock,
2334 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002335 mSettingsStates.put(key, settingsState);
2336 }
2337 }
2338
2339 public void removeUserStateLocked(int userId, boolean permanently) {
2340 // We always keep the global settings in memory.
2341
2342 // Nuke system settings.
2343 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2344 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2345 if (systemSettingsState != null) {
2346 if (permanently) {
2347 mSettingsStates.remove(systemKey);
2348 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002349 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002350 systemSettingsState.destroyLocked(new Runnable() {
2351 @Override
2352 public void run() {
2353 mSettingsStates.remove(systemKey);
2354 }
2355 });
2356 }
2357 }
2358
2359 // Nuke secure settings.
2360 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2361 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2362 if (secureSettingsState != null) {
2363 if (permanently) {
2364 mSettingsStates.remove(secureKey);
2365 secureSettingsState.destroyLocked(null);
2366 } else {
2367 secureSettingsState.destroyLocked(new Runnable() {
2368 @Override
2369 public void run() {
2370 mSettingsStates.remove(secureKey);
2371 }
2372 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002373 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002374 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002375
Mark Rathjend891f012017-01-19 04:10:37 +00002376 // Nuke ssaid settings.
2377 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2378 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2379 if (ssaidSettingsState != null) {
2380 if (permanently) {
2381 mSettingsStates.remove(ssaidKey);
2382 ssaidSettingsState.destroyLocked(null);
2383 } else {
2384 ssaidSettingsState.destroyLocked(new Runnable() {
2385 @Override
2386 public void run() {
2387 mSettingsStates.remove(ssaidKey);
2388 }
2389 });
2390 }
2391 }
2392
Svet Ganov53a441c2016-04-19 19:38:00 -07002393 // Nuke generation tracking data
2394 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002395 }
2396
Svetoslav683914b2015-01-15 14:22:26 -08002397 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002398 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2399 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002400 final int key = makeKey(type, userId);
2401
Svetoslav Ganove080da92016-12-21 17:10:35 -08002402 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002403 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002404 if (settingsState != null) {
2405 success = settingsState.insertSettingLocked(name, value,
2406 tag, makeDefault, packageName);
2407 }
Svetoslav683914b2015-01-15 14:22:26 -08002408
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002409 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2410 settingsState.persistSyncLocked();
2411 }
2412
Svet Ganov53a441c2016-04-19 19:38:00 -07002413 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002414 notifyForSettingsChange(key, name);
2415 }
2416 return success;
2417 }
2418
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002419 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2420 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002421 final int key = makeKey(type, userId);
2422
Svetoslav Ganove080da92016-12-21 17:10:35 -08002423 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002424 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002425 if (settingsState != null) {
2426 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002427 }
Svetoslav683914b2015-01-15 14:22:26 -08002428
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002429 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2430 settingsState.persistSyncLocked();
2431 }
2432
Svet Ganov53a441c2016-04-19 19:38:00 -07002433 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002434 notifyForSettingsChange(key, name);
2435 }
2436 return success;
2437 }
2438
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002439 public boolean updateSettingLocked(int type, int userId, String name, String value,
2440 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2441 Set<String> criticalSettings) {
2442 final int key = makeKey(type, userId);
2443
2444 boolean success = false;
2445 SettingsState settingsState = peekSettingsStateLocked(key);
2446 if (settingsState != null) {
2447 success = settingsState.updateSettingLocked(name, value, tag,
2448 makeDefault, packageName);
2449 }
2450
2451 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2452 settingsState.persistSyncLocked();
2453 }
2454
2455 if (forceNotify || success) {
2456 notifyForSettingsChange(key, name);
2457 }
2458
2459 return success;
2460 }
2461
Svetoslav683914b2015-01-15 14:22:26 -08002462 public Setting getSettingLocked(int type, int userId, String name) {
2463 final int key = makeKey(type, userId);
2464
2465 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002466 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002467 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002468 }
Mark Rathjend891f012017-01-19 04:10:37 +00002469
2470 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002471 return settingsState.getSettingLocked(name);
2472 }
2473
Svetoslav Ganove080da92016-12-21 17:10:35 -08002474 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2475 String tag) {
2476 final int key = makeKey(type, userId);
2477 SettingsState settingsState = peekSettingsStateLocked(key);
2478 if (settingsState == null) {
2479 return;
2480 }
2481
2482 switch (mode) {
2483 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2484 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002485 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002486 Setting setting = settingsState.getSettingLocked(name);
2487 if (packageName.equals(setting.getPackageName())) {
2488 if (tag != null && !tag.equals(setting.getTag())) {
2489 continue;
2490 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002491 if (settingsState.resetSettingLocked(name)) {
2492 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002493 notifyForSettingsChange(key, name);
2494 }
2495 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002496 if (someSettingChanged) {
2497 settingsState.persistSyncLocked();
2498 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002499 }
2500 } break;
2501
2502 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2503 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002504 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002505 Setting setting = settingsState.getSettingLocked(name);
2506 if (!SettingsState.isSystemPackage(getContext(),
2507 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002508 if (settingsState.resetSettingLocked(name)) {
2509 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002510 notifyForSettingsChange(key, name);
2511 }
2512 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002513 if (someSettingChanged) {
2514 settingsState.persistSyncLocked();
2515 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002516 }
2517 } break;
2518
2519 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2520 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002521 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002522 Setting setting = settingsState.getSettingLocked(name);
2523 if (!SettingsState.isSystemPackage(getContext(),
2524 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002525 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002526 if (settingsState.resetSettingLocked(name)) {
2527 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002528 notifyForSettingsChange(key, name);
2529 }
2530 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002531 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002532 notifyForSettingsChange(key, name);
2533 }
2534 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002535 if (someSettingChanged) {
2536 settingsState.persistSyncLocked();
2537 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002538 }
2539 } break;
2540
2541 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2542 for (String name : settingsState.getSettingNamesLocked()) {
2543 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002544 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002545 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002546 if (settingsState.resetSettingLocked(name)) {
2547 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002548 notifyForSettingsChange(key, name);
2549 }
2550 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002551 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002552 notifyForSettingsChange(key, name);
2553 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002554 if (someSettingChanged) {
2555 settingsState.persistSyncLocked();
2556 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002557 }
2558 } break;
2559 }
2560 }
2561
Svetoslav683914b2015-01-15 14:22:26 -08002562 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002563 // Global and secure settings are signature protected. Apps signed
2564 // by the platform certificate are generally not uninstalled and
2565 // the main exception is tests. We trust components signed
2566 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002567
2568 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2569 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002570 if (systemSettings != null) {
2571 systemSettings.onPackageRemovedLocked(packageName);
2572 }
Svetoslav683914b2015-01-15 14:22:26 -08002573 }
2574
Mark Rathjend891f012017-01-19 04:10:37 +00002575 public void onUidRemovedLocked(int uid) {
2576 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2577 UserHandle.getUserId(uid));
2578 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2579 }
2580
Svetoslav683914b2015-01-15 14:22:26 -08002581 private SettingsState peekSettingsStateLocked(int key) {
2582 SettingsState settingsState = mSettingsStates.get(key);
2583 if (settingsState != null) {
2584 return settingsState;
2585 }
2586
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002587 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2588 return null;
2589 }
Svetoslav683914b2015-01-15 14:22:26 -08002590 return mSettingsStates.get(key);
2591 }
2592
2593 private void migrateAllLegacySettingsIfNeeded() {
2594 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002595 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002596 File globalFile = getSettingsFile(key);
2597 if (globalFile.exists()) {
2598 return;
2599 }
2600
Amith Yamasani39452022017-03-21 15:23:47 -07002601 mSettingsCreationBuildId = Build.ID;
2602
Svetoslav683914b2015-01-15 14:22:26 -08002603 final long identity = Binder.clearCallingIdentity();
2604 try {
2605 List<UserInfo> users = mUserManager.getUsers(true);
2606
2607 final int userCount = users.size();
2608 for (int i = 0; i < userCount; i++) {
2609 final int userId = users.get(i).id;
2610
2611 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2612 SQLiteDatabase database = dbHelper.getWritableDatabase();
2613 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2614
2615 // Upgrade to the latest version.
2616 UpgradeController upgrader = new UpgradeController(userId);
2617 upgrader.upgradeIfNeededLocked();
2618
2619 // Drop from memory if not a running user.
2620 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2621 removeUserStateLocked(userId, false);
2622 }
2623 }
2624 } finally {
2625 Binder.restoreCallingIdentity(identity);
2626 }
2627 }
2628 }
2629
2630 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2631 // Every user has secure settings and if no file we need to migrate.
2632 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2633 File secureFile = getSettingsFile(secureKey);
2634 if (secureFile.exists()) {
2635 return;
2636 }
2637
2638 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2639 SQLiteDatabase database = dbHelper.getWritableDatabase();
2640
2641 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2642 }
2643
2644 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2645 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002646 // Move over the system settings.
2647 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2648 ensureSettingsStateLocked(systemKey);
2649 SettingsState systemSettings = mSettingsStates.get(systemKey);
2650 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2651 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002652
2653 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002654 // Do this after System settings, since this is the first thing we check when deciding
2655 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002656 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2657 ensureSettingsStateLocked(secureKey);
2658 SettingsState secureSettings = mSettingsStates.get(secureKey);
2659 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2660 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2661 secureSettings.persistSyncLocked();
2662
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002663 // Move over the global settings if owner.
2664 // Do this last, since this is the first thing we check when deciding
2665 // to skip over migration from db to xml for owner user.
2666 if (userId == UserHandle.USER_SYSTEM) {
2667 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2668 ensureSettingsStateLocked(globalKey);
2669 SettingsState globalSettings = mSettingsStates.get(globalKey);
2670 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002671 // If this was just created
2672 if (mSettingsCreationBuildId != null) {
2673 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2674 mSettingsCreationBuildId, null, true,
2675 SettingsState.SYSTEM_PACKAGE_NAME);
2676 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002677 globalSettings.persistSyncLocked();
2678 }
Svetoslav683914b2015-01-15 14:22:26 -08002679
2680 // Drop the database as now all is moved and persisted.
2681 if (DROP_DATABASE_ON_MIGRATION) {
2682 dbHelper.dropDatabase();
2683 } else {
2684 dbHelper.backupDatabase();
2685 }
2686 }
2687
2688 private void migrateLegacySettingsLocked(SettingsState settingsState,
2689 SQLiteDatabase database, String table) {
2690 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2691 queryBuilder.setTables(table);
2692
2693 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2694 null, null, null, null, null);
2695
2696 if (cursor == null) {
2697 return;
2698 }
2699
2700 try {
2701 if (!cursor.moveToFirst()) {
2702 return;
2703 }
2704
2705 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2706 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2707
2708 settingsState.setVersionLocked(database.getVersion());
2709
2710 while (!cursor.isAfterLast()) {
2711 String name = cursor.getString(nameColumnIdx);
2712 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002713 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002714 SettingsState.SYSTEM_PACKAGE_NAME);
2715 cursor.moveToNext();
2716 }
2717 } finally {
2718 cursor.close();
2719 }
2720 }
2721
2722 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2723 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2724
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002725 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002726 return;
2727 }
2728
2729 final int userId = getUserIdFromKey(secureSettings.mKey);
2730
2731 final UserInfo user;
2732 final long identity = Binder.clearCallingIdentity();
2733 try {
2734 user = mUserManager.getUserInfo(userId);
2735 } finally {
2736 Binder.restoreCallingIdentity(identity);
2737 }
2738 if (user == null) {
2739 // Can happen due to races when deleting users - treat as benign.
2740 return;
2741 }
2742
2743 String androidId = Long.toHexString(new SecureRandom().nextLong());
2744 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002745 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002746
2747 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2748 + "] for user " + userId);
2749
2750 // Write a drop box entry if it's a restricted profile
2751 if (user.isRestricted()) {
2752 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2753 Context.DROPBOX_SERVICE);
2754 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2755 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2756 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2757 }
2758 }
2759 }
2760
2761 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002762 final int userId = getUserIdFromKey(key);
2763 Uri uri = getNotificationUriFor(key, name);
2764
Phil Weaver83fec002016-05-11 10:55:29 -07002765 mGenerationRegistry.incrementGeneration(key);
2766
Svetoslav7e0683b2015-08-03 16:02:52 -07002767 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2768 userId, 0, uri).sendToTarget();
2769
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002770 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002771 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2772 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002773 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2774 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002775 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002776 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2777 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002778 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002779
Svet Ganov53a441c2016-04-19 19:38:00 -07002780 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002781 }
2782
Svet Ganov53a441c2016-04-19 19:38:00 -07002783 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002784 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002785 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002786 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002787 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002788 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002789 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002790 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002791 final int key = makeKey(type, profileId);
2792 mGenerationRegistry.incrementGeneration(key);
2793
2794 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002795 }
2796 }
2797 }
Svetoslav683914b2015-01-15 14:22:26 -08002798 }
2799
Svetoslav683914b2015-01-15 14:22:26 -08002800 private boolean isGlobalSettingsKey(int key) {
2801 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2802 }
2803
2804 private boolean isSystemSettingsKey(int key) {
2805 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2806 }
2807
2808 private boolean isSecureSettingsKey(int key) {
2809 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2810 }
2811
Mark Rathjend891f012017-01-19 04:10:37 +00002812 private boolean isSsaidSettingsKey(int key) {
2813 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2814 }
2815
Svetoslav683914b2015-01-15 14:22:26 -08002816 private File getSettingsFile(int key) {
2817 if (isGlobalSettingsKey(key)) {
2818 final int userId = getUserIdFromKey(key);
2819 return new File(Environment.getUserSystemDirectory(userId),
2820 SETTINGS_FILE_GLOBAL);
2821 } else if (isSystemSettingsKey(key)) {
2822 final int userId = getUserIdFromKey(key);
2823 return new File(Environment.getUserSystemDirectory(userId),
2824 SETTINGS_FILE_SYSTEM);
2825 } else if (isSecureSettingsKey(key)) {
2826 final int userId = getUserIdFromKey(key);
2827 return new File(Environment.getUserSystemDirectory(userId),
2828 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002829 } else if (isSsaidSettingsKey(key)) {
2830 final int userId = getUserIdFromKey(key);
2831 return new File(Environment.getUserSystemDirectory(userId),
2832 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002833 } else {
2834 throw new IllegalArgumentException("Invalid settings key:" + key);
2835 }
2836 }
2837
2838 private Uri getNotificationUriFor(int key, String name) {
2839 if (isGlobalSettingsKey(key)) {
2840 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2841 : Settings.Global.CONTENT_URI;
2842 } else if (isSecureSettingsKey(key)) {
2843 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2844 : Settings.Secure.CONTENT_URI;
2845 } else if (isSystemSettingsKey(key)) {
2846 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2847 : Settings.System.CONTENT_URI;
2848 } else {
2849 throw new IllegalArgumentException("Invalid settings key:" + key);
2850 }
2851 }
2852
2853 private int getMaxBytesPerPackageForType(int type) {
2854 switch (type) {
2855 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002856 case SETTINGS_TYPE_SECURE:
2857 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002858 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2859 }
2860
2861 default: {
2862 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2863 }
2864 }
2865 }
2866
Svetoslav7e0683b2015-08-03 16:02:52 -07002867 private final class MyHandler extends Handler {
2868 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2869 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2870
2871 public MyHandler(Looper looper) {
2872 super(looper);
2873 }
2874
2875 @Override
2876 public void handleMessage(Message msg) {
2877 switch (msg.what) {
2878 case MSG_NOTIFY_URI_CHANGED: {
2879 final int userId = msg.arg1;
2880 Uri uri = (Uri) msg.obj;
2881 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2882 if (DEBUG) {
2883 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2884 }
2885 } break;
2886
2887 case MSG_NOTIFY_DATA_CHANGED: {
2888 mBackupManager.dataChanged();
2889 } break;
2890 }
2891 }
2892 }
2893
Svetoslav683914b2015-01-15 14:22:26 -08002894 private final class UpgradeController {
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002895 private static final int SETTINGS_VERSION = 147;
Svetoslav683914b2015-01-15 14:22:26 -08002896
2897 private final int mUserId;
2898
2899 public UpgradeController(int userId) {
2900 mUserId = userId;
2901 }
2902
2903 public void upgradeIfNeededLocked() {
2904 // The version of all settings for a user is the same (all users have secure).
2905 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002906 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002907
2908 // Try an update from the current state.
2909 final int oldVersion = secureSettings.getVersionLocked();
2910 final int newVersion = SETTINGS_VERSION;
2911
Svet Ganovc9755bc2015-03-28 13:21:22 -07002912 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002913 if (oldVersion == newVersion) {
2914 return;
2915 }
2916
2917 // Try to upgrade.
2918 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2919
2920 // If upgrade failed start from scratch and upgrade.
2921 if (curVersion != newVersion) {
2922 // Drop state we have for this user.
2923 removeUserStateLocked(mUserId, true);
2924
2925 // Recreate the database.
2926 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2927 SQLiteDatabase database = dbHelper.getWritableDatabase();
2928 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2929
2930 // Migrate the settings for this user.
2931 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2932
2933 // Now upgrade should work fine.
2934 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002935
2936 // Make a note what happened, so we don't wonder why data was lost
2937 String reason = "Settings rebuilt! Current version: "
2938 + curVersion + " while expected: " + newVersion;
2939 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002940 Settings.Global.DATABASE_DOWNGRADE_REASON,
2941 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002942 }
2943
2944 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002945 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002946 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002947 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002948 globalSettings.setVersionLocked(newVersion);
2949 }
2950
2951 // Set the secure settings version.
2952 secureSettings.setVersionLocked(newVersion);
2953
2954 // Set the system settings version.
2955 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002956 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002957 systemSettings.setVersionLocked(newVersion);
2958 }
2959
2960 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002961 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002962 }
2963
2964 private SettingsState getSecureSettingsLocked(int userId) {
2965 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2966 }
2967
Mark Rathjend891f012017-01-19 04:10:37 +00002968 private SettingsState getSsaidSettingsLocked(int userId) {
2969 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2970 }
2971
Svetoslav683914b2015-01-15 14:22:26 -08002972 private SettingsState getSystemSettingsLocked(int userId) {
2973 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2974 }
2975
Jeff Brown503cffc2015-03-26 18:08:51 -07002976 /**
2977 * You must perform all necessary mutations to bring the settings
2978 * for this user from the old to the new version. When you add a new
2979 * upgrade step you *must* update SETTINGS_VERSION.
2980 *
2981 * This is an example of moving a setting from secure to global.
2982 *
2983 * // v119: Example settings changes.
2984 * if (currentVersion == 118) {
2985 * if (userId == UserHandle.USER_OWNER) {
2986 * // Remove from the secure settings.
2987 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2988 * String name = "example_setting_to_move";
2989 * String value = secureSettings.getSetting(name);
2990 * secureSettings.deleteSetting(name);
2991 *
2992 * // Add to the global settings.
2993 * SettingsState globalSettings = getGlobalSettingsLocked();
2994 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2995 * }
2996 *
2997 * // Update the current version.
2998 * currentVersion = 119;
2999 * }
3000 */
Svetoslav683914b2015-01-15 14:22:26 -08003001 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3002 if (DEBUG) {
3003 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3004 + oldVersion + " to version: " + newVersion);
3005 }
3006
Jeff Brown503cffc2015-03-26 18:08:51 -07003007 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003008
John Spurlocke11ae112015-05-11 16:09:03 -04003009 // v119: Reset zen + ringer mode.
3010 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003011 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003012 final SettingsState globalSettings = getGlobalSettingsLocked();
3013 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003014 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3015 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003016 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003017 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3018 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003019 }
3020 currentVersion = 119;
3021 }
3022
Jason Monk27bbb2d2015-03-31 16:46:39 -04003023 // v120: Add double tap to wake setting.
3024 if (currentVersion == 119) {
3025 SettingsState secureSettings = getSecureSettingsLocked(userId);
3026 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3027 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003028 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003029 SettingsState.SYSTEM_PACKAGE_NAME);
3030
3031 currentVersion = 120;
3032 }
3033
Svetoslav7e0683b2015-08-03 16:02:52 -07003034 if (currentVersion == 120) {
3035 // Before 121, we used a different string encoding logic. We just bump the
3036 // version here; SettingsState knows how to handle pre-version 120 files.
3037 currentVersion = 121;
3038 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003039
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003040 if (currentVersion == 121) {
3041 // Version 122: allow OEMs to set a default payment component in resources.
3042 // Note that we only write the default if no default has been set;
3043 // if there is, we just leave the default at whatever it currently is.
3044 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3045 String defaultComponent = (getContext().getResources().getString(
3046 R.string.def_nfc_payment_component));
3047 Setting currentSetting = secureSettings.getSettingLocked(
3048 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3049 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003050 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003051 secureSettings.insertSettingLocked(
3052 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003053 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003054 }
3055 currentVersion = 122;
3056 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003057
3058 if (currentVersion == 122) {
3059 // Version 123: Adding a default value for the ability to add a user from
3060 // the lock screen.
3061 if (userId == UserHandle.USER_SYSTEM) {
3062 final SettingsState globalSettings = getGlobalSettingsLocked();
3063 Setting currentSetting = globalSettings.getSettingLocked(
3064 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003065 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003066 globalSettings.insertSettingLocked(
3067 Settings.Global.ADD_USERS_WHEN_LOCKED,
3068 getContext().getResources().getBoolean(
3069 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003070 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003071 }
3072 }
3073 currentVersion = 123;
3074 }
Bryce Leebd179282015-12-17 19:01:37 -08003075
3076 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003077 final SettingsState globalSettings = getGlobalSettingsLocked();
3078 String defaultDisabledProfiles = (getContext().getResources().getString(
3079 R.string.def_bluetooth_disabled_profiles));
3080 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003081 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003082 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003083 }
3084
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003085 if (currentVersion == 124) {
3086 // Version 124: allow OEMs to set a default value for whether IME should be
3087 // shown when a physical keyboard is connected.
3088 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3089 Setting currentSetting = secureSettings.getSettingLocked(
3090 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003091 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003092 secureSettings.insertSettingLocked(
3093 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3094 getContext().getResources().getBoolean(
3095 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003096 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003097 }
3098 currentVersion = 125;
3099 }
3100
Ruben Brunk98576cf2016-03-07 18:54:28 -08003101 if (currentVersion == 125) {
3102 // Version 125: Allow OEMs to set the default VR service.
3103 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3104
3105 Setting currentSetting = secureSettings.getSettingLocked(
3106 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003107 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003108 ArraySet<ComponentName> l =
3109 SystemConfig.getInstance().getDefaultVrComponents();
3110
3111 if (l != null && !l.isEmpty()) {
3112 StringBuilder b = new StringBuilder();
3113 boolean start = true;
3114 for (ComponentName c : l) {
3115 if (!start) {
3116 b.append(':');
3117 }
3118 b.append(c.flattenToString());
3119 start = false;
3120 }
3121 secureSettings.insertSettingLocked(
3122 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003123 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003124 }
3125
3126 }
3127 currentVersion = 126;
3128 }
3129
Daniel U02ba6122016-04-01 18:41:42 +01003130 if (currentVersion == 126) {
3131 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3132 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3133 if (mUserManager.isManagedProfile(userId)) {
3134 final SettingsState systemSecureSettings =
3135 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3136
3137 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3138 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003139 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003140 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3141 secureSettings.insertSettingLocked(
3142 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003143 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003144 SettingsState.SYSTEM_PACKAGE_NAME);
3145 }
3146
3147 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3148 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003149 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003150 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3151 secureSettings.insertSettingLocked(
3152 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003153 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003154 SettingsState.SYSTEM_PACKAGE_NAME);
3155 }
3156 }
3157 currentVersion = 127;
3158 }
3159
Steven Ngdc20ba62016-04-26 18:19:04 +01003160 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003161 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003162 currentVersion = 128;
3163 }
3164
Julia Reynolds1f721e12016-07-11 08:50:58 -04003165 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003166 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003167 currentVersion = 129;
3168 }
3169
Dan Sandler71f85e92016-07-20 13:46:05 -04003170 if (currentVersion == 129) {
3171 // default longpress timeout changed from 500 to 400. If unchanged from the old
3172 // default, update to the new default.
3173 final SettingsState systemSecureSettings =
3174 getSecureSettingsLocked(userId);
3175 final String oldValue = systemSecureSettings.getSettingLocked(
3176 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3177 if (TextUtils.equals("500", oldValue)) {
3178 systemSecureSettings.insertSettingLocked(
3179 Settings.Secure.LONG_PRESS_TIMEOUT,
3180 String.valueOf(getContext().getResources().getInteger(
3181 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003182 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003183 }
3184 currentVersion = 130;
3185 }
3186
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003187 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003188 // Split Ambient settings
3189 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3190 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3191 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3192
3193 if (dozeExplicitlyDisabled) {
3194 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003195 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003196 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003197 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003198 }
3199 currentVersion = 131;
3200 }
3201
3202 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003203 // Initialize new multi-press timeout to default value
3204 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3205 final String oldValue = systemSecureSettings.getSettingLocked(
3206 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3207 if (TextUtils.equals(null, oldValue)) {
3208 systemSecureSettings.insertSettingLocked(
3209 Settings.Secure.MULTI_PRESS_TIMEOUT,
3210 String.valueOf(getContext().getResources().getInteger(
3211 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003212 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003213 }
3214
Adrian Roos69741a22016-10-21 14:49:17 -07003215 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003216 }
3217
Adrian Roos69741a22016-10-21 14:49:17 -07003218 if (currentVersion == 132) {
3219 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003220 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3221 String defaultSyncParentSounds = (getContext().getResources()
3222 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3223 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003224 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3225 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003226 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003227 }
3228
Adrian Roos69741a22016-10-21 14:49:17 -07003229 if (currentVersion == 133) {
3230 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003231 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3232 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3233 null) {
3234 String defaultEndButtonBehavior = Integer.toString(getContext()
3235 .getResources().getInteger(R.integer.def_end_button_behavior));
3236 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003237 defaultEndButtonBehavior, null, true,
3238 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003239 }
Adrian Roos69741a22016-10-21 14:49:17 -07003240 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003241 }
3242
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003243 if (currentVersion == 134) {
3244 // Remove setting that specifies if magnification values should be preserved.
3245 // This setting defaulted to true and never has a UI.
3246 getSecureSettingsLocked(userId).deleteSettingLocked(
3247 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3248 currentVersion = 135;
3249 }
3250
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003251 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003252 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003253 currentVersion = 136;
3254 }
3255
Mark Rathjend891f012017-01-19 04:10:37 +00003256 if (currentVersion == 136) {
3257 // Version 136: Store legacy SSAID for all apps currently installed on the
3258 // device as first step in migrating SSAID to be unique per application.
3259
3260 final boolean isUpgrade;
3261 try {
3262 isUpgrade = mPackageManager.isUpgrade();
3263 } catch (RemoteException e) {
3264 throw new IllegalStateException("Package manager not available");
3265 }
3266 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3267 // user data or first boot on a new device should use new ssaid generation.
3268 if (isUpgrade) {
3269 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003270 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3271 userId, Settings.Secure.ANDROID_ID);
3272 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3273 || legacySsaidSetting.getValue() == null) {
3274 throw new IllegalStateException("Legacy ssaid not accessible");
3275 }
3276 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003277
3278 // Fill each uid with the legacy ssaid to be backwards compatible.
3279 final List<PackageInfo> packages;
3280 try {
3281 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3282 } catch (RemoteException e) {
3283 throw new IllegalStateException("Package manager not available");
3284 }
3285
3286 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3287 for (PackageInfo info : packages) {
3288 // Check if the UID already has an entry in the table.
3289 final String uid = Integer.toString(info.applicationInfo.uid);
3290 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3291
3292 if (ssaid.isNull() || ssaid.getValue() == null) {
3293 // Android Id doesn't exist for this package so create it.
3294 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3295 info.packageName);
3296 }
3297 }
3298 }
3299
3300 currentVersion = 137;
3301 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003302 if (currentVersion == 137) {
3303 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3304 // default value set to 1. The user can no longer change the value of this
3305 // setting through the UI.
3306 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3307 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003308 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3309 && secureSetting.getSettingLocked(
3310 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3311
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003312 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3313 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003314 // For managed profiles with profile owners, DevicePolicyManagerService
3315 // may want to set the user restriction in this case
3316 secureSetting.insertSettingLocked(
3317 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3318 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003319 }
3320 currentVersion = 138;
3321 }
Mark Rathjend891f012017-01-19 04:10:37 +00003322
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003323 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003324 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003325 currentVersion = 139;
3326 }
3327
Phil Weaver385912e2017-02-10 10:06:56 -08003328 if (currentVersion == 139) {
3329 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3330 // the user can no longer change the value of this setting through the UI.
3331 // Force to true.
3332 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3333 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3334 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3335 currentVersion = 140;
3336 }
3337
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003338 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003339 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003340 currentVersion = 141;
3341 }
3342
Svet Ganov13701552017-02-23 12:45:17 -08003343 if (currentVersion == 141) {
Felipe Lemeff355092017-04-03 12:55:02 -07003344 // Version 142: We added the notion of a default and whether the system set
Svet Ganov13701552017-02-23 12:45:17 -08003345 // the setting. This is used for resetting the internal state and we need
3346 // to make sure this value is updated for the existing settings, otherwise
3347 // we would delete system set settings while they should stay unmodified.
3348 SettingsState globalSettings = getGlobalSettingsLocked();
3349 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3350 globalSettings.persistSyncLocked();
3351
3352 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3353 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3354 secureSettings.persistSyncLocked();
3355
3356 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3357 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3358 systemSettings.persistSyncLocked();
3359
3360 currentVersion = 142;
3361 }
3362
Stephen Chen5d0922f2017-03-27 10:28:04 -07003363 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003364 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003365 if (userId == UserHandle.USER_SYSTEM) {
3366 final SettingsState globalSettings = getGlobalSettingsLocked();
3367 Setting currentSetting = globalSettings.getSettingLocked(
3368 Settings.Global.WIFI_WAKEUP_ENABLED);
3369 if (currentSetting.isNull()) {
3370 globalSettings.insertSettingLocked(
3371 Settings.Global.WIFI_WAKEUP_ENABLED,
3372 getContext().getResources().getBoolean(
3373 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3374 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3375 }
3376 }
3377
3378 currentVersion = 143;
3379 }
3380
Felipe Lemeff355092017-04-03 12:55:02 -07003381 if (currentVersion == 143) {
3382 // Version 144: Set a default value for Autofill service.
3383 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3384 final Setting currentSetting = secureSettings
3385 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3386 if (currentSetting.isNull()) {
3387 final String defaultValue = getContext().getResources().getString(
3388 com.android.internal.R.string.config_defaultAutofillService);
3389 if (defaultValue != null) {
3390 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3391 + "for user " + userId);
3392 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3393 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3394 }
3395 }
3396
3397 currentVersion = 144;
3398 }
3399
Jeremy Joslin45caa252017-05-04 11:22:46 -07003400 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003401 // Version 145: Removed
3402 currentVersion = 145;
3403 }
3404
3405 if (currentVersion == 145) {
3406 // Version 146: Set the default value for WIFI_WAKEUP_AVAILABLE.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003407 if (userId == UserHandle.USER_SYSTEM) {
3408 final SettingsState globalSettings = getGlobalSettingsLocked();
3409 final Setting currentSetting = globalSettings.getSettingLocked(
3410 Settings.Global.WIFI_WAKEUP_AVAILABLE);
Amin Shaikh86367962017-06-07 08:58:22 -07003411 final int defaultValue = getContext().getResources().getInteger(
3412 com.android.internal.R.integer.config_wifi_wakeup_available);
3413 globalSettings.insertSettingLocked(
3414 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3415 String.valueOf(defaultValue),
3416 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Jeremy Joslin45caa252017-05-04 11:22:46 -07003417 }
3418
Amin Shaikh86367962017-06-07 08:58:22 -07003419 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003420 }
3421
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003422 if (currentVersion == 146) {
3423 // Version 146: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
3424 if (userId == UserHandle.USER_SYSTEM) {
3425 final SettingsState globalSettings = getGlobalSettingsLocked();
3426 final Setting currentSetting = globalSettings.getSettingLocked(
3427 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3428 if (currentSetting.isNull()) {
3429 globalSettings.insertSettingLocked(
3430 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3431 getContext().getResources().getBoolean(
3432 R.bool.def_restrict_background_data) ? "1" : "0",
3433 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3434 }
3435 }
3436 currentVersion = 147;
3437 }
3438
Felipe Lemeff355092017-04-03 12:55:02 -07003439 // vXXX: Add new settings above this point.
3440
Dan Sandler71f85e92016-07-20 13:46:05 -04003441 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003442 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003443 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003444 + currentVersion +
3445 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3446 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003447 if (DEBUG) {
3448 throw new RuntimeException("db upgrade error");
3449 }
3450 }
3451
Jeff Brown503cffc2015-03-26 18:08:51 -07003452 // Return the current version.
3453 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003454 }
3455 }
Svet Ganov13701552017-02-23 12:45:17 -08003456
3457 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3458 List<String> names = settings.getSettingNamesLocked();
3459 final int nameCount = names.size();
3460 for (int i = 0; i < nameCount; i++) {
3461 String name = names.get(i);
3462 Setting setting = settings.getSettingLocked(name);
3463 if (setting.getDefaultValue() == null) {
3464 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3465 setting.getPackageName());
3466 if (systemSet) {
3467 settings.insertSettingLocked(name, setting.getValue(),
3468 setting.getTag(), true, setting.getPackageName());
3469 }
3470 }
3471 }
3472 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003473 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003474}