blob: 04be92e73b381aeeaf96168d0fa80084d14aee9c [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 Brubakerb6108d62017-12-23 20:06:44 -08001690 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1691 // in the current form.
1692 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001693 }
1694
Chad Brubakera6830e72017-04-28 17:34:36 -07001695 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001696 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1697 return;
1698 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001699 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001700 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001701 return;
1702 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001703 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1704 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001705 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1706 // breakage in the current form.
1707 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1708 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001709 }
1710 }
1711
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001712 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1713 // We always use the callingUid for this lookup. This means that if hypothetically an
1714 // app was installed in user A with cross user and in user B as an Instant App
1715 // the app in A would be able to see all the settings in user B. However since cross
1716 // user is a system permission and the app must be uninstalled in B and then installed as
1717 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001718 ApplicationInfo ai = null;
1719 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001720 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1721 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001722 } catch (RemoteException ignored) {
1723 }
1724 if (ai == null) {
1725 throw new IllegalStateException("Failed to lookup info for package "
1726 + getCallingPackage());
1727 }
1728 return ai;
1729 }
1730
Xiaohui Chen43765b72015-08-31 10:57:33 -07001731 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001732 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001733 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1734 getCallingPackage(), 0, userId);
1735 if (packageInfo != null) {
1736 return packageInfo;
1737 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001738 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001739 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001740 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001741 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001742 }
1743
1744 private int getGroupParentLocked(int userId) {
1745 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001746 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001747 return userId;
1748 }
1749 // We are in the same process with the user manager and the returned
1750 // user info is a cached instance, so just look up instead of cache.
1751 final long identity = Binder.clearCallingIdentity();
1752 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001753 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001754 UserInfo userInfo = mUserManager.getProfileParent(userId);
1755 return (userInfo != null) ? userInfo.id : userId;
1756 } finally {
1757 Binder.restoreCallingIdentity(identity);
1758 }
1759 }
1760
Svetoslav683914b2015-01-15 14:22:26 -08001761 private void enforceWritePermission(String permission) {
1762 if (getContext().checkCallingOrSelfPermission(permission)
1763 != PackageManager.PERMISSION_GRANTED) {
1764 throw new SecurityException("Permission denial: writing to settings requires:"
1765 + permission);
1766 }
1767 }
1768
1769 /*
1770 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1771 * This setting contains a list of the currently enabled location providers.
1772 * But helper functions in android.providers.Settings can enable or disable
1773 * a single provider by using a "+" or "-" prefix before the provider name.
1774 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001775 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1776 * is set, the said method will only allow values with the "-" prefix.
1777 *
Svetoslav683914b2015-01-15 14:22:26 -08001778 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001779 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001780 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1781 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001782 if (TextUtils.isEmpty(value)) {
1783 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001784 }
1785
Svetoslav683914b2015-01-15 14:22:26 -08001786 final char prefix = value.charAt(0);
1787 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001788 if (forceNotify) {
1789 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1790 mSettingsRegistry.notifyForSettingsChange(key,
1791 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1792 }
Svetoslav683914b2015-01-15 14:22:26 -08001793 return false;
1794 }
1795
1796 // skip prefix
1797 value = value.substring(1);
1798
Svetoslav7ec28e82015-05-20 17:01:10 -07001799 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001800 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001801 if (settingValue == null) {
1802 return false;
1803 }
Svetoslav683914b2015-01-15 14:22:26 -08001804
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001805 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001806
1807 int index = oldProviders.indexOf(value);
1808 int end = index + value.length();
1809
1810 // check for commas to avoid matching on partial string
1811 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1812 index = -1;
1813 }
1814
1815 // check for commas to avoid matching on partial string
1816 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1817 index = -1;
1818 }
1819
1820 String newProviders;
1821
1822 if (prefix == '+' && index < 0) {
1823 // append the provider to the list if not present
1824 if (oldProviders.length() == 0) {
1825 newProviders = value;
1826 } else {
1827 newProviders = oldProviders + ',' + value;
1828 }
1829 } else if (prefix == '-' && index >= 0) {
1830 // remove the provider from the list if present
1831 // remove leading or trailing comma
1832 if (index > 0) {
1833 index--;
1834 } else if (end < oldProviders.length()) {
1835 end++;
1836 }
1837
1838 newProviders = oldProviders.substring(0, index);
1839 if (end < oldProviders.length()) {
1840 newProviders += oldProviders.substring(end);
1841 }
1842 } else {
1843 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001844 if (forceNotify) {
1845 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1846 mSettingsRegistry.notifyForSettingsChange(key,
1847 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1848 }
Svetoslav683914b2015-01-15 14:22:26 -08001849 return false;
1850 }
1851
Svet Ganov53a441c2016-04-19 19:38:00 -07001852 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001853 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001854 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001855 }
1856
Svetoslav683914b2015-01-15 14:22:26 -08001857 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1858 int targetSdkVersion, String name) {
1859 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1860 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1861 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1862 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1863 + " This will soon become an error.");
1864 } else {
1865 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1866 + " This will soon become an error.");
1867 }
1868 } else {
1869 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1870 throw new IllegalArgumentException("You cannot change private secure settings.");
1871 } else {
1872 throw new IllegalArgumentException("You cannot keep your settings in"
1873 + " the secure settings.");
1874 }
1875 }
1876 }
1877
1878 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1879 if (requestingUserId == UserHandle.getCallingUserId()) {
1880 return requestingUserId;
1881 }
1882 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1883 Binder.getCallingUid(), requestingUserId, false, true,
1884 "get/set setting for user", null);
1885 }
1886
Svet Ganov53a441c2016-04-19 19:38:00 -07001887 private Bundle packageValueForCallResult(Setting setting,
1888 boolean trackingGeneration) {
1889 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001890 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001891 return NULL_SETTING_BUNDLE;
1892 }
1893 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001894 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001895 Bundle result = new Bundle();
1896 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001897 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001898
Svetoslav Ganove080da92016-12-21 17:10:35 -08001899 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001900 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001901 }
1902
1903 private static int getRequestingUserId(Bundle args) {
1904 final int callingUserId = UserHandle.getCallingUserId();
1905 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1906 : callingUserId;
1907 }
1908
Svet Ganov53a441c2016-04-19 19:38:00 -07001909 private boolean isTrackingGeneration(Bundle args) {
1910 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1911 }
1912
Svetoslav683914b2015-01-15 14:22:26 -08001913 private static String getSettingValue(Bundle args) {
1914 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1915 }
1916
Svetoslav Ganove080da92016-12-21 17:10:35 -08001917 private static String getSettingTag(Bundle args) {
1918 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1919 }
1920
1921 private static boolean getSettingMakeDefault(Bundle args) {
1922 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1923 }
1924
1925 private static int getResetModeEnforcingPermission(Bundle args) {
1926 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1927 switch (mode) {
1928 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1929 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1930 throw new SecurityException("Only system, shell/root on a "
1931 + "debuggable build can reset to untrusted defaults");
1932 }
1933 return mode;
1934 }
1935 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1936 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1937 throw new SecurityException("Only system, shell/root on a "
1938 + "debuggable build can reset untrusted changes");
1939 }
1940 return mode;
1941 }
1942 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1943 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1944 throw new SecurityException("Only system, shell/root on a "
1945 + "debuggable build can reset to trusted defaults");
1946 }
1947 return mode;
1948 }
1949 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1950 return mode;
1951 }
1952 }
1953 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1954 }
1955
1956 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1957 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1958 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1959 && (appId == SHELL_UID || appId == ROOT_UID));
1960 }
1961
Svetoslav683914b2015-01-15 14:22:26 -08001962 private static String getValidTableOrThrow(Uri uri) {
1963 if (uri.getPathSegments().size() > 0) {
1964 String table = uri.getPathSegments().get(0);
1965 if (DatabaseHelper.isValidTable(table)) {
1966 return table;
1967 }
1968 throw new IllegalArgumentException("Bad root path: " + table);
1969 }
1970 throw new IllegalArgumentException("Invalid URI:" + uri);
1971 }
1972
1973 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001974 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001975 return new MatrixCursor(projection, 0);
1976 }
1977 MatrixCursor cursor = new MatrixCursor(projection, 1);
1978 appendSettingToCursor(cursor, setting);
1979 return cursor;
1980 }
1981
1982 private static String[] normalizeProjection(String[] projection) {
1983 if (projection == null) {
1984 return ALL_COLUMNS;
1985 }
1986
1987 final int columnCount = projection.length;
1988 for (int i = 0; i < columnCount; i++) {
1989 String column = projection[i];
1990 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1991 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001992 }
1993 }
1994
Svetoslav683914b2015-01-15 14:22:26 -08001995 return projection;
1996 }
1997
1998 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001999 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002000 return;
2001 }
Svetoslav683914b2015-01-15 14:22:26 -08002002 final int columnCount = cursor.getColumnCount();
2003
2004 String[] values = new String[columnCount];
2005
2006 for (int i = 0; i < columnCount; i++) {
2007 String column = cursor.getColumnName(i);
2008
2009 switch (column) {
2010 case Settings.NameValueTable._ID: {
2011 values[i] = setting.getId();
2012 } break;
2013
2014 case Settings.NameValueTable.NAME: {
2015 values[i] = setting.getName();
2016 } break;
2017
2018 case Settings.NameValueTable.VALUE: {
2019 values[i] = setting.getValue();
2020 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002021 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002022 }
2023
Svetoslav683914b2015-01-15 14:22:26 -08002024 cursor.addRow(values);
2025 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002026
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002027 private static boolean isKeyValid(String key) {
2028 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2029 }
2030
Svetoslav683914b2015-01-15 14:22:26 -08002031 private static final class Arguments {
2032 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2033 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2034
2035 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2036 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2037
2038 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2039 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2040
2041 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2042 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2043
2044 public final String table;
2045 public final String name;
2046
2047 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2048 final int segmentSize = uri.getPathSegments().size();
2049 switch (segmentSize) {
2050 case 1: {
2051 if (where != null
2052 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2053 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2054 && whereArgs.length == 1) {
2055 name = whereArgs[0];
2056 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002057 return;
Svetoslav683914b2015-01-15 14:22:26 -08002058 } else if (where != null
2059 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2060 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2061 final int startIndex = Math.max(where.indexOf("'"),
2062 where.indexOf("\"")) + 1;
2063 final int endIndex = Math.max(where.lastIndexOf("'"),
2064 where.lastIndexOf("\""));
2065 name = where.substring(startIndex, endIndex);
2066 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002067 return;
Svetoslav683914b2015-01-15 14:22:26 -08002068 } else if (supportAll && where == null && whereArgs == null) {
2069 name = null;
2070 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002071 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002072 }
Svetoslav683914b2015-01-15 14:22:26 -08002073 } break;
2074
Svetoslav28494652015-02-12 14:11:42 -08002075 case 2: {
2076 if (where == null && whereArgs == null) {
2077 name = uri.getPathSegments().get(1);
2078 table = computeTableForSetting(uri, name);
2079 return;
2080 }
2081 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002082 }
Svetoslav28494652015-02-12 14:11:42 -08002083
2084 EventLogTags.writeUnsupportedSettingsQuery(
2085 uri.toSafeString(), where, Arrays.toString(whereArgs));
2086 String message = String.format( "Supported SQL:\n"
2087 + " uri content://some_table/some_property with null where and where args\n"
2088 + " uri content://some_table with query name=? and single name as arg\n"
2089 + " uri content://some_table with query name=some_name and null args\n"
2090 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2091 Arrays.toString(whereArgs));
2092 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002093 }
2094
Svetoslav28494652015-02-12 14:11:42 -08002095 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002096 String table = getValidTableOrThrow(uri);
2097
2098 if (name != null) {
2099 if (sSystemMovedToSecureSettings.contains(name)) {
2100 table = TABLE_SECURE;
2101 }
2102
2103 if (sSystemMovedToGlobalSettings.contains(name)) {
2104 table = TABLE_GLOBAL;
2105 }
2106
2107 if (sSecureMovedToGlobalSettings.contains(name)) {
2108 table = TABLE_GLOBAL;
2109 }
2110
2111 if (sGlobalMovedToSecureSettings.contains(name)) {
2112 table = TABLE_SECURE;
2113 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002114 }
Svetoslav683914b2015-01-15 14:22:26 -08002115
2116 return table;
2117 }
2118 }
2119
2120 final class SettingsRegistry {
2121 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2122
Svetoslav683914b2015-01-15 14:22:26 -08002123 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2124 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2125 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002126 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2127
2128 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002129
2130 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2131
Svet Ganov53a441c2016-04-19 19:38:00 -07002132 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002133
Svetoslav7e0683b2015-08-03 16:02:52 -07002134 private final Handler mHandler;
2135
Svet Ganov53a441c2016-04-19 19:38:00 -07002136 private final BackupManager mBackupManager;
2137
Amith Yamasani39452022017-03-21 15:23:47 -07002138 private String mSettingsCreationBuildId;
2139
Svetoslav683914b2015-01-15 14:22:26 -08002140 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002141 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002142 mGenerationRegistry = new GenerationRegistry(mLock);
2143 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002144 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002145 syncSsaidTableOnStart();
2146 }
2147
2148 private void generateUserKeyLocked(int userId) {
2149 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002150 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002151 final SecureRandom rand = new SecureRandom();
2152 rand.nextBytes(keyBytes);
2153
2154 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002155 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002156
2157 // Store the key in the ssaid table.
2158 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2159 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2160 true, SettingsState.SYSTEM_PACKAGE_NAME);
2161
2162 if (!success) {
2163 throw new IllegalStateException("Ssaid settings not accessible");
2164 }
2165 }
2166
Mark Rathjen7599f132017-01-23 14:15:54 -08002167 private byte[] getLengthPrefix(byte[] data) {
2168 return ByteBuffer.allocate(4).putInt(data.length).array();
2169 }
2170
Christopher Tateb218e762017-04-05 16:34:07 -07002171 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002172 // Read the user's key from the ssaid table.
2173 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002174 if (userKeySetting == null || userKeySetting.isNull()
2175 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002176 // Lazy initialize and store the user key.
2177 generateUserKeyLocked(userId);
2178 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002179 if (userKeySetting == null || userKeySetting.isNull()
2180 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002181 throw new IllegalStateException("User key not accessible");
2182 }
2183 }
2184 final String userKey = userKeySetting.getValue();
2185
2186 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002187 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2188
2189 // Validate that the key is of expected length.
2190 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2191 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002192 throw new IllegalStateException("User key invalid");
2193 }
2194
Mark Rathjen7599f132017-01-23 14:15:54 -08002195 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002196 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002197 m = Mac.getInstance("HmacSHA256");
2198 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002199 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002200 throw new IllegalStateException("HmacSHA256 is not available", e);
2201 } catch (InvalidKeyException e) {
2202 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002203 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002204
Mark Rathjenf42dd912017-06-05 19:04:34 -07002205 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002206 for (int i = 0; i < callingPkg.signatures.length; i++) {
2207 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002208 m.update(getLengthPrefix(sig), 0, 4);
2209 m.update(sig);
2210 }
Mark Rathjend891f012017-01-19 04:10:37 +00002211
2212 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002213 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2214 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002215
2216 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002217 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002218 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2219 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002220 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002221
2222 if (!success) {
2223 throw new IllegalStateException("Ssaid settings not accessible");
2224 }
2225
2226 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2227 }
2228
2229 public void syncSsaidTableOnStart() {
2230 synchronized (mLock) {
2231 // Verify that each user's packages and ssaid's are in sync.
2232 for (UserInfo user : mUserManager.getUsers(true)) {
2233 // Get all uids for the user's packages.
2234 final List<PackageInfo> packages;
2235 try {
2236 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2237 } catch (RemoteException e) {
2238 throw new IllegalStateException("Package manager not available");
2239 }
2240 final Set<String> appUids = new HashSet<>();
2241 for (PackageInfo info : packages) {
2242 appUids.add(Integer.toString(info.applicationInfo.uid));
2243 }
2244
2245 // Get all uids currently stored in the user's ssaid table.
2246 final Set<String> ssaidUids = new HashSet<>(
2247 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2248 ssaidUids.remove(SSAID_USER_KEY);
2249
2250 // Perform a set difference for the appUids and ssaidUids.
2251 ssaidUids.removeAll(appUids);
2252
2253 // If there are ssaidUids left over they need to be removed from the table.
2254 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2255 user.id);
2256 for (String uid : ssaidUids) {
2257 ssaidSettings.deleteSettingLocked(uid);
2258 }
2259 }
2260 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002261 }
2262
Svetoslav683914b2015-01-15 14:22:26 -08002263 public List<String> getSettingsNamesLocked(int type, int userId) {
2264 final int key = makeKey(type, userId);
2265 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002266 if (settingsState == null) {
2267 return new ArrayList<String>();
2268 }
Svetoslav683914b2015-01-15 14:22:26 -08002269 return settingsState.getSettingNamesLocked();
2270 }
2271
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002272 public SparseBooleanArray getKnownUsersLocked() {
2273 SparseBooleanArray users = new SparseBooleanArray();
2274 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2275 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2276 }
2277 return users;
2278 }
2279
Svetoslav683914b2015-01-15 14:22:26 -08002280 public SettingsState getSettingsLocked(int type, int userId) {
2281 final int key = makeKey(type, userId);
2282 return peekSettingsStateLocked(key);
2283 }
2284
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002285 public boolean ensureSettingsForUserLocked(int userId) {
2286 // First make sure this user actually exists.
2287 if (mUserManager.getUserInfo(userId) == null) {
2288 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2289 return false;
2290 }
2291
Svetoslav683914b2015-01-15 14:22:26 -08002292 // Migrate the setting for this user if needed.
2293 migrateLegacySettingsForUserIfNeededLocked(userId);
2294
2295 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002296 if (userId == UserHandle.USER_SYSTEM) {
2297 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002298 ensureSettingsStateLocked(globalKey);
2299 }
2300
2301 // Ensure secure settings loaded.
2302 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2303 ensureSettingsStateLocked(secureKey);
2304
2305 // Make sure the secure settings have an Android id set.
2306 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2307 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2308
2309 // Ensure system settings loaded.
2310 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2311 ensureSettingsStateLocked(systemKey);
2312
Mark Rathjend891f012017-01-19 04:10:37 +00002313 // Ensure secure settings loaded.
2314 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2315 ensureSettingsStateLocked(ssaidKey);
2316
Svetoslav683914b2015-01-15 14:22:26 -08002317 // Upgrade the settings to the latest version.
2318 UpgradeController upgrader = new UpgradeController(userId);
2319 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002320 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002321 }
2322
2323 private void ensureSettingsStateLocked(int key) {
2324 if (mSettingsStates.get(key) == null) {
2325 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002326 SettingsState settingsState = new SettingsState(getContext(), mLock,
2327 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002328 mSettingsStates.put(key, settingsState);
2329 }
2330 }
2331
2332 public void removeUserStateLocked(int userId, boolean permanently) {
2333 // We always keep the global settings in memory.
2334
2335 // Nuke system settings.
2336 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2337 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2338 if (systemSettingsState != null) {
2339 if (permanently) {
2340 mSettingsStates.remove(systemKey);
2341 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002342 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002343 systemSettingsState.destroyLocked(new Runnable() {
2344 @Override
2345 public void run() {
2346 mSettingsStates.remove(systemKey);
2347 }
2348 });
2349 }
2350 }
2351
2352 // Nuke secure settings.
2353 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2354 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2355 if (secureSettingsState != null) {
2356 if (permanently) {
2357 mSettingsStates.remove(secureKey);
2358 secureSettingsState.destroyLocked(null);
2359 } else {
2360 secureSettingsState.destroyLocked(new Runnable() {
2361 @Override
2362 public void run() {
2363 mSettingsStates.remove(secureKey);
2364 }
2365 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002366 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002367 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002368
Mark Rathjend891f012017-01-19 04:10:37 +00002369 // Nuke ssaid settings.
2370 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2371 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2372 if (ssaidSettingsState != null) {
2373 if (permanently) {
2374 mSettingsStates.remove(ssaidKey);
2375 ssaidSettingsState.destroyLocked(null);
2376 } else {
2377 ssaidSettingsState.destroyLocked(new Runnable() {
2378 @Override
2379 public void run() {
2380 mSettingsStates.remove(ssaidKey);
2381 }
2382 });
2383 }
2384 }
2385
Svet Ganov53a441c2016-04-19 19:38:00 -07002386 // Nuke generation tracking data
2387 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002388 }
2389
Svetoslav683914b2015-01-15 14:22:26 -08002390 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002391 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2392 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002393 final int key = makeKey(type, userId);
2394
Svetoslav Ganove080da92016-12-21 17:10:35 -08002395 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002396 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002397 if (settingsState != null) {
2398 success = settingsState.insertSettingLocked(name, value,
2399 tag, makeDefault, packageName);
2400 }
Svetoslav683914b2015-01-15 14:22:26 -08002401
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002402 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2403 settingsState.persistSyncLocked();
2404 }
2405
Svet Ganov53a441c2016-04-19 19:38:00 -07002406 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002407 notifyForSettingsChange(key, name);
2408 }
2409 return success;
2410 }
2411
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002412 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2413 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002414 final int key = makeKey(type, userId);
2415
Svetoslav Ganove080da92016-12-21 17:10:35 -08002416 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002417 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002418 if (settingsState != null) {
2419 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002420 }
Svetoslav683914b2015-01-15 14:22:26 -08002421
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002422 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2423 settingsState.persistSyncLocked();
2424 }
2425
Svet Ganov53a441c2016-04-19 19:38:00 -07002426 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002427 notifyForSettingsChange(key, name);
2428 }
2429 return success;
2430 }
2431
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002432 public boolean updateSettingLocked(int type, int userId, String name, String value,
2433 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2434 Set<String> criticalSettings) {
2435 final int key = makeKey(type, userId);
2436
2437 boolean success = false;
2438 SettingsState settingsState = peekSettingsStateLocked(key);
2439 if (settingsState != null) {
2440 success = settingsState.updateSettingLocked(name, value, tag,
2441 makeDefault, packageName);
2442 }
2443
2444 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2445 settingsState.persistSyncLocked();
2446 }
2447
2448 if (forceNotify || success) {
2449 notifyForSettingsChange(key, name);
2450 }
2451
2452 return success;
2453 }
2454
Svetoslav683914b2015-01-15 14:22:26 -08002455 public Setting getSettingLocked(int type, int userId, String name) {
2456 final int key = makeKey(type, userId);
2457
2458 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002459 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002460 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002461 }
Mark Rathjend891f012017-01-19 04:10:37 +00002462
2463 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002464 return settingsState.getSettingLocked(name);
2465 }
2466
Svetoslav Ganove080da92016-12-21 17:10:35 -08002467 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2468 String tag) {
2469 final int key = makeKey(type, userId);
2470 SettingsState settingsState = peekSettingsStateLocked(key);
2471 if (settingsState == null) {
2472 return;
2473 }
2474
2475 switch (mode) {
2476 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2477 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002478 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002479 Setting setting = settingsState.getSettingLocked(name);
2480 if (packageName.equals(setting.getPackageName())) {
2481 if (tag != null && !tag.equals(setting.getTag())) {
2482 continue;
2483 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002484 if (settingsState.resetSettingLocked(name)) {
2485 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002486 notifyForSettingsChange(key, name);
2487 }
2488 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002489 if (someSettingChanged) {
2490 settingsState.persistSyncLocked();
2491 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002492 }
2493 } break;
2494
2495 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2496 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002497 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002498 Setting setting = settingsState.getSettingLocked(name);
2499 if (!SettingsState.isSystemPackage(getContext(),
2500 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002501 if (settingsState.resetSettingLocked(name)) {
2502 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002503 notifyForSettingsChange(key, name);
2504 }
2505 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002506 if (someSettingChanged) {
2507 settingsState.persistSyncLocked();
2508 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002509 }
2510 } break;
2511
2512 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2513 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002514 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002515 Setting setting = settingsState.getSettingLocked(name);
2516 if (!SettingsState.isSystemPackage(getContext(),
2517 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002518 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002519 if (settingsState.resetSettingLocked(name)) {
2520 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002521 notifyForSettingsChange(key, name);
2522 }
2523 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002524 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002525 notifyForSettingsChange(key, name);
2526 }
2527 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002528 if (someSettingChanged) {
2529 settingsState.persistSyncLocked();
2530 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002531 }
2532 } break;
2533
2534 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2535 for (String name : settingsState.getSettingNamesLocked()) {
2536 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002537 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002538 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002539 if (settingsState.resetSettingLocked(name)) {
2540 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002541 notifyForSettingsChange(key, name);
2542 }
2543 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002544 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002545 notifyForSettingsChange(key, name);
2546 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002547 if (someSettingChanged) {
2548 settingsState.persistSyncLocked();
2549 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002550 }
2551 } break;
2552 }
2553 }
2554
Svetoslav683914b2015-01-15 14:22:26 -08002555 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002556 // Global and secure settings are signature protected. Apps signed
2557 // by the platform certificate are generally not uninstalled and
2558 // the main exception is tests. We trust components signed
2559 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002560
2561 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2562 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002563 if (systemSettings != null) {
2564 systemSettings.onPackageRemovedLocked(packageName);
2565 }
Svetoslav683914b2015-01-15 14:22:26 -08002566 }
2567
Mark Rathjend891f012017-01-19 04:10:37 +00002568 public void onUidRemovedLocked(int uid) {
2569 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2570 UserHandle.getUserId(uid));
2571 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2572 }
2573
Svetoslav683914b2015-01-15 14:22:26 -08002574 private SettingsState peekSettingsStateLocked(int key) {
2575 SettingsState settingsState = mSettingsStates.get(key);
2576 if (settingsState != null) {
2577 return settingsState;
2578 }
2579
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002580 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2581 return null;
2582 }
Svetoslav683914b2015-01-15 14:22:26 -08002583 return mSettingsStates.get(key);
2584 }
2585
2586 private void migrateAllLegacySettingsIfNeeded() {
2587 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002588 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002589 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002590 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002591 return;
2592 }
2593
Amith Yamasani39452022017-03-21 15:23:47 -07002594 mSettingsCreationBuildId = Build.ID;
2595
Svetoslav683914b2015-01-15 14:22:26 -08002596 final long identity = Binder.clearCallingIdentity();
2597 try {
2598 List<UserInfo> users = mUserManager.getUsers(true);
2599
2600 final int userCount = users.size();
2601 for (int i = 0; i < userCount; i++) {
2602 final int userId = users.get(i).id;
2603
2604 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2605 SQLiteDatabase database = dbHelper.getWritableDatabase();
2606 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2607
2608 // Upgrade to the latest version.
2609 UpgradeController upgrader = new UpgradeController(userId);
2610 upgrader.upgradeIfNeededLocked();
2611
2612 // Drop from memory if not a running user.
2613 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2614 removeUserStateLocked(userId, false);
2615 }
2616 }
2617 } finally {
2618 Binder.restoreCallingIdentity(identity);
2619 }
2620 }
2621 }
2622
2623 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2624 // Every user has secure settings and if no file we need to migrate.
2625 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2626 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002627 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002628 return;
2629 }
2630
2631 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2632 SQLiteDatabase database = dbHelper.getWritableDatabase();
2633
2634 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2635 }
2636
2637 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2638 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002639 // Move over the system settings.
2640 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2641 ensureSettingsStateLocked(systemKey);
2642 SettingsState systemSettings = mSettingsStates.get(systemKey);
2643 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2644 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002645
2646 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002647 // Do this after System settings, since this is the first thing we check when deciding
2648 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002649 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2650 ensureSettingsStateLocked(secureKey);
2651 SettingsState secureSettings = mSettingsStates.get(secureKey);
2652 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2653 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2654 secureSettings.persistSyncLocked();
2655
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002656 // Move over the global settings if owner.
2657 // Do this last, since this is the first thing we check when deciding
2658 // to skip over migration from db to xml for owner user.
2659 if (userId == UserHandle.USER_SYSTEM) {
2660 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2661 ensureSettingsStateLocked(globalKey);
2662 SettingsState globalSettings = mSettingsStates.get(globalKey);
2663 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002664 // If this was just created
2665 if (mSettingsCreationBuildId != null) {
2666 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2667 mSettingsCreationBuildId, null, true,
2668 SettingsState.SYSTEM_PACKAGE_NAME);
2669 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002670 globalSettings.persistSyncLocked();
2671 }
Svetoslav683914b2015-01-15 14:22:26 -08002672
2673 // Drop the database as now all is moved and persisted.
2674 if (DROP_DATABASE_ON_MIGRATION) {
2675 dbHelper.dropDatabase();
2676 } else {
2677 dbHelper.backupDatabase();
2678 }
2679 }
2680
2681 private void migrateLegacySettingsLocked(SettingsState settingsState,
2682 SQLiteDatabase database, String table) {
2683 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2684 queryBuilder.setTables(table);
2685
2686 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2687 null, null, null, null, null);
2688
2689 if (cursor == null) {
2690 return;
2691 }
2692
2693 try {
2694 if (!cursor.moveToFirst()) {
2695 return;
2696 }
2697
2698 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2699 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2700
2701 settingsState.setVersionLocked(database.getVersion());
2702
2703 while (!cursor.isAfterLast()) {
2704 String name = cursor.getString(nameColumnIdx);
2705 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002706 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002707 SettingsState.SYSTEM_PACKAGE_NAME);
2708 cursor.moveToNext();
2709 }
2710 } finally {
2711 cursor.close();
2712 }
2713 }
2714
2715 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2716 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2717
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002718 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002719 return;
2720 }
2721
2722 final int userId = getUserIdFromKey(secureSettings.mKey);
2723
2724 final UserInfo user;
2725 final long identity = Binder.clearCallingIdentity();
2726 try {
2727 user = mUserManager.getUserInfo(userId);
2728 } finally {
2729 Binder.restoreCallingIdentity(identity);
2730 }
2731 if (user == null) {
2732 // Can happen due to races when deleting users - treat as benign.
2733 return;
2734 }
2735
2736 String androidId = Long.toHexString(new SecureRandom().nextLong());
2737 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002738 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002739
2740 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2741 + "] for user " + userId);
2742
2743 // Write a drop box entry if it's a restricted profile
2744 if (user.isRestricted()) {
2745 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2746 Context.DROPBOX_SERVICE);
2747 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2748 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2749 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2750 }
2751 }
2752 }
2753
2754 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002755 final int userId = getUserIdFromKey(key);
2756 Uri uri = getNotificationUriFor(key, name);
2757
Phil Weaver83fec002016-05-11 10:55:29 -07002758 mGenerationRegistry.incrementGeneration(key);
2759
Svetoslav7e0683b2015-08-03 16:02:52 -07002760 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2761 userId, 0, uri).sendToTarget();
2762
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002763 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002764 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2765 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002766 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2767 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002768 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002769 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2770 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002771 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002772
Svet Ganov53a441c2016-04-19 19:38:00 -07002773 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002774 }
2775
Svet Ganov53a441c2016-04-19 19:38:00 -07002776 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002777 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002778 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002779 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002780 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002781 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002782 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002783 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002784 final int key = makeKey(type, profileId);
2785 mGenerationRegistry.incrementGeneration(key);
2786
2787 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002788 }
2789 }
2790 }
Svetoslav683914b2015-01-15 14:22:26 -08002791 }
2792
Svetoslav683914b2015-01-15 14:22:26 -08002793 private boolean isGlobalSettingsKey(int key) {
2794 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2795 }
2796
2797 private boolean isSystemSettingsKey(int key) {
2798 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2799 }
2800
2801 private boolean isSecureSettingsKey(int key) {
2802 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2803 }
2804
Mark Rathjend891f012017-01-19 04:10:37 +00002805 private boolean isSsaidSettingsKey(int key) {
2806 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2807 }
2808
Svetoslav683914b2015-01-15 14:22:26 -08002809 private File getSettingsFile(int key) {
2810 if (isGlobalSettingsKey(key)) {
2811 final int userId = getUserIdFromKey(key);
2812 return new File(Environment.getUserSystemDirectory(userId),
2813 SETTINGS_FILE_GLOBAL);
2814 } else if (isSystemSettingsKey(key)) {
2815 final int userId = getUserIdFromKey(key);
2816 return new File(Environment.getUserSystemDirectory(userId),
2817 SETTINGS_FILE_SYSTEM);
2818 } else if (isSecureSettingsKey(key)) {
2819 final int userId = getUserIdFromKey(key);
2820 return new File(Environment.getUserSystemDirectory(userId),
2821 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002822 } else if (isSsaidSettingsKey(key)) {
2823 final int userId = getUserIdFromKey(key);
2824 return new File(Environment.getUserSystemDirectory(userId),
2825 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002826 } else {
2827 throw new IllegalArgumentException("Invalid settings key:" + key);
2828 }
2829 }
2830
2831 private Uri getNotificationUriFor(int key, String name) {
2832 if (isGlobalSettingsKey(key)) {
2833 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2834 : Settings.Global.CONTENT_URI;
2835 } else if (isSecureSettingsKey(key)) {
2836 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2837 : Settings.Secure.CONTENT_URI;
2838 } else if (isSystemSettingsKey(key)) {
2839 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2840 : Settings.System.CONTENT_URI;
2841 } else {
2842 throw new IllegalArgumentException("Invalid settings key:" + key);
2843 }
2844 }
2845
2846 private int getMaxBytesPerPackageForType(int type) {
2847 switch (type) {
2848 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002849 case SETTINGS_TYPE_SECURE:
2850 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002851 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2852 }
2853
2854 default: {
2855 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2856 }
2857 }
2858 }
2859
Svetoslav7e0683b2015-08-03 16:02:52 -07002860 private final class MyHandler extends Handler {
2861 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2862 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2863
2864 public MyHandler(Looper looper) {
2865 super(looper);
2866 }
2867
2868 @Override
2869 public void handleMessage(Message msg) {
2870 switch (msg.what) {
2871 case MSG_NOTIFY_URI_CHANGED: {
2872 final int userId = msg.arg1;
2873 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002874 try {
2875 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2876 } catch (SecurityException e) {
2877 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2878 }
Svetoslav7e0683b2015-08-03 16:02:52 -07002879 if (DEBUG) {
2880 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2881 }
2882 } break;
2883
2884 case MSG_NOTIFY_DATA_CHANGED: {
2885 mBackupManager.dataChanged();
2886 } break;
2887 }
2888 }
2889 }
2890
Svetoslav683914b2015-01-15 14:22:26 -08002891 private final class UpgradeController {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07002892 private static final int SETTINGS_VERSION = 148;
Svetoslav683914b2015-01-15 14:22:26 -08002893
2894 private final int mUserId;
2895
2896 public UpgradeController(int userId) {
2897 mUserId = userId;
2898 }
2899
2900 public void upgradeIfNeededLocked() {
2901 // The version of all settings for a user is the same (all users have secure).
2902 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002903 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002904
2905 // Try an update from the current state.
2906 final int oldVersion = secureSettings.getVersionLocked();
2907 final int newVersion = SETTINGS_VERSION;
2908
Svet Ganovc9755bc2015-03-28 13:21:22 -07002909 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002910 if (oldVersion == newVersion) {
2911 return;
2912 }
2913
2914 // Try to upgrade.
2915 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2916
2917 // If upgrade failed start from scratch and upgrade.
2918 if (curVersion != newVersion) {
2919 // Drop state we have for this user.
2920 removeUserStateLocked(mUserId, true);
2921
2922 // Recreate the database.
2923 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2924 SQLiteDatabase database = dbHelper.getWritableDatabase();
2925 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2926
2927 // Migrate the settings for this user.
2928 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2929
2930 // Now upgrade should work fine.
2931 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002932
2933 // Make a note what happened, so we don't wonder why data was lost
2934 String reason = "Settings rebuilt! Current version: "
2935 + curVersion + " while expected: " + newVersion;
2936 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002937 Settings.Global.DATABASE_DOWNGRADE_REASON,
2938 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002939 }
2940
2941 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002942 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002943 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002944 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002945 globalSettings.setVersionLocked(newVersion);
2946 }
2947
2948 // Set the secure settings version.
2949 secureSettings.setVersionLocked(newVersion);
2950
2951 // Set the system settings version.
2952 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002953 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002954 systemSettings.setVersionLocked(newVersion);
2955 }
2956
2957 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002958 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002959 }
2960
2961 private SettingsState getSecureSettingsLocked(int userId) {
2962 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2963 }
2964
Mark Rathjend891f012017-01-19 04:10:37 +00002965 private SettingsState getSsaidSettingsLocked(int userId) {
2966 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2967 }
2968
Svetoslav683914b2015-01-15 14:22:26 -08002969 private SettingsState getSystemSettingsLocked(int userId) {
2970 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2971 }
2972
Jeff Brown503cffc2015-03-26 18:08:51 -07002973 /**
2974 * You must perform all necessary mutations to bring the settings
2975 * for this user from the old to the new version. When you add a new
2976 * upgrade step you *must* update SETTINGS_VERSION.
2977 *
2978 * This is an example of moving a setting from secure to global.
2979 *
2980 * // v119: Example settings changes.
2981 * if (currentVersion == 118) {
2982 * if (userId == UserHandle.USER_OWNER) {
2983 * // Remove from the secure settings.
2984 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2985 * String name = "example_setting_to_move";
2986 * String value = secureSettings.getSetting(name);
2987 * secureSettings.deleteSetting(name);
2988 *
2989 * // Add to the global settings.
2990 * SettingsState globalSettings = getGlobalSettingsLocked();
2991 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2992 * }
2993 *
2994 * // Update the current version.
2995 * currentVersion = 119;
2996 * }
2997 */
Svetoslav683914b2015-01-15 14:22:26 -08002998 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2999 if (DEBUG) {
3000 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3001 + oldVersion + " to version: " + newVersion);
3002 }
3003
Jeff Brown503cffc2015-03-26 18:08:51 -07003004 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003005
John Spurlocke11ae112015-05-11 16:09:03 -04003006 // v119: Reset zen + ringer mode.
3007 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003008 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003009 final SettingsState globalSettings = getGlobalSettingsLocked();
3010 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003011 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3012 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003013 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003014 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3015 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003016 }
3017 currentVersion = 119;
3018 }
3019
Jason Monk27bbb2d2015-03-31 16:46:39 -04003020 // v120: Add double tap to wake setting.
3021 if (currentVersion == 119) {
3022 SettingsState secureSettings = getSecureSettingsLocked(userId);
3023 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3024 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003025 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003026 SettingsState.SYSTEM_PACKAGE_NAME);
3027
3028 currentVersion = 120;
3029 }
3030
Svetoslav7e0683b2015-08-03 16:02:52 -07003031 if (currentVersion == 120) {
3032 // Before 121, we used a different string encoding logic. We just bump the
3033 // version here; SettingsState knows how to handle pre-version 120 files.
3034 currentVersion = 121;
3035 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003036
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003037 if (currentVersion == 121) {
3038 // Version 122: allow OEMs to set a default payment component in resources.
3039 // Note that we only write the default if no default has been set;
3040 // if there is, we just leave the default at whatever it currently is.
3041 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3042 String defaultComponent = (getContext().getResources().getString(
3043 R.string.def_nfc_payment_component));
3044 Setting currentSetting = secureSettings.getSettingLocked(
3045 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3046 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003047 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003048 secureSettings.insertSettingLocked(
3049 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003050 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003051 }
3052 currentVersion = 122;
3053 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003054
3055 if (currentVersion == 122) {
3056 // Version 123: Adding a default value for the ability to add a user from
3057 // the lock screen.
3058 if (userId == UserHandle.USER_SYSTEM) {
3059 final SettingsState globalSettings = getGlobalSettingsLocked();
3060 Setting currentSetting = globalSettings.getSettingLocked(
3061 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003062 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003063 globalSettings.insertSettingLocked(
3064 Settings.Global.ADD_USERS_WHEN_LOCKED,
3065 getContext().getResources().getBoolean(
3066 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003067 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003068 }
3069 }
3070 currentVersion = 123;
3071 }
Bryce Leebd179282015-12-17 19:01:37 -08003072
3073 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003074 final SettingsState globalSettings = getGlobalSettingsLocked();
3075 String defaultDisabledProfiles = (getContext().getResources().getString(
3076 R.string.def_bluetooth_disabled_profiles));
3077 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003078 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003079 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003080 }
3081
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003082 if (currentVersion == 124) {
3083 // Version 124: allow OEMs to set a default value for whether IME should be
3084 // shown when a physical keyboard is connected.
3085 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3086 Setting currentSetting = secureSettings.getSettingLocked(
3087 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003088 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003089 secureSettings.insertSettingLocked(
3090 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3091 getContext().getResources().getBoolean(
3092 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003093 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003094 }
3095 currentVersion = 125;
3096 }
3097
Ruben Brunk98576cf2016-03-07 18:54:28 -08003098 if (currentVersion == 125) {
3099 // Version 125: Allow OEMs to set the default VR service.
3100 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3101
3102 Setting currentSetting = secureSettings.getSettingLocked(
3103 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003104 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003105 ArraySet<ComponentName> l =
3106 SystemConfig.getInstance().getDefaultVrComponents();
3107
3108 if (l != null && !l.isEmpty()) {
3109 StringBuilder b = new StringBuilder();
3110 boolean start = true;
3111 for (ComponentName c : l) {
3112 if (!start) {
3113 b.append(':');
3114 }
3115 b.append(c.flattenToString());
3116 start = false;
3117 }
3118 secureSettings.insertSettingLocked(
3119 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003120 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003121 }
3122
3123 }
3124 currentVersion = 126;
3125 }
3126
Daniel U02ba6122016-04-01 18:41:42 +01003127 if (currentVersion == 126) {
3128 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3129 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3130 if (mUserManager.isManagedProfile(userId)) {
3131 final SettingsState systemSecureSettings =
3132 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3133
3134 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3135 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003136 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003137 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3138 secureSettings.insertSettingLocked(
3139 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003140 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003141 SettingsState.SYSTEM_PACKAGE_NAME);
3142 }
3143
3144 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3145 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003146 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003147 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3148 secureSettings.insertSettingLocked(
3149 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003150 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003151 SettingsState.SYSTEM_PACKAGE_NAME);
3152 }
3153 }
3154 currentVersion = 127;
3155 }
3156
Steven Ngdc20ba62016-04-26 18:19:04 +01003157 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003158 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003159 currentVersion = 128;
3160 }
3161
Julia Reynolds1f721e12016-07-11 08:50:58 -04003162 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003163 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003164 currentVersion = 129;
3165 }
3166
Dan Sandler71f85e92016-07-20 13:46:05 -04003167 if (currentVersion == 129) {
3168 // default longpress timeout changed from 500 to 400. If unchanged from the old
3169 // default, update to the new default.
3170 final SettingsState systemSecureSettings =
3171 getSecureSettingsLocked(userId);
3172 final String oldValue = systemSecureSettings.getSettingLocked(
3173 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3174 if (TextUtils.equals("500", oldValue)) {
3175 systemSecureSettings.insertSettingLocked(
3176 Settings.Secure.LONG_PRESS_TIMEOUT,
3177 String.valueOf(getContext().getResources().getInteger(
3178 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003179 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003180 }
3181 currentVersion = 130;
3182 }
3183
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003184 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003185 // Split Ambient settings
3186 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3187 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3188 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3189
3190 if (dozeExplicitlyDisabled) {
3191 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003192 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003193 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003194 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003195 }
3196 currentVersion = 131;
3197 }
3198
3199 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003200 // Initialize new multi-press timeout to default value
3201 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3202 final String oldValue = systemSecureSettings.getSettingLocked(
3203 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3204 if (TextUtils.equals(null, oldValue)) {
3205 systemSecureSettings.insertSettingLocked(
3206 Settings.Secure.MULTI_PRESS_TIMEOUT,
3207 String.valueOf(getContext().getResources().getInteger(
3208 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003209 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003210 }
3211
Adrian Roos69741a22016-10-21 14:49:17 -07003212 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003213 }
3214
Adrian Roos69741a22016-10-21 14:49:17 -07003215 if (currentVersion == 132) {
3216 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003217 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3218 String defaultSyncParentSounds = (getContext().getResources()
3219 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3220 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003221 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3222 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003223 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003224 }
3225
Adrian Roos69741a22016-10-21 14:49:17 -07003226 if (currentVersion == 133) {
3227 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003228 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3229 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3230 null) {
3231 String defaultEndButtonBehavior = Integer.toString(getContext()
3232 .getResources().getInteger(R.integer.def_end_button_behavior));
3233 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003234 defaultEndButtonBehavior, null, true,
3235 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003236 }
Adrian Roos69741a22016-10-21 14:49:17 -07003237 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003238 }
3239
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003240 if (currentVersion == 134) {
3241 // Remove setting that specifies if magnification values should be preserved.
3242 // This setting defaulted to true and never has a UI.
3243 getSecureSettingsLocked(userId).deleteSettingLocked(
3244 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3245 currentVersion = 135;
3246 }
3247
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003248 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003249 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003250 currentVersion = 136;
3251 }
3252
Mark Rathjend891f012017-01-19 04:10:37 +00003253 if (currentVersion == 136) {
3254 // Version 136: Store legacy SSAID for all apps currently installed on the
3255 // device as first step in migrating SSAID to be unique per application.
3256
3257 final boolean isUpgrade;
3258 try {
3259 isUpgrade = mPackageManager.isUpgrade();
3260 } catch (RemoteException e) {
3261 throw new IllegalStateException("Package manager not available");
3262 }
3263 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3264 // user data or first boot on a new device should use new ssaid generation.
3265 if (isUpgrade) {
3266 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003267 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3268 userId, Settings.Secure.ANDROID_ID);
3269 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3270 || legacySsaidSetting.getValue() == null) {
3271 throw new IllegalStateException("Legacy ssaid not accessible");
3272 }
3273 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003274
3275 // Fill each uid with the legacy ssaid to be backwards compatible.
3276 final List<PackageInfo> packages;
3277 try {
3278 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3279 } catch (RemoteException e) {
3280 throw new IllegalStateException("Package manager not available");
3281 }
3282
3283 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3284 for (PackageInfo info : packages) {
3285 // Check if the UID already has an entry in the table.
3286 final String uid = Integer.toString(info.applicationInfo.uid);
3287 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3288
3289 if (ssaid.isNull() || ssaid.getValue() == null) {
3290 // Android Id doesn't exist for this package so create it.
3291 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3292 info.packageName);
3293 }
3294 }
3295 }
3296
3297 currentVersion = 137;
3298 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003299 if (currentVersion == 137) {
3300 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3301 // default value set to 1. The user can no longer change the value of this
3302 // setting through the UI.
3303 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3304 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003305 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3306 && secureSetting.getSettingLocked(
3307 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3308
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003309 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3310 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003311 // For managed profiles with profile owners, DevicePolicyManagerService
3312 // may want to set the user restriction in this case
3313 secureSetting.insertSettingLocked(
3314 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3315 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003316 }
3317 currentVersion = 138;
3318 }
Mark Rathjend891f012017-01-19 04:10:37 +00003319
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003320 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003321 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003322 currentVersion = 139;
3323 }
3324
Phil Weaver385912e2017-02-10 10:06:56 -08003325 if (currentVersion == 139) {
3326 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3327 // the user can no longer change the value of this setting through the UI.
3328 // Force to true.
3329 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3330 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3331 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3332 currentVersion = 140;
3333 }
3334
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003335 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003336 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003337 currentVersion = 141;
3338 }
3339
Svet Ganov13701552017-02-23 12:45:17 -08003340 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003341 // This implementation was incorrectly setting the current value of
3342 // settings changed by non-system packages as the default which default
3343 // is set by the system. We add a new upgrade step at the end to properly
3344 // handle this case which would also fix incorrect changes made by the
3345 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003346 currentVersion = 142;
3347 }
3348
Stephen Chen5d0922f2017-03-27 10:28:04 -07003349 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003350 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003351 if (userId == UserHandle.USER_SYSTEM) {
3352 final SettingsState globalSettings = getGlobalSettingsLocked();
3353 Setting currentSetting = globalSettings.getSettingLocked(
3354 Settings.Global.WIFI_WAKEUP_ENABLED);
3355 if (currentSetting.isNull()) {
3356 globalSettings.insertSettingLocked(
3357 Settings.Global.WIFI_WAKEUP_ENABLED,
3358 getContext().getResources().getBoolean(
3359 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3360 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3361 }
3362 }
3363
3364 currentVersion = 143;
3365 }
3366
Felipe Lemeff355092017-04-03 12:55:02 -07003367 if (currentVersion == 143) {
3368 // Version 144: Set a default value for Autofill service.
3369 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3370 final Setting currentSetting = secureSettings
3371 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3372 if (currentSetting.isNull()) {
3373 final String defaultValue = getContext().getResources().getString(
3374 com.android.internal.R.string.config_defaultAutofillService);
3375 if (defaultValue != null) {
3376 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3377 + "for user " + userId);
3378 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3379 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3380 }
3381 }
3382
3383 currentVersion = 144;
3384 }
3385
Jeremy Joslin45caa252017-05-04 11:22:46 -07003386 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003387 // Version 145: Removed
3388 currentVersion = 145;
3389 }
3390
3391 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003392 // Version 146: In step 142 we had a bug where incorrectly
3393 // some settings were considered system set and as a result
3394 // made the default and marked as the default being set by
3395 // the system. Here reevaluate the default and default system
3396 // set flags. This would both fix corruption by the old impl
3397 // of step 142 and also properly handle devices which never
3398 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003399 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003400 SettingsState globalSettings = getGlobalSettingsLocked();
3401 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3402 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003403 }
3404
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003405 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3406 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3407 secureSettings.persistSyncLocked();
3408
3409 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3410 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3411 systemSettings.persistSyncLocked();
3412
Amin Shaikh86367962017-06-07 08:58:22 -07003413 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003414 }
3415
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003416 if (currentVersion == 146) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003417 // Version 147: Set the default value for WIFI_WAKEUP_AVAILABLE.
3418 if (userId == UserHandle.USER_SYSTEM) {
3419 final SettingsState globalSettings = getGlobalSettingsLocked();
3420 final Setting currentSetting = globalSettings.getSettingLocked(
3421 Settings.Global.WIFI_WAKEUP_AVAILABLE);
3422 if (currentSetting.getValue() == null) {
3423 final int defaultValue = getContext().getResources().getInteger(
3424 com.android.internal.R.integer.config_wifi_wakeup_available);
3425 globalSettings.insertSettingLocked(
3426 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3427 String.valueOf(defaultValue),
3428 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3429 }
3430 }
3431
3432 currentVersion = 147;
3433 }
3434
3435 if (currentVersion == 147) {
3436 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003437 if (userId == UserHandle.USER_SYSTEM) {
3438 final SettingsState globalSettings = getGlobalSettingsLocked();
3439 final Setting currentSetting = globalSettings.getSettingLocked(
3440 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3441 if (currentSetting.isNull()) {
3442 globalSettings.insertSettingLocked(
3443 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3444 getContext().getResources().getBoolean(
3445 R.bool.def_restrict_background_data) ? "1" : "0",
3446 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3447 }
3448 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003449 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003450 }
3451
Felipe Lemeff355092017-04-03 12:55:02 -07003452 // vXXX: Add new settings above this point.
3453
Dan Sandler71f85e92016-07-20 13:46:05 -04003454 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003455 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003456 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003457 + currentVersion +
3458 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3459 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003460 if (DEBUG) {
3461 throw new RuntimeException("db upgrade error");
3462 }
3463 }
3464
Jeff Brown503cffc2015-03-26 18:08:51 -07003465 // Return the current version.
3466 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003467 }
3468 }
Svet Ganov13701552017-02-23 12:45:17 -08003469
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003470 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3471 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003472 List<String> names = settings.getSettingNamesLocked();
3473 final int nameCount = names.size();
3474 for (int i = 0; i < nameCount; i++) {
3475 String name = names.get(i);
3476 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003477
3478 // In the upgrade case we pretend the call is made from the app
3479 // that made the last change to the setting to properly determine
3480 // whether the call has been made by a system component.
3481 int callingUid = -1;
3482 try {
3483 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3484 } catch (RemoteException e) {
3485 /* ignore - handled below */
3486 }
3487 if (callingUid < 0) {
3488 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3489 continue;
3490 }
3491 try {
3492 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3493 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003494 if (systemSet) {
3495 settings.insertSettingLocked(name, setting.getValue(),
3496 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003497 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3498 // We had a bug where changes by non-system packages were marked
3499 // as system made and as a result set as the default. Therefore, if
3500 // the package changed the setting last is not a system one but the
3501 // setting is marked as its default coming from the system we clear
3502 // the default and clear the system set flag.
3503 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003504 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003505 } catch (IllegalStateException e) {
3506 // If the package goes over its quota during the upgrade, don't
3507 // crash but just log the error as the system does the upgrade.
3508 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3509
Svet Ganov13701552017-02-23 12:45:17 -08003510 }
3511 }
3512 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003513 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003514}