blob: 1bd58ad85424946a1f5742d15ea9821259294f75 [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;
Julia Reynoldsad0d9e02017-02-15 08:41:48 -050035import android.content.pm.ResolveInfo;
36import android.content.pm.ServiceInfo;
Christopher Tate38e7a602013-09-03 16:57:34 -070037import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070038import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080040import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.sqlite.SQLiteDatabase;
42import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040044import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070046import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080047import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080048import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070049import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070051import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070052import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070053import android.os.Looper;
54import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070055import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070056import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070057import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070058import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070059import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070060import android.os.UserHandle;
61import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070062import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063import android.provider.Settings;
Julia Reynoldsad0d9e02017-02-15 08:41:48 -050064import android.service.notification.NotificationListenerService;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010066import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080067import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000068import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070069import android.util.Slog;
70import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070071import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080072import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040073
Svetoslav683914b2015-01-15 14:22:26 -080074import com.android.internal.annotations.GuardedBy;
75import com.android.internal.content.PackageMonitor;
76import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080077import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070078import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080079import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040080
Svetoslav683914b2015-01-15 14:22:26 -080081import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080082import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080083import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080084import java.io.PrintWriter;
Mark Rathjend891f012017-01-19 04:10:37 +000085import java.nio.charset.StandardCharsets;
Mark Rathjen7599f132017-01-23 14:15:54 -080086import java.nio.ByteBuffer;
87import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000088import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080089import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070090import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000092import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000093import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080094import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080095import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010096import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080097import java.util.Set;
98import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import javax.crypto.Mac;
100import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700101
Svetoslav Ganove080da92016-12-21 17:10:35 -0800102import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800103import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800104import static android.os.Process.SYSTEM_UID;
105
Svetoslav Ganove080da92016-12-21 17:10:35 -0800106
Svetoslav683914b2015-01-15 14:22:26 -0800107/**
108 * <p>
109 * This class is a content provider that publishes the system settings.
110 * It can be accessed via the content provider APIs or via custom call
111 * commands. The latter is a bit faster and is the preferred way to access
112 * the platform settings.
113 * </p>
114 * <p>
115 * There are three settings types, global (with signature level protection
116 * and shared across users), secure (with signature permission level
117 * protection and per user), and system (with dangerous permission level
118 * protection and per user). Global settings are stored under the device owner.
119 * Each of these settings is represented by a {@link
120 * com.android.providers.settings.SettingsState} object mapped to an integer
121 * key derived from the setting type in the most significant bits and user
122 * id in the least significant bits. Settings are synchronously loaded on
123 * instantiation of a SettingsState and asynchronously persisted on mutation.
124 * Settings are stored in the user specific system directory.
125 * </p>
126 * <p>
127 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
128 * and get a warning. Targeting higher API version prohibits this as the
129 * system settings are not a place for apps to save their state. When a package
130 * is removed the settings it added are deleted. Apps cannot delete system
131 * settings added by the platform. System settings values are validated to
132 * ensure the clients do not put bad values. Global and secure settings are
133 * changed only by trusted parties, therefore no validation is performed. Also
134 * there is a limit on the amount of app specific settings that can be added
135 * to prevent unlimited growth of the system process memory footprint.
136 * </p>
137 */
138@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700140 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700142 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800143
144 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700145
Christopher Tate06efb532012-08-24 15:29:27 -0700146 private static final String TABLE_SYSTEM = "system";
147 private static final String TABLE_SECURE = "secure";
148 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800149
150 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 private static final String TABLE_FAVORITES = "favorites";
152 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800153 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
154 private static final String TABLE_BOOKMARKS = "bookmarks";
155 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Svetoslav683914b2015-01-15 14:22:26 -0800157 // The set of removed legacy tables.
158 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700159 static {
Svetoslav683914b2015-01-15 14:22:26 -0800160 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
161 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
162 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
163 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
164 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
165 }
Christopher Tate06efb532012-08-24 15:29:27 -0700166
Svetoslav683914b2015-01-15 14:22:26 -0800167 private static final int MUTATION_OPERATION_INSERT = 1;
168 private static final int MUTATION_OPERATION_DELETE = 2;
169 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800170 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400171
Svetoslav683914b2015-01-15 14:22:26 -0800172 private static final String[] ALL_COLUMNS = new String[] {
173 Settings.NameValueTable._ID,
174 Settings.NameValueTable.NAME,
175 Settings.NameValueTable.VALUE
176 };
177
Svet Ganov53a441c2016-04-19 19:38:00 -0700178 public static final int SETTINGS_TYPE_GLOBAL = 0;
179 public static final int SETTINGS_TYPE_SYSTEM = 1;
180 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000181 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800182
Svet Ganov53a441c2016-04-19 19:38:00 -0700183 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
184 public static final int SETTINGS_TYPE_SHIFT = 28;
185
186 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
187 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700188
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700189 // Overlay specified settings whitelisted for Instant Apps
190 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
191 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
192 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
193
194 static {
195 for (String name : Resources.getSystem().getStringArray(
196 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
197 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
198 }
199 for (String name : Resources.getSystem().getStringArray(
200 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
201 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
202 }
203 for (String name : Resources.getSystem().getStringArray(
204 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
205 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
206 }
207 }
208
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800209 // Changes to these global settings are synchronously persisted
210 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
211 static {
212 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
213 }
214
215 // Changes to these secure settings are synchronously persisted
216 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
217 static {
218 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
219 }
220
Svetoslav683914b2015-01-15 14:22:26 -0800221 // Per user secure settings that moved to the for all users global settings.
222 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
223 static {
224 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700225 }
226
Svetoslav683914b2015-01-15 14:22:26 -0800227 // Per user system settings that moved to the for all users global settings.
228 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
229 static {
230 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231 }
232
Svetoslav683914b2015-01-15 14:22:26 -0800233 // Per user system settings that moved to the per user secure settings.
234 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
235 static {
236 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700237 }
238
Svetoslav683914b2015-01-15 14:22:26 -0800239 // Per all users global settings that moved to the per user secure settings.
240 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
241 static {
242 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700243 }
244
Svetoslav683914b2015-01-15 14:22:26 -0800245 // Per user secure settings that are cloned for the managed profiles of the user.
246 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
247 static {
248 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249 }
250
Svetoslav683914b2015-01-15 14:22:26 -0800251 // Per user system settings that are cloned for the managed profiles of the user.
252 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
253 static {
254 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400255 }
256
Andre Lago3fa139c2016-08-04 13:53:44 +0100257 // Per user system settings that are cloned from the profile's parent when a dependency
258 // in {@link Settings.Secure} is set to "1".
259 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
260 static {
261 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
262 }
263
Svetoslav683914b2015-01-15 14:22:26 -0800264 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700265
Svetoslav683914b2015-01-15 14:22:26 -0800266 @GuardedBy("mLock")
267 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700268
Svet Ganova8f90262016-05-10 08:44:48 -0700269 @GuardedBy("mLock")
270 private HandlerThread mHandlerThread;
271
Makoto Onuki73360ab2017-03-17 11:50:13 -0700272 @GuardedBy("mLock")
273 private Handler mHandler;
274
Svetoslav7ec28e82015-05-20 17:01:10 -0700275 // We have to call in the user manager with no lock held,
276 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800277
Svetoslav7ec28e82015-05-20 17:01:10 -0700278 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700279 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700280
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 public static int makeKey(int type, int userId) {
282 return (type << SETTINGS_TYPE_SHIFT) | userId;
283 }
284
285 public static int getTypeFromKey(int key) {
286 return key >>> SETTINGS_TYPE_SHIFT;
287 }
288
289 public static int getUserIdFromKey(int key) {
290 return key & ~SETTINGS_TYPE_MASK;
291 }
292
293 public static String settingTypeToString(int type) {
294 switch (type) {
295 case SETTINGS_TYPE_GLOBAL: {
296 return "SETTINGS_GLOBAL";
297 }
298 case SETTINGS_TYPE_SECURE: {
299 return "SETTINGS_SECURE";
300 }
301 case SETTINGS_TYPE_SYSTEM: {
302 return "SETTINGS_SYSTEM";
303 }
Mark Rathjend891f012017-01-19 04:10:37 +0000304 case SETTINGS_TYPE_SSAID: {
305 return "SETTINGS_SSAID";
306 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700307 default: {
308 return "UNKNOWN";
309 }
310 }
311 }
312
313 public static String keyToString(int key) {
314 return "Key[user=" + getUserIdFromKey(key) + ";type="
315 + settingTypeToString(getTypeFromKey(key)) + "]";
316 }
317
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700318 @Override
319 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800320 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800321 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700322 mUserManager = UserManager.get(getContext());
323 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700324 mHandlerThread = new HandlerThread(LOG_TAG,
325 Process.THREAD_PRIORITY_BACKGROUND);
326 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700327 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800328 mSettingsRegistry = new SettingsRegistry();
329 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700330 mHandler.post(() -> {
331 registerBroadcastReceivers();
332 startWatchingUserRestrictionChanges();
333 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700334 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700335 return true;
336 }
337
Svetoslav683914b2015-01-15 14:22:26 -0800338 @Override
339 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700340 final int requestingUserId = getRequestingUserId(args);
341 switch (method) {
342 case Settings.CALL_METHOD_GET_GLOBAL: {
343 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700344 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800345 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700346
347 case Settings.CALL_METHOD_GET_SECURE: {
348 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700349 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700350 }
351
352 case Settings.CALL_METHOD_GET_SYSTEM: {
353 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700354 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700355 }
356
357 case Settings.CALL_METHOD_PUT_GLOBAL: {
358 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800359 String tag = getSettingTag(args);
360 final boolean makeDefault = getSettingMakeDefault(args);
361 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700362 break;
363 }
364
365 case Settings.CALL_METHOD_PUT_SECURE: {
366 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800367 String tag = getSettingTag(args);
368 final boolean makeDefault = getSettingMakeDefault(args);
369 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700370 break;
371 }
372
373 case Settings.CALL_METHOD_PUT_SYSTEM: {
374 String value = getSettingValue(args);
375 insertSystemSetting(name, value, requestingUserId);
376 break;
377 }
378
Svetoslav Ganove080da92016-12-21 17:10:35 -0800379 case Settings.CALL_METHOD_RESET_GLOBAL: {
380 final int mode = getResetModeEnforcingPermission(args);
381 String tag = getSettingTag(args);
382 resetGlobalSetting(requestingUserId, mode, tag);
383 break;
384 }
385
386 case Settings.CALL_METHOD_RESET_SECURE: {
387 final int mode = getResetModeEnforcingPermission(args);
388 String tag = getSettingTag(args);
389 resetSecureSetting(requestingUserId, mode, tag);
390 break;
391 }
392
Svetoslav7ec28e82015-05-20 17:01:10 -0700393 default: {
394 Slog.w(LOG_TAG, "call() with invalid method: " + method);
395 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700396 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700397
Christopher Tate06efb532012-08-24 15:29:27 -0700398 return null;
399 }
400
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800401 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800402 public String getType(Uri uri) {
403 Arguments args = new Arguments(uri, null, null, true);
404 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700405 return "vnd.android.cursor.dir/" + args.table;
406 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700407 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700408 }
409 }
410
411 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800412 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
413 String order) {
414 if (DEBUG) {
415 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700416 }
417
Svetoslav683914b2015-01-15 14:22:26 -0800418 Arguments args = new Arguments(uri, where, whereArgs, true);
419 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700420
Svetoslav683914b2015-01-15 14:22:26 -0800421 // If a legacy table that is gone, done.
422 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
423 return new MatrixCursor(normalizedProjection, 0);
424 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700425
Svetoslav7ec28e82015-05-20 17:01:10 -0700426 switch (args.table) {
427 case TABLE_GLOBAL: {
428 if (args.name != null) {
429 Setting setting = getGlobalSetting(args.name);
430 return packageSettingForQuery(setting, normalizedProjection);
431 } else {
432 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700433 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700434 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700435
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 case TABLE_SECURE: {
437 final int userId = UserHandle.getCallingUserId();
438 if (args.name != null) {
439 Setting setting = getSecureSetting(args.name, userId);
440 return packageSettingForQuery(setting, normalizedProjection);
441 } else {
442 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800443 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700444 }
Svetoslav683914b2015-01-15 14:22:26 -0800445
Svetoslav7ec28e82015-05-20 17:01:10 -0700446 case TABLE_SYSTEM: {
447 final int userId = UserHandle.getCallingUserId();
448 if (args.name != null) {
449 Setting setting = getSystemSetting(args.name, userId);
450 return packageSettingForQuery(setting, normalizedProjection);
451 } else {
452 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800453 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700454 }
Svetoslav683914b2015-01-15 14:22:26 -0800455
Svetoslav7ec28e82015-05-20 17:01:10 -0700456 default: {
457 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700458 }
459 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700460 }
461
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700462 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800463 public Uri insert(Uri uri, ContentValues values) {
464 if (DEBUG) {
465 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700466 }
467
Svetoslav683914b2015-01-15 14:22:26 -0800468 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700469
Svetoslav683914b2015-01-15 14:22:26 -0800470 // If a legacy table that is gone, done.
471 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 return null;
473 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700474
Svetoslav683914b2015-01-15 14:22:26 -0800475 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700476 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800477 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700478 }
479
Svetoslav683914b2015-01-15 14:22:26 -0800480 String value = values.getAsString(Settings.Secure.VALUE);
481
Svetoslav7ec28e82015-05-20 17:01:10 -0700482 switch (table) {
483 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800484 if (insertGlobalSetting(name, value, null, false,
485 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700486 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700487 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700488 } break;
489
490 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800491 if (insertSecureSetting(name, value, null, false,
492 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700493 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
494 }
495 } break;
496
497 case TABLE_SYSTEM: {
498 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
499 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
500 }
501 } break;
502
503 default: {
504 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700505 }
506 }
507
Svetoslav683914b2015-01-15 14:22:26 -0800508 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700509 }
510
511 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800512 public int bulkInsert(Uri uri, ContentValues[] allValues) {
513 if (DEBUG) {
514 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516
Svetoslav683914b2015-01-15 14:22:26 -0800517 int insertionCount = 0;
518 final int valuesCount = allValues.length;
519 for (int i = 0; i < valuesCount; i++) {
520 ContentValues values = allValues[i];
521 if (insert(uri, values) != null) {
522 insertionCount++;
523 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700524 }
Svetoslav683914b2015-01-15 14:22:26 -0800525
526 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700527 }
528
529 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800530 public int delete(Uri uri, String where, String[] whereArgs) {
531 if (DEBUG) {
532 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700534
Svetoslav683914b2015-01-15 14:22:26 -0800535 Arguments args = new Arguments(uri, where, whereArgs, false);
536
537 // If a legacy table that is gone, done.
538 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
539 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700540 }
Svetoslav683914b2015-01-15 14:22:26 -0800541
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700542 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800543 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700544 }
Svetoslav683914b2015-01-15 14:22:26 -0800545
Svetoslav7ec28e82015-05-20 17:01:10 -0700546 switch (args.table) {
547 case TABLE_GLOBAL: {
548 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700549 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700550 }
Svetoslav683914b2015-01-15 14:22:26 -0800551
Svetoslav7ec28e82015-05-20 17:01:10 -0700552 case TABLE_SECURE: {
553 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700554 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700555 }
Svetoslav683914b2015-01-15 14:22:26 -0800556
Svetoslav7ec28e82015-05-20 17:01:10 -0700557 case TABLE_SYSTEM: {
558 final int userId = UserHandle.getCallingUserId();
559 return deleteSystemSetting(args.name, userId) ? 1 : 0;
560 }
561
562 default: {
563 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800564 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700565 }
Svetoslav683914b2015-01-15 14:22:26 -0800566 }
567
568 @Override
569 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
570 if (DEBUG) {
571 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700572 }
Svetoslav683914b2015-01-15 14:22:26 -0800573
574 Arguments args = new Arguments(uri, where, whereArgs, false);
575
576 // If a legacy table that is gone, done.
577 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
578 return 0;
579 }
580
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700581 String name = values.getAsString(Settings.Secure.NAME);
582 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800583 return 0;
584 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700585 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800586
Svetoslav7ec28e82015-05-20 17:01:10 -0700587 switch (args.table) {
588 case TABLE_GLOBAL: {
589 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800590 return updateGlobalSetting(args.name, value, null, false,
591 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700592 }
Svetoslav683914b2015-01-15 14:22:26 -0800593
Svetoslav7ec28e82015-05-20 17:01:10 -0700594 case TABLE_SECURE: {
595 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800596 return updateSecureSetting(args.name, value, null, false,
597 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700598 }
Svetoslav683914b2015-01-15 14:22:26 -0800599
Svetoslav7ec28e82015-05-20 17:01:10 -0700600 case TABLE_SYSTEM: {
601 final int userId = UserHandle.getCallingUserId();
602 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
603 }
Svetoslav683914b2015-01-15 14:22:26 -0800604
Svetoslav7ec28e82015-05-20 17:01:10 -0700605 default: {
606 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800607 }
608 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700609 }
610
611 @Override
612 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100613 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
614 if (userId != UserHandle.getCallingUserId()) {
615 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
616 "Access files from the settings of another user");
617 }
618 uri = ContentProvider.getUriWithoutUserId(uri);
619
Andre Lago3fa139c2016-08-04 13:53:44 +0100620 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700621 final String cacheName;
622 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100623 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700624 cacheName = Settings.System.RINGTONE_CACHE;
625 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100626 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700627 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
628 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100629 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700630 cacheName = Settings.System.ALARM_ALERT_CACHE;
631 } else {
632 throw new FileNotFoundException("Direct file access no longer supported; "
633 + "ringtone playback is available through android.media.Ringtone");
634 }
635
Andre Lago3fa139c2016-08-04 13:53:44 +0100636 int actualCacheOwner;
637 // Redirect cache to parent if ringtone setting is owned by profile parent
638 synchronized (mLock) {
639 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
640 cacheRingtoneSetting);
641 }
642 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700643 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
644 }
645
646 private File getRingtoneCacheDir(int userId) {
647 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
648 cacheDir.mkdir();
649 SELinux.restorecon(cacheDir);
650 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700651 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800652
Eugene Suslad72c3972016-12-27 15:49:30 -0800653 /**
654 * Dump all settings as a proto buf.
655 *
656 * @param fd The file to dump to
657 */
658 void dumpProto(@NonNull FileDescriptor fd) {
659 ProtoOutputStream proto = new ProtoOutputStream(fd);
660
661 synchronized (mLock) {
662 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
663
664 }
665
666 proto.flush();
667 }
668
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700669 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800670 synchronized (mLock) {
671 final long identity = Binder.clearCallingIdentity();
672 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700673 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800674 final int userCount = users.size();
675 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700676 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800677 }
678 } finally {
679 Binder.restoreCallingIdentity(identity);
680 }
681 }
682 }
683
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700684 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700685 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800686 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700687 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
688 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700689 if (globalSettings != null) {
690 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800691 pw.println();
692 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700693 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800694 }
695
696 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700697 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
698 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700699 if (secureSettings != null) {
700 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800701 pw.println();
702 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700703 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700704
Svetoslavb505ccc2015-02-17 12:41:04 -0800705 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700706 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
707 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700708 if (systemSettings != null) {
709 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800710 pw.println();
711 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700712 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800713 }
714
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700715 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
716 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800717
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700718 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800719
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700720 for (int i = 0; i < nameCount; i++) {
721 String name = names.get(i);
722 Setting setting = settingsState.getSettingLocked(name);
723 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
724 pw.print(" name:"); pw.print(toDumpString(name));
725 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800726 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700727 }
728 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800729 if (setting.getDefaultValue() != null) {
730 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800731 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800732 }
733 if (setting.getTag() != null) {
734 pw.print(" tag:"); pw.print(setting.getTag());
735 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800736 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700737 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800738 }
739
Svetoslav7e0683b2015-08-03 16:02:52 -0700740 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700741 if (s != null) {
742 return s;
743 }
744 return "{null}";
745 }
746
Svetoslav683914b2015-01-15 14:22:26 -0800747 private void registerBroadcastReceivers() {
748 IntentFilter userFilter = new IntentFilter();
749 userFilter.addAction(Intent.ACTION_USER_REMOVED);
750 userFilter.addAction(Intent.ACTION_USER_STOPPED);
751
752 getContext().registerReceiver(new BroadcastReceiver() {
753 @Override
754 public void onReceive(Context context, Intent intent) {
755 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700756 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800757
758 switch (intent.getAction()) {
759 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700760 synchronized (mLock) {
761 mSettingsRegistry.removeUserStateLocked(userId, true);
762 }
Svetoslav683914b2015-01-15 14:22:26 -0800763 } break;
764
765 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700766 synchronized (mLock) {
767 mSettingsRegistry.removeUserStateLocked(userId, false);
768 }
Svetoslav683914b2015-01-15 14:22:26 -0800769 } break;
770 }
771 }
772 }, userFilter);
773
774 PackageMonitor monitor = new PackageMonitor() {
775 @Override
776 public void onPackageRemoved(String packageName, int uid) {
777 synchronized (mLock) {
778 mSettingsRegistry.onPackageRemovedLocked(packageName,
779 UserHandle.getUserId(uid));
780 }
781 }
Mark Rathjend891f012017-01-19 04:10:37 +0000782
783 @Override
784 public void onUidRemoved(int uid) {
785 synchronized (mLock) {
786 mSettingsRegistry.onUidRemovedLocked(uid);
787 }
788 }
Svetoslav683914b2015-01-15 14:22:26 -0800789 };
790
791 // package changes
792 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
793 UserHandle.ALL, true);
794 }
795
Svet Ganov53a441c2016-04-19 19:38:00 -0700796 private void startWatchingUserRestrictionChanges() {
797 // TODO: The current design of settings looking different based on user restrictions
798 // should be reworked to keep them separate and system code should check the setting
799 // first followed by checking the user restriction before performing an operation.
800 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
801 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
802 Bundle prevRestrictions) -> {
803 // We are changing the settings affected by restrictions to their current
804 // value with a forced update to ensure that all cross profile dependencies
805 // are taken into account. Also make sure the settings update to.. the same
806 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800807 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
808 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700809 final long identity = Binder.clearCallingIdentity();
810 try {
811 synchronized (mLock) {
812 Setting setting = getSecureSetting(
813 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
814 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 setting != null ? setting.getValue() : null, null,
816 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 }
818 } finally {
819 Binder.restoreCallingIdentity(identity);
820 }
821 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800822 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
823 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700824 final long identity = Binder.clearCallingIdentity();
825 try {
826 synchronized (mLock) {
827 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800828 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700829 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800830 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 }
832 } finally {
833 Binder.restoreCallingIdentity(identity);
834 }
835 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800836 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
837 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700838 final long identity = Binder.clearCallingIdentity();
839 try {
840 synchronized (mLock) {
841 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800842 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700843 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800844 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700845 }
846 } finally {
847 Binder.restoreCallingIdentity(identity);
848 }
849 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800850 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
851 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700852 final long identity = Binder.clearCallingIdentity();
853 try {
854 synchronized (mLock) {
855 Setting enable = getGlobalSetting(
856 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800857 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700858 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800859 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700860 Setting include = getGlobalSetting(
861 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800862 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700863 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800864 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700865 }
866 } finally {
867 Binder.restoreCallingIdentity(identity);
868 }
869 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800870 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
871 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700872 final long identity = Binder.clearCallingIdentity();
873 try {
874 synchronized (mLock) {
875 Setting setting = getGlobalSetting(
876 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800877 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700878 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800879 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700880 }
881 } finally {
882 Binder.restoreCallingIdentity(identity);
883 }
884 }
885 });
886 }
887
Svetoslav7ec28e82015-05-20 17:01:10 -0700888 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800889 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700890 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800891 }
892
Svetoslav7ec28e82015-05-20 17:01:10 -0700893 synchronized (mLock) {
894 // Get the settings.
895 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700896 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800897
Chad Brubaker97bccee2017-01-05 15:51:41 -0800898 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
899 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800900
Svetoslav7ec28e82015-05-20 17:01:10 -0700901 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800902
Svetoslav7ec28e82015-05-20 17:01:10 -0700903 String[] normalizedProjection = normalizeProjection(projection);
904 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800905
Svetoslav7ec28e82015-05-20 17:01:10 -0700906 // Anyone can get the global settings, so no security checks.
907 for (int i = 0; i < nameCount; i++) {
908 String name = names.get(i);
909 Setting setting = settingsState.getSettingLocked(name);
910 appendSettingToCursor(result, setting);
911 }
912
913 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800914 }
Svetoslav683914b2015-01-15 14:22:26 -0800915 }
916
Svetoslav7ec28e82015-05-20 17:01:10 -0700917 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800918 if (DEBUG) {
919 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
920 }
921
Chad Brubakera6830e72017-04-28 17:34:36 -0700922 // Ensure the caller can access the setting.
923 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
924
Svetoslav683914b2015-01-15 14:22:26 -0800925 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700926 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700927 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700928 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800929 }
Svetoslav683914b2015-01-15 14:22:26 -0800930 }
931
Svetoslav Ganove080da92016-12-21 17:10:35 -0800932 private boolean updateGlobalSetting(String name, String value, String tag,
933 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800934 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800935 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
936 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
937 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800938 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800939 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
940 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800941 }
942
Svetoslav Ganove080da92016-12-21 17:10:35 -0800943 private boolean insertGlobalSetting(String name, String value, String tag,
944 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700945 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800946 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
947 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
948 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700949 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800950 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
951 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700952 }
953
Svet Ganov53a441c2016-04-19 19:38:00 -0700954 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800955 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800956 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
957 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800958 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800959 return mutateGlobalSetting(name, null, null, false, requestingUserId,
960 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800961 }
962
Svetoslav Ganove080da92016-12-21 17:10:35 -0800963 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
964 if (DEBUG) {
965 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
966 + mode + ", " + tag + ")");
967 }
968 mutateGlobalSetting(null, null, tag, false, requestingUserId,
969 MUTATION_OPERATION_RESET, false, mode);
970 }
971
972 private boolean mutateGlobalSetting(String name, String value, String tag,
973 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
974 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800975 // Make sure the caller can change the settings - treated as secure.
976 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
977
Svetoslav683914b2015-01-15 14:22:26 -0800978 // Resolve the userId on whose behalf the call is made.
979 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
980
Makoto Onuki28da2e32015-11-20 11:30:44 -0800981 // If this is a setting that is currently restricted for this user, do not allow
982 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800983 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100984 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800985 return false;
986 }
987
988 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 synchronized (mLock) {
990 switch (operation) {
991 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800992 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
993 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800994 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700995 }
Svetoslav683914b2015-01-15 14:22:26 -0800996
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700998 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800999 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001000 }
Svetoslav683914b2015-01-15 14:22:26 -08001001
Svetoslav7ec28e82015-05-20 17:01:10 -07001002 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001003 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1004 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001005 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001006 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001007
1008 case MUTATION_OPERATION_RESET: {
1009 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1010 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1011 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001012 }
1013 }
1014
1015 return false;
1016 }
1017
Christopher Tateb218e762017-04-05 16:34:07 -07001018 private PackageInfo getCallingPackageInfo(int userId) {
1019 try {
1020 return mPackageManager.getPackageInfo(getCallingPackage(),
1021 PackageManager.GET_SIGNATURES, userId);
1022 } catch (RemoteException e) {
1023 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1024 }
1025 }
1026
Svetoslav7ec28e82015-05-20 17:01:10 -07001027 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001028 if (DEBUG) {
1029 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1030 }
1031
1032 // Resolve the userId on whose behalf the call is made.
1033 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1034
Christopher Tateb218e762017-04-05 16:34:07 -07001035 // The relevant "calling package" userId will be the owning userId for some
1036 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1037 // up front who the effective "new SSAID" user ID for that settings name will be.
1038 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1039 Settings.Secure.ANDROID_ID);
1040 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1041
Svetoslav7ec28e82015-05-20 17:01:10 -07001042 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001043 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001044
Svetoslav7ec28e82015-05-20 17:01:10 -07001045 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001046
Svetoslav7ec28e82015-05-20 17:01:10 -07001047 String[] normalizedProjection = normalizeProjection(projection);
1048 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001049
Svetoslav7ec28e82015-05-20 17:01:10 -07001050 for (int i = 0; i < nameCount; i++) {
1051 String name = names.get(i);
1052 // Determine the owning user as some profile settings are cloned from the parent.
1053 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1054 name);
Svetoslav683914b2015-01-15 14:22:26 -08001055
Alex Klyubin1991f572017-03-03 14:08:36 -08001056 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1057 // This caller is not permitted to access this setting. Pretend the setting
1058 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001059 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001060 }
Svetoslav683914b2015-01-15 14:22:26 -08001061
Mark Rathjen7599f132017-01-23 14:15:54 -08001062 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001063 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1064 final Setting setting;
1065 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001066 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001067 } else {
1068 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1069 name);
1070 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001071 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001072 }
1073
Svetoslav7ec28e82015-05-20 17:01:10 -07001074 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001075 }
Svetoslav683914b2015-01-15 14:22:26 -08001076 }
1077
Svetoslav7ec28e82015-05-20 17:01:10 -07001078 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001079 if (DEBUG) {
1080 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1081 }
1082
1083 // Resolve the userId on whose behalf the call is made.
1084 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1085
Chad Brubakera6830e72017-04-28 17:34:36 -07001086 // Ensure the caller can access the setting.
1087 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1088
Svetoslav683914b2015-01-15 14:22:26 -08001089 // Determine the owning user as some profile settings are cloned from the parent.
1090 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1091
Alex Klyubin1991f572017-03-03 14:08:36 -08001092 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1093 // This caller is not permitted to access this setting. Pretend the setting doesn't
1094 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001095 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1096 owningUserId);
1097 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001098 }
1099
Christopher Tateb218e762017-04-05 16:34:07 -07001100 // As of Android O, the SSAID is read from an app-specific entry in table
1101 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1102 if (isNewSsaidSetting(name)) {
1103 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1104 synchronized (mLock) {
1105 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001106 }
Christopher Tateb218e762017-04-05 16:34:07 -07001107 }
Mark Rathjend891f012017-01-19 04:10:37 +00001108
Christopher Tateb218e762017-04-05 16:34:07 -07001109 // Not the SSAID; do a straight lookup
1110 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001111 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001112 owningUserId, name);
1113 }
Svetoslav683914b2015-01-15 14:22:26 -08001114 }
1115
Mark Rathjend891f012017-01-19 04:10:37 +00001116 private boolean isNewSsaidSetting(String name) {
1117 return Settings.Secure.ANDROID_ID.equals(name)
1118 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1119 }
1120
Christopher Tateb218e762017-04-05 16:34:07 -07001121 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001122 // Get uid of caller (key) used to store ssaid value
1123 String name = Integer.toString(
1124 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1125
1126 if (DEBUG) {
1127 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1128 }
1129
1130 // Retrieve the ssaid from the table if present.
1131 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1132 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001133 // If the app is an Instant App use its stored SSAID instead of our own.
1134 final String instantSsaid;
1135 final long token = Binder.clearCallingIdentity();
1136 try {
1137 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1138 owningUserId);
1139 } catch (RemoteException e) {
1140 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1141 return null;
1142 } finally {
1143 Binder.restoreCallingIdentity(token);
1144 }
Svet Ganov96c99462017-05-05 14:27:13 -07001145
1146 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1147 SETTINGS_TYPE_SSAID, owningUserId);
1148
Chad Brubaker0d277a72017-04-12 16:56:53 -07001149 if (instantSsaid != null) {
1150 // Use the stored value if it is still valid.
1151 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001152 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001153 }
1154 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001155 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1156 true, callingPkg.packageName);
1157 if (!success) {
1158 throw new IllegalStateException("Failed to update instant app android id");
1159 }
Svet Ganov96c99462017-05-05 14:27:13 -07001160 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1161 owningUserId, name);
1162 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001163 }
Mark Rathjend891f012017-01-19 04:10:37 +00001164
1165 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001166 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001167 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1168 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001169 }
1170
Svet Ganov96c99462017-05-05 14:27:13 -07001171 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1172 }
1173
1174 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1175 // SSAID settings are located in a dedicated table for internal bookkeeping
1176 // but for the world they reside in the secure table, so adjust the key here.
1177 // We have a special name when looking it up but want the world to see it as
1178 // "android_id".
1179 if (ssaidSetting != null) {
1180 return settingsState.new Setting(ssaidSetting) {
1181 @Override
1182 public int getKey() {
1183 final int userId = getUserIdFromKey(super.getKey());
1184 return makeKey(SETTINGS_TYPE_SECURE, userId);
1185 }
1186
1187 @Override
1188 public String getName() {
1189 return Settings.Secure.ANDROID_ID;
1190 }
1191 };
1192 }
1193 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001194 }
1195
Svetoslav Ganove080da92016-12-21 17:10:35 -08001196 private boolean insertSecureSetting(String name, String value, String tag,
1197 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001198 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001199 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001200 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1201 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001202 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001203 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1204 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001205 }
1206
Svet Ganov53a441c2016-04-19 19:38:00 -07001207 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001208 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001209 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1210 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001211 }
1212
Svetoslav Ganove080da92016-12-21 17:10:35 -08001213 return mutateSecureSetting(name, null, null, false, requestingUserId,
1214 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001215 }
1216
Svetoslav Ganove080da92016-12-21 17:10:35 -08001217 private boolean updateSecureSetting(String name, String value, String tag,
1218 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001219 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001220 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001221 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1222 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001223 }
1224
Svetoslav Ganove080da92016-12-21 17:10:35 -08001225 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1226 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001227 }
1228
Svetoslav Ganove080da92016-12-21 17:10:35 -08001229 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1230 if (DEBUG) {
1231 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1232 + mode + ", " + tag + ")");
1233 }
1234
1235 mutateSecureSetting(null, null, tag, false, requestingUserId,
1236 MUTATION_OPERATION_RESET, false, mode);
1237 }
1238
1239 private boolean mutateSecureSetting(String name, String value, String tag,
1240 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1241 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001242 // Make sure the caller can change the settings.
1243 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1244
Svetoslav683914b2015-01-15 14:22:26 -08001245 // Resolve the userId on whose behalf the call is made.
1246 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1247
Makoto Onuki28da2e32015-11-20 11:30:44 -08001248 // If this is a setting that is currently restricted for this user, do not allow
1249 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001250 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001251 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001252 return false;
1253 }
1254
1255 // Determine the owning user as some profile settings are cloned from the parent.
1256 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1257
1258 // Only the owning user can change the setting.
1259 if (owningUserId != callingUserId) {
1260 return false;
1261 }
1262
1263 // Special cases for location providers (sigh).
1264 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001265 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1266 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001267 }
1268
1269 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001270 synchronized (mLock) {
1271 switch (operation) {
1272 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001273 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001274 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001275 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001276 }
Svetoslav683914b2015-01-15 14:22:26 -08001277
Svetoslav7ec28e82015-05-20 17:01:10 -07001278 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001279 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001280 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001281 }
Svetoslav683914b2015-01-15 14:22:26 -08001282
Svetoslav7ec28e82015-05-20 17:01:10 -07001283 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001284 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001285 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001286 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001287 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001288
1289 case MUTATION_OPERATION_RESET: {
1290 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1291 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1292 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001293 }
1294 }
1295
1296 return false;
1297 }
1298
Svetoslav7ec28e82015-05-20 17:01:10 -07001299 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001300 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001301 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001302 }
1303
1304 // Resolve the userId on whose behalf the call is made.
1305 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1306
Svetoslav7ec28e82015-05-20 17:01:10 -07001307 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001308 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001309
Svetoslav7ec28e82015-05-20 17:01:10 -07001310 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001311
Svetoslav7ec28e82015-05-20 17:01:10 -07001312 String[] normalizedProjection = normalizeProjection(projection);
1313 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001314
Svetoslav7ec28e82015-05-20 17:01:10 -07001315 for (int i = 0; i < nameCount; i++) {
1316 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001317
Svetoslav7ec28e82015-05-20 17:01:10 -07001318 // Determine the owning user as some profile settings are cloned from the parent.
1319 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1320 name);
Svetoslav683914b2015-01-15 14:22:26 -08001321
Svetoslav7ec28e82015-05-20 17:01:10 -07001322 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001323 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001324 appendSettingToCursor(result, setting);
1325 }
1326
1327 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001328 }
Svetoslav683914b2015-01-15 14:22:26 -08001329 }
1330
Svetoslav7ec28e82015-05-20 17:01:10 -07001331 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001332 if (DEBUG) {
1333 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1334 }
1335
1336 // Resolve the userId on whose behalf the call is made.
1337 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1338
Chad Brubakera6830e72017-04-28 17:34:36 -07001339 // Ensure the caller can access the setting.
1340 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001341
Svetoslav683914b2015-01-15 14:22:26 -08001342 // Determine the owning user as some profile settings are cloned from the parent.
1343 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1344
1345 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001346 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001347 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001348 }
Svetoslav683914b2015-01-15 14:22:26 -08001349 }
1350
Svetoslav7ec28e82015-05-20 17:01:10 -07001351 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001352 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001353 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001354 + requestingUserId + ")");
1355 }
1356
Svetoslav7ec28e82015-05-20 17:01:10 -07001357 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001358 }
1359
Svetoslav7ec28e82015-05-20 17:01:10 -07001360 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001361 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001362 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001363 }
1364
Svetoslav7ec28e82015-05-20 17:01:10 -07001365 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001366 }
1367
Svetoslav7ec28e82015-05-20 17:01:10 -07001368 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001369 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001370 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001371 + requestingUserId + ")");
1372 }
1373
Svetoslav7ec28e82015-05-20 17:01:10 -07001374 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001375 }
1376
Svetoslav7ec28e82015-05-20 17:01:10 -07001377 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001378 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001379 if (!hasWriteSecureSettingsPermission()) {
1380 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1381 // operation is allowed for the calling package through appops.
1382 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1383 Binder.getCallingUid(), getCallingPackage(), true)) {
1384 return false;
1385 }
Svetoslav683914b2015-01-15 14:22:26 -08001386 }
1387
Svetoslav683914b2015-01-15 14:22:26 -08001388 // Resolve the userId on whose behalf the call is made.
1389 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1390
Svetoslavd8d25e02015-11-20 13:09:26 -08001391 // Enforce what the calling package can mutate the system settings.
1392 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1393
Svetoslav683914b2015-01-15 14:22:26 -08001394 // Determine the owning user as some profile settings are cloned from the parent.
1395 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1396
1397 // Only the owning user id can change the setting.
1398 if (owningUserId != callingUserId) {
1399 return false;
1400 }
1401
Jeff Sharkey413573a2016-02-22 17:52:45 -07001402 // Invalidate any relevant cache files
1403 String cacheName = null;
1404 if (Settings.System.RINGTONE.equals(name)) {
1405 cacheName = Settings.System.RINGTONE_CACHE;
1406 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1407 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1408 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1409 cacheName = Settings.System.ALARM_ALERT_CACHE;
1410 }
1411 if (cacheName != null) {
1412 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001413 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001414 cacheFile.delete();
1415 }
1416
Svetoslav683914b2015-01-15 14:22:26 -08001417 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001418 synchronized (mLock) {
1419 switch (operation) {
1420 case MUTATION_OPERATION_INSERT: {
1421 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001422 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001423 owningUserId, name, value, null, false, getCallingPackage(),
1424 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001425 }
1426
1427 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001428 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001429 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001430 }
1431
1432 case MUTATION_OPERATION_UPDATE: {
1433 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001434 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001435 owningUserId, name, value, null, false, getCallingPackage(),
1436 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001437 }
Svetoslav683914b2015-01-15 14:22:26 -08001438 }
1439
Svetoslav7ec28e82015-05-20 17:01:10 -07001440 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001441 }
Svetoslav683914b2015-01-15 14:22:26 -08001442 }
1443
Billy Lau6ad2d662015-07-18 00:26:58 +01001444 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001445 // Write secure settings is a more protected permission. If caller has it we are good.
1446 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1447 == PackageManager.PERMISSION_GRANTED) {
1448 return true;
1449 }
1450
Svetoslavf41334b2015-06-23 12:06:03 -07001451 return false;
1452 }
1453
Svetoslav683914b2015-01-15 14:22:26 -08001454 private void validateSystemSettingValue(String name, String value) {
1455 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1456 if (validator != null && !validator.validate(value)) {
1457 throw new IllegalArgumentException("Invalid value: " + value
1458 + " for setting: " + name);
1459 }
1460 }
1461
Alex Klyubin1991f572017-03-03 14:08:36 -08001462 /**
1463 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1464 */
1465 private boolean isSecureSettingAccessible(String name, int callingUserId,
1466 int owningUserId) {
1467 // Special case for location (sigh).
1468 // This check is not inside the name-based checks below because this method performs checks
1469 // only if the calling user ID is not the same as the owning user ID.
1470 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1471 return false;
1472 }
1473
1474 switch (name) {
1475 case "bluetooth_address":
1476 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1477 // address in this secure setting. Secure settings can normally be read by any app,
1478 // which thus enables them to bypass the recently introduced restrictions on access
1479 // to device identifiers.
1480 // To mitigate this we make this setting available only to callers privileged to see
1481 // this device's MAC addresses, same as through public API
1482 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1483 return getContext().checkCallingOrSelfPermission(
1484 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1485 default:
1486 return true;
1487 }
1488 }
1489
Svetoslav683914b2015-01-15 14:22:26 -08001490 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1491 int owningUserId) {
1492 // Optimization - location providers are restricted only for managed profiles.
1493 if (callingUserId == owningUserId) {
1494 return false;
1495 }
1496 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1497 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1498 new UserHandle(callingUserId))) {
1499 return true;
1500 }
1501 return false;
1502 }
1503
Makoto Onuki28da2e32015-11-20 11:30:44 -08001504 /**
1505 * Checks whether changing a setting to a value is prohibited by the corresponding user
1506 * restriction.
1507 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001508 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1509 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001510 *
1511 * @return true if the change is prohibited, false if the change is allowed.
1512 */
1513 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001514 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001515 String restriction;
1516 switch (setting) {
1517 case Settings.Secure.LOCATION_MODE:
1518 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1519 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1520 // here normally, but we still protect it here from a direct provider write.
1521 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1522 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1523 break;
1524
1525 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1526 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1527 // a provider, which should be allowed even if the user restriction is set.
1528 if (value != null && value.startsWith("-")) return false;
1529 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1530 break;
1531
1532 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1533 if ("0".equals(value)) return false;
1534 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1535 break;
1536
1537 case Settings.Global.ADB_ENABLED:
1538 if ("0".equals(value)) return false;
1539 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1540 break;
1541
1542 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1543 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1544 if ("1".equals(value)) return false;
1545 restriction = UserManager.ENSURE_VERIFY_APPS;
1546 break;
1547
1548 case Settings.Global.PREFERRED_NETWORK_MODE:
1549 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1550 break;
1551
Victor Chang9c7b7062016-07-12 23:47:29 +01001552 case Settings.Secure.ALWAYS_ON_VPN_APP:
1553 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1554 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001555 final int appId = UserHandle.getAppId(callingUid);
1556 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001557 return false;
1558 }
1559 restriction = UserManager.DISALLOW_CONFIG_VPN;
1560 break;
1561
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001562 case Settings.Global.SAFE_BOOT_DISALLOWED:
1563 if ("1".equals(value)) return false;
1564 restriction = UserManager.DISALLOW_SAFE_BOOT;
1565 break;
1566
Makoto Onuki28da2e32015-11-20 11:30:44 -08001567 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001568 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001569 if ("0".equals(value)) return false;
1570 restriction = UserManager.DISALLOW_DATA_ROAMING;
1571 break;
1572 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001573 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001574 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001575
1576 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001577 }
1578
1579 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1580 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1581 }
1582
1583 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001584 final int parentId;
1585 // Resolves dependency if setting has a dependency and the calling user has a parent
1586 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1587 && (parentId = getGroupParentLocked(userId)) != userId) {
1588 // The setting has a dependency and the profile has a parent
1589 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001590 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1591 final long token = Binder.clearCallingIdentity();
1592 try {
1593 Setting settingObj = getSecureSetting(dependency, userId);
1594 if (settingObj != null && settingObj.getValue().equals("1")) {
1595 return parentId;
1596 }
1597 } finally {
1598 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001599 }
1600 }
Svetoslav683914b2015-01-15 14:22:26 -08001601 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1602 }
1603
1604 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1605 final int parentId = getGroupParentLocked(userId);
1606 if (parentId != userId && keys.contains(name)) {
1607 return parentId;
1608 }
1609 return userId;
1610 }
1611
Svetoslavf41334b2015-06-23 12:06:03 -07001612 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001613 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001614 // System/root/shell can mutate whatever secure settings they want.
1615 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001616 final int appId = UserHandle.getAppId(callingUid);
1617 if (appId == android.os.Process.SYSTEM_UID
1618 || appId == Process.SHELL_UID
1619 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001620 return;
1621 }
1622
1623 switch (operation) {
1624 case MUTATION_OPERATION_INSERT:
1625 // Insert updates.
1626 case MUTATION_OPERATION_UPDATE: {
1627 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1628 return;
1629 }
1630
1631 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001632 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001633
1634 // Privileged apps can do whatever they want.
1635 if ((packageInfo.applicationInfo.privateFlags
1636 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1637 return;
1638 }
1639
1640 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1641 packageInfo.applicationInfo.targetSdkVersion, name);
1642 } break;
1643
1644 case MUTATION_OPERATION_DELETE: {
1645 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1646 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1647 throw new IllegalArgumentException("You cannot delete system defined"
1648 + " secure settings.");
1649 }
1650
1651 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001652 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001653
1654 // Privileged apps can do whatever they want.
1655 if ((packageInfo.applicationInfo.privateFlags &
1656 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1657 return;
1658 }
1659
1660 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1661 packageInfo.applicationInfo.targetSdkVersion, name);
1662 } break;
1663 }
1664 }
1665
Todd Kennedybe0b8892017-02-15 14:13:52 -08001666 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001667 switch (settingsType) {
1668 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001669 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001670 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001671 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001672 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001673 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001674 default:
1675 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1676 }
1677 }
1678
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001679 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1680 switch (settingsType) {
1681 case SETTINGS_TYPE_GLOBAL:
1682 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1683 case SETTINGS_TYPE_SYSTEM:
1684 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1685 case SETTINGS_TYPE_SECURE:
1686 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1687 default:
1688 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1689 }
1690 }
1691
Chad Brubaker97bccee2017-01-05 15:51:41 -08001692 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001693 boolean instantApp;
1694 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1695 instantApp = false;
1696 } else {
1697 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1698 instantApp = ai.isInstantApp();
1699 }
1700 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001701 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001702 } else {
1703 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1704 }
1705 }
1706
Chad Brubakera6830e72017-04-28 17:34:36 -07001707 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001708 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1709 return;
1710 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001711 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001712 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001713 return;
1714 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001715 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1716 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001717 throw new SecurityException("Setting " + settingName + " is not accessible from"
1718 + " ephemeral package " + getCallingPackage());
1719 }
1720 }
1721
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001722 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1723 // We always use the callingUid for this lookup. This means that if hypothetically an
1724 // app was installed in user A with cross user and in user B as an Instant App
1725 // the app in A would be able to see all the settings in user B. However since cross
1726 // user is a system permission and the app must be uninstalled in B and then installed as
1727 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001728 ApplicationInfo ai = null;
1729 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001730 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1731 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001732 } catch (RemoteException ignored) {
1733 }
1734 if (ai == null) {
1735 throw new IllegalStateException("Failed to lookup info for package "
1736 + getCallingPackage());
1737 }
1738 return ai;
1739 }
1740
Xiaohui Chen43765b72015-08-31 10:57:33 -07001741 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001742 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001743 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1744 getCallingPackage(), 0, userId);
1745 if (packageInfo != null) {
1746 return packageInfo;
1747 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001748 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001749 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001750 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001751 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001752 }
1753
1754 private int getGroupParentLocked(int userId) {
1755 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001756 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001757 return userId;
1758 }
1759 // We are in the same process with the user manager and the returned
1760 // user info is a cached instance, so just look up instead of cache.
1761 final long identity = Binder.clearCallingIdentity();
1762 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001763 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001764 UserInfo userInfo = mUserManager.getProfileParent(userId);
1765 return (userInfo != null) ? userInfo.id : userId;
1766 } finally {
1767 Binder.restoreCallingIdentity(identity);
1768 }
1769 }
1770
Svetoslav683914b2015-01-15 14:22:26 -08001771 private void enforceWritePermission(String permission) {
1772 if (getContext().checkCallingOrSelfPermission(permission)
1773 != PackageManager.PERMISSION_GRANTED) {
1774 throw new SecurityException("Permission denial: writing to settings requires:"
1775 + permission);
1776 }
1777 }
1778
1779 /*
1780 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1781 * This setting contains a list of the currently enabled location providers.
1782 * But helper functions in android.providers.Settings can enable or disable
1783 * a single provider by using a "+" or "-" prefix before the provider name.
1784 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001785 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1786 * is set, the said method will only allow values with the "-" prefix.
1787 *
Svetoslav683914b2015-01-15 14:22:26 -08001788 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001789 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001790 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1791 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001792 if (TextUtils.isEmpty(value)) {
1793 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001794 }
1795
Svetoslav683914b2015-01-15 14:22:26 -08001796 final char prefix = value.charAt(0);
1797 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001798 if (forceNotify) {
1799 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1800 mSettingsRegistry.notifyForSettingsChange(key,
1801 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1802 }
Svetoslav683914b2015-01-15 14:22:26 -08001803 return false;
1804 }
1805
1806 // skip prefix
1807 value = value.substring(1);
1808
Svetoslav7ec28e82015-05-20 17:01:10 -07001809 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001810 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001811 if (settingValue == null) {
1812 return false;
1813 }
Svetoslav683914b2015-01-15 14:22:26 -08001814
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001815 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001816
1817 int index = oldProviders.indexOf(value);
1818 int end = index + value.length();
1819
1820 // check for commas to avoid matching on partial string
1821 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1822 index = -1;
1823 }
1824
1825 // check for commas to avoid matching on partial string
1826 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1827 index = -1;
1828 }
1829
1830 String newProviders;
1831
1832 if (prefix == '+' && index < 0) {
1833 // append the provider to the list if not present
1834 if (oldProviders.length() == 0) {
1835 newProviders = value;
1836 } else {
1837 newProviders = oldProviders + ',' + value;
1838 }
1839 } else if (prefix == '-' && index >= 0) {
1840 // remove the provider from the list if present
1841 // remove leading or trailing comma
1842 if (index > 0) {
1843 index--;
1844 } else if (end < oldProviders.length()) {
1845 end++;
1846 }
1847
1848 newProviders = oldProviders.substring(0, index);
1849 if (end < oldProviders.length()) {
1850 newProviders += oldProviders.substring(end);
1851 }
1852 } else {
1853 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001854 if (forceNotify) {
1855 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1856 mSettingsRegistry.notifyForSettingsChange(key,
1857 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1858 }
Svetoslav683914b2015-01-15 14:22:26 -08001859 return false;
1860 }
1861
Svet Ganov53a441c2016-04-19 19:38:00 -07001862 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001863 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001864 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001865 }
1866
Svetoslav683914b2015-01-15 14:22:26 -08001867 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1868 int targetSdkVersion, String name) {
1869 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1870 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1871 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1872 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1873 + " This will soon become an error.");
1874 } else {
1875 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1876 + " This will soon become an error.");
1877 }
1878 } else {
1879 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1880 throw new IllegalArgumentException("You cannot change private secure settings.");
1881 } else {
1882 throw new IllegalArgumentException("You cannot keep your settings in"
1883 + " the secure settings.");
1884 }
1885 }
1886 }
1887
1888 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1889 if (requestingUserId == UserHandle.getCallingUserId()) {
1890 return requestingUserId;
1891 }
1892 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1893 Binder.getCallingUid(), requestingUserId, false, true,
1894 "get/set setting for user", null);
1895 }
1896
Svet Ganov53a441c2016-04-19 19:38:00 -07001897 private Bundle packageValueForCallResult(Setting setting,
1898 boolean trackingGeneration) {
1899 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001900 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001901 return NULL_SETTING_BUNDLE;
1902 }
1903 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001904 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001905 Bundle result = new Bundle();
1906 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001907 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001908
Svetoslav Ganove080da92016-12-21 17:10:35 -08001909 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001910 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001911 }
1912
1913 private static int getRequestingUserId(Bundle args) {
1914 final int callingUserId = UserHandle.getCallingUserId();
1915 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1916 : callingUserId;
1917 }
1918
Svet Ganov53a441c2016-04-19 19:38:00 -07001919 private boolean isTrackingGeneration(Bundle args) {
1920 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1921 }
1922
Svetoslav683914b2015-01-15 14:22:26 -08001923 private static String getSettingValue(Bundle args) {
1924 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1925 }
1926
Svetoslav Ganove080da92016-12-21 17:10:35 -08001927 private static String getSettingTag(Bundle args) {
1928 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1929 }
1930
1931 private static boolean getSettingMakeDefault(Bundle args) {
1932 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1933 }
1934
1935 private static int getResetModeEnforcingPermission(Bundle args) {
1936 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1937 switch (mode) {
1938 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1939 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1940 throw new SecurityException("Only system, shell/root on a "
1941 + "debuggable build can reset to untrusted defaults");
1942 }
1943 return mode;
1944 }
1945 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1946 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1947 throw new SecurityException("Only system, shell/root on a "
1948 + "debuggable build can reset untrusted changes");
1949 }
1950 return mode;
1951 }
1952 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1953 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1954 throw new SecurityException("Only system, shell/root on a "
1955 + "debuggable build can reset to trusted defaults");
1956 }
1957 return mode;
1958 }
1959 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1960 return mode;
1961 }
1962 }
1963 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1964 }
1965
1966 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1967 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1968 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1969 && (appId == SHELL_UID || appId == ROOT_UID));
1970 }
1971
Svetoslav683914b2015-01-15 14:22:26 -08001972 private static String getValidTableOrThrow(Uri uri) {
1973 if (uri.getPathSegments().size() > 0) {
1974 String table = uri.getPathSegments().get(0);
1975 if (DatabaseHelper.isValidTable(table)) {
1976 return table;
1977 }
1978 throw new IllegalArgumentException("Bad root path: " + table);
1979 }
1980 throw new IllegalArgumentException("Invalid URI:" + uri);
1981 }
1982
1983 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001984 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001985 return new MatrixCursor(projection, 0);
1986 }
1987 MatrixCursor cursor = new MatrixCursor(projection, 1);
1988 appendSettingToCursor(cursor, setting);
1989 return cursor;
1990 }
1991
1992 private static String[] normalizeProjection(String[] projection) {
1993 if (projection == null) {
1994 return ALL_COLUMNS;
1995 }
1996
1997 final int columnCount = projection.length;
1998 for (int i = 0; i < columnCount; i++) {
1999 String column = projection[i];
2000 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2001 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002002 }
2003 }
2004
Svetoslav683914b2015-01-15 14:22:26 -08002005 return projection;
2006 }
2007
2008 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002009 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002010 return;
2011 }
Svetoslav683914b2015-01-15 14:22:26 -08002012 final int columnCount = cursor.getColumnCount();
2013
2014 String[] values = new String[columnCount];
2015
2016 for (int i = 0; i < columnCount; i++) {
2017 String column = cursor.getColumnName(i);
2018
2019 switch (column) {
2020 case Settings.NameValueTable._ID: {
2021 values[i] = setting.getId();
2022 } break;
2023
2024 case Settings.NameValueTable.NAME: {
2025 values[i] = setting.getName();
2026 } break;
2027
2028 case Settings.NameValueTable.VALUE: {
2029 values[i] = setting.getValue();
2030 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002031 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002032 }
2033
Svetoslav683914b2015-01-15 14:22:26 -08002034 cursor.addRow(values);
2035 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002036
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002037 private static boolean isKeyValid(String key) {
2038 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2039 }
2040
Svetoslav683914b2015-01-15 14:22:26 -08002041 private static final class Arguments {
2042 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2043 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2044
2045 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2046 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2047
2048 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2049 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2050
2051 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2052 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2053
2054 public final String table;
2055 public final String name;
2056
2057 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2058 final int segmentSize = uri.getPathSegments().size();
2059 switch (segmentSize) {
2060 case 1: {
2061 if (where != null
2062 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2063 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2064 && whereArgs.length == 1) {
2065 name = whereArgs[0];
2066 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002067 return;
Svetoslav683914b2015-01-15 14:22:26 -08002068 } else if (where != null
2069 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2070 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2071 final int startIndex = Math.max(where.indexOf("'"),
2072 where.indexOf("\"")) + 1;
2073 final int endIndex = Math.max(where.lastIndexOf("'"),
2074 where.lastIndexOf("\""));
2075 name = where.substring(startIndex, endIndex);
2076 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002077 return;
Svetoslav683914b2015-01-15 14:22:26 -08002078 } else if (supportAll && where == null && whereArgs == null) {
2079 name = null;
2080 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002081 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002082 }
Svetoslav683914b2015-01-15 14:22:26 -08002083 } break;
2084
Svetoslav28494652015-02-12 14:11:42 -08002085 case 2: {
2086 if (where == null && whereArgs == null) {
2087 name = uri.getPathSegments().get(1);
2088 table = computeTableForSetting(uri, name);
2089 return;
2090 }
2091 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002092 }
Svetoslav28494652015-02-12 14:11:42 -08002093
2094 EventLogTags.writeUnsupportedSettingsQuery(
2095 uri.toSafeString(), where, Arrays.toString(whereArgs));
2096 String message = String.format( "Supported SQL:\n"
2097 + " uri content://some_table/some_property with null where and where args\n"
2098 + " uri content://some_table with query name=? and single name as arg\n"
2099 + " uri content://some_table with query name=some_name and null args\n"
2100 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2101 Arrays.toString(whereArgs));
2102 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002103 }
2104
Svetoslav28494652015-02-12 14:11:42 -08002105 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002106 String table = getValidTableOrThrow(uri);
2107
2108 if (name != null) {
2109 if (sSystemMovedToSecureSettings.contains(name)) {
2110 table = TABLE_SECURE;
2111 }
2112
2113 if (sSystemMovedToGlobalSettings.contains(name)) {
2114 table = TABLE_GLOBAL;
2115 }
2116
2117 if (sSecureMovedToGlobalSettings.contains(name)) {
2118 table = TABLE_GLOBAL;
2119 }
2120
2121 if (sGlobalMovedToSecureSettings.contains(name)) {
2122 table = TABLE_SECURE;
2123 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002124 }
Svetoslav683914b2015-01-15 14:22:26 -08002125
2126 return table;
2127 }
2128 }
2129
2130 final class SettingsRegistry {
2131 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2132
Svetoslav683914b2015-01-15 14:22:26 -08002133 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2134 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2135 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002136 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2137
2138 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002139
2140 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2141
Svet Ganov53a441c2016-04-19 19:38:00 -07002142 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002143
Svetoslav7e0683b2015-08-03 16:02:52 -07002144 private final Handler mHandler;
2145
Svet Ganov53a441c2016-04-19 19:38:00 -07002146 private final BackupManager mBackupManager;
2147
Amith Yamasani39452022017-03-21 15:23:47 -07002148 private String mSettingsCreationBuildId;
2149
Svetoslav683914b2015-01-15 14:22:26 -08002150 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002151 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002152 mGenerationRegistry = new GenerationRegistry(mLock);
2153 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002154 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002155 syncSsaidTableOnStart();
2156 }
2157
2158 private void generateUserKeyLocked(int userId) {
2159 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002160 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002161 final SecureRandom rand = new SecureRandom();
2162 rand.nextBytes(keyBytes);
2163
2164 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002165 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002166
2167 // Store the key in the ssaid table.
2168 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2169 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2170 true, SettingsState.SYSTEM_PACKAGE_NAME);
2171
2172 if (!success) {
2173 throw new IllegalStateException("Ssaid settings not accessible");
2174 }
2175 }
2176
Mark Rathjen7599f132017-01-23 14:15:54 -08002177 private byte[] getLengthPrefix(byte[] data) {
2178 return ByteBuffer.allocate(4).putInt(data.length).array();
2179 }
2180
Christopher Tateb218e762017-04-05 16:34:07 -07002181 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002182 // Read the user's key from the ssaid table.
2183 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002184 if (userKeySetting == null || userKeySetting.isNull()
2185 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002186 // Lazy initialize and store the user key.
2187 generateUserKeyLocked(userId);
2188 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002189 if (userKeySetting == null || userKeySetting.isNull()
2190 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002191 throw new IllegalStateException("User key not accessible");
2192 }
2193 }
2194 final String userKey = userKeySetting.getValue();
2195
2196 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002197 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2198
2199 // Validate that the key is of expected length.
2200 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2201 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002202 throw new IllegalStateException("User key invalid");
2203 }
2204
Mark Rathjen7599f132017-01-23 14:15:54 -08002205 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002206 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002207 m = Mac.getInstance("HmacSHA256");
2208 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002209 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002210 throw new IllegalStateException("HmacSHA256 is not available", e);
2211 } catch (InvalidKeyException e) {
2212 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002213 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002214
Mark Rathjenf42dd912017-06-05 19:04:34 -07002215 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002216 for (int i = 0; i < callingPkg.signatures.length; i++) {
2217 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002218 m.update(getLengthPrefix(sig), 0, 4);
2219 m.update(sig);
2220 }
Mark Rathjend891f012017-01-19 04:10:37 +00002221
2222 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002223 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2224 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002225
2226 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002227 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002228 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2229 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002230 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002231
2232 if (!success) {
2233 throw new IllegalStateException("Ssaid settings not accessible");
2234 }
2235
2236 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2237 }
2238
2239 public void syncSsaidTableOnStart() {
2240 synchronized (mLock) {
2241 // Verify that each user's packages and ssaid's are in sync.
2242 for (UserInfo user : mUserManager.getUsers(true)) {
2243 // Get all uids for the user's packages.
2244 final List<PackageInfo> packages;
2245 try {
2246 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2247 } catch (RemoteException e) {
2248 throw new IllegalStateException("Package manager not available");
2249 }
2250 final Set<String> appUids = new HashSet<>();
2251 for (PackageInfo info : packages) {
2252 appUids.add(Integer.toString(info.applicationInfo.uid));
2253 }
2254
2255 // Get all uids currently stored in the user's ssaid table.
2256 final Set<String> ssaidUids = new HashSet<>(
2257 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2258 ssaidUids.remove(SSAID_USER_KEY);
2259
2260 // Perform a set difference for the appUids and ssaidUids.
2261 ssaidUids.removeAll(appUids);
2262
2263 // If there are ssaidUids left over they need to be removed from the table.
2264 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2265 user.id);
2266 for (String uid : ssaidUids) {
2267 ssaidSettings.deleteSettingLocked(uid);
2268 }
2269 }
2270 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002271 }
2272
Svetoslav683914b2015-01-15 14:22:26 -08002273 public List<String> getSettingsNamesLocked(int type, int userId) {
2274 final int key = makeKey(type, userId);
2275 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002276 if (settingsState == null) {
2277 return new ArrayList<String>();
2278 }
Svetoslav683914b2015-01-15 14:22:26 -08002279 return settingsState.getSettingNamesLocked();
2280 }
2281
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002282 public SparseBooleanArray getKnownUsersLocked() {
2283 SparseBooleanArray users = new SparseBooleanArray();
2284 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2285 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2286 }
2287 return users;
2288 }
2289
Svetoslav683914b2015-01-15 14:22:26 -08002290 public SettingsState getSettingsLocked(int type, int userId) {
2291 final int key = makeKey(type, userId);
2292 return peekSettingsStateLocked(key);
2293 }
2294
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002295 public boolean ensureSettingsForUserLocked(int userId) {
2296 // First make sure this user actually exists.
2297 if (mUserManager.getUserInfo(userId) == null) {
2298 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2299 return false;
2300 }
2301
Svetoslav683914b2015-01-15 14:22:26 -08002302 // Migrate the setting for this user if needed.
2303 migrateLegacySettingsForUserIfNeededLocked(userId);
2304
2305 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002306 if (userId == UserHandle.USER_SYSTEM) {
2307 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002308 ensureSettingsStateLocked(globalKey);
2309 }
2310
2311 // Ensure secure settings loaded.
2312 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2313 ensureSettingsStateLocked(secureKey);
2314
2315 // Make sure the secure settings have an Android id set.
2316 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2317 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2318
2319 // Ensure system settings loaded.
2320 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2321 ensureSettingsStateLocked(systemKey);
2322
Mark Rathjend891f012017-01-19 04:10:37 +00002323 // Ensure secure settings loaded.
2324 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2325 ensureSettingsStateLocked(ssaidKey);
2326
Svetoslav683914b2015-01-15 14:22:26 -08002327 // Upgrade the settings to the latest version.
2328 UpgradeController upgrader = new UpgradeController(userId);
2329 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002330 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002331 }
2332
2333 private void ensureSettingsStateLocked(int key) {
2334 if (mSettingsStates.get(key) == null) {
2335 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002336 SettingsState settingsState = new SettingsState(getContext(), mLock,
2337 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002338 mSettingsStates.put(key, settingsState);
2339 }
2340 }
2341
2342 public void removeUserStateLocked(int userId, boolean permanently) {
2343 // We always keep the global settings in memory.
2344
2345 // Nuke system settings.
2346 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2347 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2348 if (systemSettingsState != null) {
2349 if (permanently) {
2350 mSettingsStates.remove(systemKey);
2351 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002352 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002353 systemSettingsState.destroyLocked(new Runnable() {
2354 @Override
2355 public void run() {
2356 mSettingsStates.remove(systemKey);
2357 }
2358 });
2359 }
2360 }
2361
2362 // Nuke secure settings.
2363 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2364 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2365 if (secureSettingsState != null) {
2366 if (permanently) {
2367 mSettingsStates.remove(secureKey);
2368 secureSettingsState.destroyLocked(null);
2369 } else {
2370 secureSettingsState.destroyLocked(new Runnable() {
2371 @Override
2372 public void run() {
2373 mSettingsStates.remove(secureKey);
2374 }
2375 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002376 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002377 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002378
Mark Rathjend891f012017-01-19 04:10:37 +00002379 // Nuke ssaid settings.
2380 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2381 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2382 if (ssaidSettingsState != null) {
2383 if (permanently) {
2384 mSettingsStates.remove(ssaidKey);
2385 ssaidSettingsState.destroyLocked(null);
2386 } else {
2387 ssaidSettingsState.destroyLocked(new Runnable() {
2388 @Override
2389 public void run() {
2390 mSettingsStates.remove(ssaidKey);
2391 }
2392 });
2393 }
2394 }
2395
Svet Ganov53a441c2016-04-19 19:38:00 -07002396 // Nuke generation tracking data
2397 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002398 }
2399
Svetoslav683914b2015-01-15 14:22:26 -08002400 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002401 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2402 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002403 final int key = makeKey(type, userId);
2404
Svetoslav Ganove080da92016-12-21 17:10:35 -08002405 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002406 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002407 if (settingsState != null) {
2408 success = settingsState.insertSettingLocked(name, value,
2409 tag, makeDefault, packageName);
2410 }
Svetoslav683914b2015-01-15 14:22:26 -08002411
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002412 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2413 settingsState.persistSyncLocked();
2414 }
2415
Svet Ganov53a441c2016-04-19 19:38:00 -07002416 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002417 notifyForSettingsChange(key, name);
2418 }
2419 return success;
2420 }
2421
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002422 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2423 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002424 final int key = makeKey(type, userId);
2425
Svetoslav Ganove080da92016-12-21 17:10:35 -08002426 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002427 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002428 if (settingsState != null) {
2429 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002430 }
Svetoslav683914b2015-01-15 14:22:26 -08002431
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002432 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2433 settingsState.persistSyncLocked();
2434 }
2435
Svet Ganov53a441c2016-04-19 19:38:00 -07002436 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002437 notifyForSettingsChange(key, name);
2438 }
2439 return success;
2440 }
2441
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002442 public boolean updateSettingLocked(int type, int userId, String name, String value,
2443 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2444 Set<String> criticalSettings) {
2445 final int key = makeKey(type, userId);
2446
2447 boolean success = false;
2448 SettingsState settingsState = peekSettingsStateLocked(key);
2449 if (settingsState != null) {
2450 success = settingsState.updateSettingLocked(name, value, tag,
2451 makeDefault, packageName);
2452 }
2453
2454 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2455 settingsState.persistSyncLocked();
2456 }
2457
2458 if (forceNotify || success) {
2459 notifyForSettingsChange(key, name);
2460 }
2461
2462 return success;
2463 }
2464
Svetoslav683914b2015-01-15 14:22:26 -08002465 public Setting getSettingLocked(int type, int userId, String name) {
2466 final int key = makeKey(type, userId);
2467
2468 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002469 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002470 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002471 }
Mark Rathjend891f012017-01-19 04:10:37 +00002472
2473 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002474 return settingsState.getSettingLocked(name);
2475 }
2476
Svetoslav Ganove080da92016-12-21 17:10:35 -08002477 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2478 String tag) {
2479 final int key = makeKey(type, userId);
2480 SettingsState settingsState = peekSettingsStateLocked(key);
2481 if (settingsState == null) {
2482 return;
2483 }
2484
2485 switch (mode) {
2486 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2487 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002488 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002489 Setting setting = settingsState.getSettingLocked(name);
2490 if (packageName.equals(setting.getPackageName())) {
2491 if (tag != null && !tag.equals(setting.getTag())) {
2492 continue;
2493 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002494 if (settingsState.resetSettingLocked(name)) {
2495 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002496 notifyForSettingsChange(key, name);
2497 }
2498 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002499 if (someSettingChanged) {
2500 settingsState.persistSyncLocked();
2501 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002502 }
2503 } break;
2504
2505 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2506 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002507 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002508 Setting setting = settingsState.getSettingLocked(name);
2509 if (!SettingsState.isSystemPackage(getContext(),
2510 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002511 if (settingsState.resetSettingLocked(name)) {
2512 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002513 notifyForSettingsChange(key, name);
2514 }
2515 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002516 if (someSettingChanged) {
2517 settingsState.persistSyncLocked();
2518 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002519 }
2520 } break;
2521
2522 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2523 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002524 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002525 Setting setting = settingsState.getSettingLocked(name);
2526 if (!SettingsState.isSystemPackage(getContext(),
2527 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002528 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002529 if (settingsState.resetSettingLocked(name)) {
2530 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002531 notifyForSettingsChange(key, name);
2532 }
2533 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002534 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002535 notifyForSettingsChange(key, name);
2536 }
2537 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002538 if (someSettingChanged) {
2539 settingsState.persistSyncLocked();
2540 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002541 }
2542 } break;
2543
2544 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2545 for (String name : settingsState.getSettingNamesLocked()) {
2546 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002547 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002548 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002549 if (settingsState.resetSettingLocked(name)) {
2550 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002551 notifyForSettingsChange(key, name);
2552 }
2553 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002554 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002555 notifyForSettingsChange(key, name);
2556 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002557 if (someSettingChanged) {
2558 settingsState.persistSyncLocked();
2559 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002560 }
2561 } break;
2562 }
2563 }
2564
Svetoslav683914b2015-01-15 14:22:26 -08002565 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002566 // Global and secure settings are signature protected. Apps signed
2567 // by the platform certificate are generally not uninstalled and
2568 // the main exception is tests. We trust components signed
2569 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002570
2571 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2572 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002573 if (systemSettings != null) {
2574 systemSettings.onPackageRemovedLocked(packageName);
2575 }
Svetoslav683914b2015-01-15 14:22:26 -08002576 }
2577
Mark Rathjend891f012017-01-19 04:10:37 +00002578 public void onUidRemovedLocked(int uid) {
2579 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2580 UserHandle.getUserId(uid));
2581 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2582 }
2583
Svetoslav683914b2015-01-15 14:22:26 -08002584 private SettingsState peekSettingsStateLocked(int key) {
2585 SettingsState settingsState = mSettingsStates.get(key);
2586 if (settingsState != null) {
2587 return settingsState;
2588 }
2589
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002590 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2591 return null;
2592 }
Svetoslav683914b2015-01-15 14:22:26 -08002593 return mSettingsStates.get(key);
2594 }
2595
2596 private void migrateAllLegacySettingsIfNeeded() {
2597 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002598 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002599 File globalFile = getSettingsFile(key);
2600 if (globalFile.exists()) {
2601 return;
2602 }
2603
Amith Yamasani39452022017-03-21 15:23:47 -07002604 mSettingsCreationBuildId = Build.ID;
2605
Svetoslav683914b2015-01-15 14:22:26 -08002606 final long identity = Binder.clearCallingIdentity();
2607 try {
2608 List<UserInfo> users = mUserManager.getUsers(true);
2609
2610 final int userCount = users.size();
2611 for (int i = 0; i < userCount; i++) {
2612 final int userId = users.get(i).id;
2613
2614 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2615 SQLiteDatabase database = dbHelper.getWritableDatabase();
2616 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2617
2618 // Upgrade to the latest version.
2619 UpgradeController upgrader = new UpgradeController(userId);
2620 upgrader.upgradeIfNeededLocked();
2621
2622 // Drop from memory if not a running user.
2623 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2624 removeUserStateLocked(userId, false);
2625 }
2626 }
2627 } finally {
2628 Binder.restoreCallingIdentity(identity);
2629 }
2630 }
2631 }
2632
2633 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2634 // Every user has secure settings and if no file we need to migrate.
2635 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2636 File secureFile = getSettingsFile(secureKey);
2637 if (secureFile.exists()) {
2638 return;
2639 }
2640
2641 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2642 SQLiteDatabase database = dbHelper.getWritableDatabase();
2643
2644 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2645 }
2646
2647 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2648 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002649 // Move over the system settings.
2650 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2651 ensureSettingsStateLocked(systemKey);
2652 SettingsState systemSettings = mSettingsStates.get(systemKey);
2653 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2654 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002655
2656 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002657 // Do this after System settings, since this is the first thing we check when deciding
2658 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002659 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2660 ensureSettingsStateLocked(secureKey);
2661 SettingsState secureSettings = mSettingsStates.get(secureKey);
2662 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2663 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2664 secureSettings.persistSyncLocked();
2665
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002666 // Move over the global settings if owner.
2667 // Do this last, since this is the first thing we check when deciding
2668 // to skip over migration from db to xml for owner user.
2669 if (userId == UserHandle.USER_SYSTEM) {
2670 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2671 ensureSettingsStateLocked(globalKey);
2672 SettingsState globalSettings = mSettingsStates.get(globalKey);
2673 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002674 // If this was just created
2675 if (mSettingsCreationBuildId != null) {
2676 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2677 mSettingsCreationBuildId, null, true,
2678 SettingsState.SYSTEM_PACKAGE_NAME);
2679 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002680 globalSettings.persistSyncLocked();
2681 }
Svetoslav683914b2015-01-15 14:22:26 -08002682
2683 // Drop the database as now all is moved and persisted.
2684 if (DROP_DATABASE_ON_MIGRATION) {
2685 dbHelper.dropDatabase();
2686 } else {
2687 dbHelper.backupDatabase();
2688 }
2689 }
2690
2691 private void migrateLegacySettingsLocked(SettingsState settingsState,
2692 SQLiteDatabase database, String table) {
2693 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2694 queryBuilder.setTables(table);
2695
2696 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2697 null, null, null, null, null);
2698
2699 if (cursor == null) {
2700 return;
2701 }
2702
2703 try {
2704 if (!cursor.moveToFirst()) {
2705 return;
2706 }
2707
2708 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2709 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2710
2711 settingsState.setVersionLocked(database.getVersion());
2712
2713 while (!cursor.isAfterLast()) {
2714 String name = cursor.getString(nameColumnIdx);
2715 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002716 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002717 SettingsState.SYSTEM_PACKAGE_NAME);
2718 cursor.moveToNext();
2719 }
2720 } finally {
2721 cursor.close();
2722 }
2723 }
2724
2725 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2726 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2727
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002728 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002729 return;
2730 }
2731
2732 final int userId = getUserIdFromKey(secureSettings.mKey);
2733
2734 final UserInfo user;
2735 final long identity = Binder.clearCallingIdentity();
2736 try {
2737 user = mUserManager.getUserInfo(userId);
2738 } finally {
2739 Binder.restoreCallingIdentity(identity);
2740 }
2741 if (user == null) {
2742 // Can happen due to races when deleting users - treat as benign.
2743 return;
2744 }
2745
2746 String androidId = Long.toHexString(new SecureRandom().nextLong());
2747 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002748 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002749
2750 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2751 + "] for user " + userId);
2752
2753 // Write a drop box entry if it's a restricted profile
2754 if (user.isRestricted()) {
2755 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2756 Context.DROPBOX_SERVICE);
2757 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2758 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2759 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2760 }
2761 }
2762 }
2763
2764 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002765 final int userId = getUserIdFromKey(key);
2766 Uri uri = getNotificationUriFor(key, name);
2767
Phil Weaver83fec002016-05-11 10:55:29 -07002768 mGenerationRegistry.incrementGeneration(key);
2769
Svetoslav7e0683b2015-08-03 16:02:52 -07002770 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2771 userId, 0, uri).sendToTarget();
2772
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002773 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002774 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2775 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002776 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2777 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002778 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002779 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2780 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002781 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002782
Svet Ganov53a441c2016-04-19 19:38:00 -07002783 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002784 }
2785
Svet Ganov53a441c2016-04-19 19:38:00 -07002786 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002787 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002788 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002789 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002790 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002791 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002792 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002793 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002794 final int key = makeKey(type, profileId);
2795 mGenerationRegistry.incrementGeneration(key);
2796
2797 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002798 }
2799 }
2800 }
Svetoslav683914b2015-01-15 14:22:26 -08002801 }
2802
Svetoslav683914b2015-01-15 14:22:26 -08002803 private boolean isGlobalSettingsKey(int key) {
2804 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2805 }
2806
2807 private boolean isSystemSettingsKey(int key) {
2808 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2809 }
2810
2811 private boolean isSecureSettingsKey(int key) {
2812 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2813 }
2814
Mark Rathjend891f012017-01-19 04:10:37 +00002815 private boolean isSsaidSettingsKey(int key) {
2816 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2817 }
2818
Svetoslav683914b2015-01-15 14:22:26 -08002819 private File getSettingsFile(int key) {
2820 if (isGlobalSettingsKey(key)) {
2821 final int userId = getUserIdFromKey(key);
2822 return new File(Environment.getUserSystemDirectory(userId),
2823 SETTINGS_FILE_GLOBAL);
2824 } else if (isSystemSettingsKey(key)) {
2825 final int userId = getUserIdFromKey(key);
2826 return new File(Environment.getUserSystemDirectory(userId),
2827 SETTINGS_FILE_SYSTEM);
2828 } else if (isSecureSettingsKey(key)) {
2829 final int userId = getUserIdFromKey(key);
2830 return new File(Environment.getUserSystemDirectory(userId),
2831 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002832 } else if (isSsaidSettingsKey(key)) {
2833 final int userId = getUserIdFromKey(key);
2834 return new File(Environment.getUserSystemDirectory(userId),
2835 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002836 } else {
2837 throw new IllegalArgumentException("Invalid settings key:" + key);
2838 }
2839 }
2840
2841 private Uri getNotificationUriFor(int key, String name) {
2842 if (isGlobalSettingsKey(key)) {
2843 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2844 : Settings.Global.CONTENT_URI;
2845 } else if (isSecureSettingsKey(key)) {
2846 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2847 : Settings.Secure.CONTENT_URI;
2848 } else if (isSystemSettingsKey(key)) {
2849 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2850 : Settings.System.CONTENT_URI;
2851 } else {
2852 throw new IllegalArgumentException("Invalid settings key:" + key);
2853 }
2854 }
2855
2856 private int getMaxBytesPerPackageForType(int type) {
2857 switch (type) {
2858 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002859 case SETTINGS_TYPE_SECURE:
2860 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002861 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2862 }
2863
2864 default: {
2865 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2866 }
2867 }
2868 }
2869
Svetoslav7e0683b2015-08-03 16:02:52 -07002870 private final class MyHandler extends Handler {
2871 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2872 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2873
2874 public MyHandler(Looper looper) {
2875 super(looper);
2876 }
2877
2878 @Override
2879 public void handleMessage(Message msg) {
2880 switch (msg.what) {
2881 case MSG_NOTIFY_URI_CHANGED: {
2882 final int userId = msg.arg1;
2883 Uri uri = (Uri) msg.obj;
2884 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2885 if (DEBUG) {
2886 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2887 }
2888 } break;
2889
2890 case MSG_NOTIFY_DATA_CHANGED: {
2891 mBackupManager.dataChanged();
2892 } break;
2893 }
2894 }
2895 }
2896
Svetoslav683914b2015-01-15 14:22:26 -08002897 private final class UpgradeController {
Amin Shaikh86367962017-06-07 08:58:22 -07002898 private static final int SETTINGS_VERSION = 146;
Svetoslav683914b2015-01-15 14:22:26 -08002899
2900 private final int mUserId;
2901
2902 public UpgradeController(int userId) {
2903 mUserId = userId;
2904 }
2905
2906 public void upgradeIfNeededLocked() {
2907 // The version of all settings for a user is the same (all users have secure).
2908 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002909 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002910
2911 // Try an update from the current state.
2912 final int oldVersion = secureSettings.getVersionLocked();
2913 final int newVersion = SETTINGS_VERSION;
2914
Svet Ganovc9755bc2015-03-28 13:21:22 -07002915 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002916 if (oldVersion == newVersion) {
2917 return;
2918 }
2919
2920 // Try to upgrade.
2921 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2922
2923 // If upgrade failed start from scratch and upgrade.
2924 if (curVersion != newVersion) {
2925 // Drop state we have for this user.
2926 removeUserStateLocked(mUserId, true);
2927
2928 // Recreate the database.
2929 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2930 SQLiteDatabase database = dbHelper.getWritableDatabase();
2931 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2932
2933 // Migrate the settings for this user.
2934 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2935
2936 // Now upgrade should work fine.
2937 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002938
2939 // Make a note what happened, so we don't wonder why data was lost
2940 String reason = "Settings rebuilt! Current version: "
2941 + curVersion + " while expected: " + newVersion;
2942 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002943 Settings.Global.DATABASE_DOWNGRADE_REASON,
2944 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002945 }
2946
2947 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002948 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002949 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002950 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002951 globalSettings.setVersionLocked(newVersion);
2952 }
2953
2954 // Set the secure settings version.
2955 secureSettings.setVersionLocked(newVersion);
2956
2957 // Set the system settings version.
2958 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002959 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002960 systemSettings.setVersionLocked(newVersion);
2961 }
2962
2963 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002964 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002965 }
2966
2967 private SettingsState getSecureSettingsLocked(int userId) {
2968 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2969 }
2970
Mark Rathjend891f012017-01-19 04:10:37 +00002971 private SettingsState getSsaidSettingsLocked(int userId) {
2972 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2973 }
2974
Svetoslav683914b2015-01-15 14:22:26 -08002975 private SettingsState getSystemSettingsLocked(int userId) {
2976 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2977 }
2978
Jeff Brown503cffc2015-03-26 18:08:51 -07002979 /**
2980 * You must perform all necessary mutations to bring the settings
2981 * for this user from the old to the new version. When you add a new
2982 * upgrade step you *must* update SETTINGS_VERSION.
2983 *
2984 * This is an example of moving a setting from secure to global.
2985 *
2986 * // v119: Example settings changes.
2987 * if (currentVersion == 118) {
2988 * if (userId == UserHandle.USER_OWNER) {
2989 * // Remove from the secure settings.
2990 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2991 * String name = "example_setting_to_move";
2992 * String value = secureSettings.getSetting(name);
2993 * secureSettings.deleteSetting(name);
2994 *
2995 * // Add to the global settings.
2996 * SettingsState globalSettings = getGlobalSettingsLocked();
2997 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2998 * }
2999 *
3000 * // Update the current version.
3001 * currentVersion = 119;
3002 * }
3003 */
Svetoslav683914b2015-01-15 14:22:26 -08003004 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3005 if (DEBUG) {
3006 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3007 + oldVersion + " to version: " + newVersion);
3008 }
3009
Jeff Brown503cffc2015-03-26 18:08:51 -07003010 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003011
John Spurlocke11ae112015-05-11 16:09:03 -04003012 // v119: Reset zen + ringer mode.
3013 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003014 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003015 final SettingsState globalSettings = getGlobalSettingsLocked();
3016 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003017 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3018 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003019 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003020 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3021 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003022 }
3023 currentVersion = 119;
3024 }
3025
Jason Monk27bbb2d2015-03-31 16:46:39 -04003026 // v120: Add double tap to wake setting.
3027 if (currentVersion == 119) {
3028 SettingsState secureSettings = getSecureSettingsLocked(userId);
3029 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3030 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003031 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003032 SettingsState.SYSTEM_PACKAGE_NAME);
3033
3034 currentVersion = 120;
3035 }
3036
Svetoslav7e0683b2015-08-03 16:02:52 -07003037 if (currentVersion == 120) {
3038 // Before 121, we used a different string encoding logic. We just bump the
3039 // version here; SettingsState knows how to handle pre-version 120 files.
3040 currentVersion = 121;
3041 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003042
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003043 if (currentVersion == 121) {
3044 // Version 122: allow OEMs to set a default payment component in resources.
3045 // Note that we only write the default if no default has been set;
3046 // if there is, we just leave the default at whatever it currently is.
3047 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3048 String defaultComponent = (getContext().getResources().getString(
3049 R.string.def_nfc_payment_component));
3050 Setting currentSetting = secureSettings.getSettingLocked(
3051 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3052 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003053 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003054 secureSettings.insertSettingLocked(
3055 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003056 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003057 }
3058 currentVersion = 122;
3059 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003060
3061 if (currentVersion == 122) {
3062 // Version 123: Adding a default value for the ability to add a user from
3063 // the lock screen.
3064 if (userId == UserHandle.USER_SYSTEM) {
3065 final SettingsState globalSettings = getGlobalSettingsLocked();
3066 Setting currentSetting = globalSettings.getSettingLocked(
3067 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003068 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003069 globalSettings.insertSettingLocked(
3070 Settings.Global.ADD_USERS_WHEN_LOCKED,
3071 getContext().getResources().getBoolean(
3072 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003073 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003074 }
3075 }
3076 currentVersion = 123;
3077 }
Bryce Leebd179282015-12-17 19:01:37 -08003078
3079 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003080 final SettingsState globalSettings = getGlobalSettingsLocked();
3081 String defaultDisabledProfiles = (getContext().getResources().getString(
3082 R.string.def_bluetooth_disabled_profiles));
3083 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003084 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003085 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003086 }
3087
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003088 if (currentVersion == 124) {
3089 // Version 124: allow OEMs to set a default value for whether IME should be
3090 // shown when a physical keyboard is connected.
3091 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3092 Setting currentSetting = secureSettings.getSettingLocked(
3093 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003094 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003095 secureSettings.insertSettingLocked(
3096 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3097 getContext().getResources().getBoolean(
3098 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003099 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003100 }
3101 currentVersion = 125;
3102 }
3103
Ruben Brunk98576cf2016-03-07 18:54:28 -08003104 if (currentVersion == 125) {
3105 // Version 125: Allow OEMs to set the default VR service.
3106 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3107
3108 Setting currentSetting = secureSettings.getSettingLocked(
3109 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003110 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003111 ArraySet<ComponentName> l =
3112 SystemConfig.getInstance().getDefaultVrComponents();
3113
3114 if (l != null && !l.isEmpty()) {
3115 StringBuilder b = new StringBuilder();
3116 boolean start = true;
3117 for (ComponentName c : l) {
3118 if (!start) {
3119 b.append(':');
3120 }
3121 b.append(c.flattenToString());
3122 start = false;
3123 }
3124 secureSettings.insertSettingLocked(
3125 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003126 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003127 }
3128
3129 }
3130 currentVersion = 126;
3131 }
3132
Daniel U02ba6122016-04-01 18:41:42 +01003133 if (currentVersion == 126) {
3134 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3135 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3136 if (mUserManager.isManagedProfile(userId)) {
3137 final SettingsState systemSecureSettings =
3138 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3139
3140 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3141 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003142 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003143 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3144 secureSettings.insertSettingLocked(
3145 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003146 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003147 SettingsState.SYSTEM_PACKAGE_NAME);
3148 }
3149
3150 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3151 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003152 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003153 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3154 secureSettings.insertSettingLocked(
3155 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003156 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003157 SettingsState.SYSTEM_PACKAGE_NAME);
3158 }
3159 }
3160 currentVersion = 127;
3161 }
3162
Steven Ngdc20ba62016-04-26 18:19:04 +01003163 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003164 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003165 currentVersion = 128;
3166 }
3167
Julia Reynolds1f721e12016-07-11 08:50:58 -04003168 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003169 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003170 currentVersion = 129;
3171 }
3172
Dan Sandler71f85e92016-07-20 13:46:05 -04003173 if (currentVersion == 129) {
3174 // default longpress timeout changed from 500 to 400. If unchanged from the old
3175 // default, update to the new default.
3176 final SettingsState systemSecureSettings =
3177 getSecureSettingsLocked(userId);
3178 final String oldValue = systemSecureSettings.getSettingLocked(
3179 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3180 if (TextUtils.equals("500", oldValue)) {
3181 systemSecureSettings.insertSettingLocked(
3182 Settings.Secure.LONG_PRESS_TIMEOUT,
3183 String.valueOf(getContext().getResources().getInteger(
3184 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003185 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003186 }
3187 currentVersion = 130;
3188 }
3189
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003190 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003191 // Split Ambient settings
3192 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3193 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3194 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3195
3196 if (dozeExplicitlyDisabled) {
3197 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003198 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003199 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003200 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003201 }
3202 currentVersion = 131;
3203 }
3204
3205 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003206 // Initialize new multi-press timeout to default value
3207 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3208 final String oldValue = systemSecureSettings.getSettingLocked(
3209 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3210 if (TextUtils.equals(null, oldValue)) {
3211 systemSecureSettings.insertSettingLocked(
3212 Settings.Secure.MULTI_PRESS_TIMEOUT,
3213 String.valueOf(getContext().getResources().getInteger(
3214 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003215 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003216 }
3217
Adrian Roos69741a22016-10-21 14:49:17 -07003218 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003219 }
3220
Adrian Roos69741a22016-10-21 14:49:17 -07003221 if (currentVersion == 132) {
3222 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003223 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3224 String defaultSyncParentSounds = (getContext().getResources()
3225 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3226 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003227 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3228 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003229 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003230 }
3231
Adrian Roos69741a22016-10-21 14:49:17 -07003232 if (currentVersion == 133) {
3233 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003234 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3235 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3236 null) {
3237 String defaultEndButtonBehavior = Integer.toString(getContext()
3238 .getResources().getInteger(R.integer.def_end_button_behavior));
3239 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003240 defaultEndButtonBehavior, null, true,
3241 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003242 }
Adrian Roos69741a22016-10-21 14:49:17 -07003243 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003244 }
3245
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003246 if (currentVersion == 134) {
3247 // Remove setting that specifies if magnification values should be preserved.
3248 // This setting defaulted to true and never has a UI.
3249 getSecureSettingsLocked(userId).deleteSettingLocked(
3250 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3251 currentVersion = 135;
3252 }
3253
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003254 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003255 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003256 currentVersion = 136;
3257 }
3258
Mark Rathjend891f012017-01-19 04:10:37 +00003259 if (currentVersion == 136) {
3260 // Version 136: Store legacy SSAID for all apps currently installed on the
3261 // device as first step in migrating SSAID to be unique per application.
3262
3263 final boolean isUpgrade;
3264 try {
3265 isUpgrade = mPackageManager.isUpgrade();
3266 } catch (RemoteException e) {
3267 throw new IllegalStateException("Package manager not available");
3268 }
3269 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3270 // user data or first boot on a new device should use new ssaid generation.
3271 if (isUpgrade) {
3272 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003273 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3274 userId, Settings.Secure.ANDROID_ID);
3275 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3276 || legacySsaidSetting.getValue() == null) {
3277 throw new IllegalStateException("Legacy ssaid not accessible");
3278 }
3279 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003280
3281 // Fill each uid with the legacy ssaid to be backwards compatible.
3282 final List<PackageInfo> packages;
3283 try {
3284 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3285 } catch (RemoteException e) {
3286 throw new IllegalStateException("Package manager not available");
3287 }
3288
3289 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3290 for (PackageInfo info : packages) {
3291 // Check if the UID already has an entry in the table.
3292 final String uid = Integer.toString(info.applicationInfo.uid);
3293 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3294
3295 if (ssaid.isNull() || ssaid.getValue() == null) {
3296 // Android Id doesn't exist for this package so create it.
3297 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3298 info.packageName);
3299 }
3300 }
3301 }
3302
3303 currentVersion = 137;
3304 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003305 if (currentVersion == 137) {
3306 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3307 // default value set to 1. The user can no longer change the value of this
3308 // setting through the UI.
3309 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3310 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003311 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3312 && secureSetting.getSettingLocked(
3313 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3314
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003315 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3316 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003317 // For managed profiles with profile owners, DevicePolicyManagerService
3318 // may want to set the user restriction in this case
3319 secureSetting.insertSettingLocked(
3320 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3321 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003322 }
3323 currentVersion = 138;
3324 }
Mark Rathjend891f012017-01-19 04:10:37 +00003325
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003326 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003327 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003328 currentVersion = 139;
3329 }
3330
Phil Weaver385912e2017-02-10 10:06:56 -08003331 if (currentVersion == 139) {
3332 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3333 // the user can no longer change the value of this setting through the UI.
3334 // Force to true.
3335 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3336 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3337 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3338 currentVersion = 140;
3339 }
3340
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003341 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003342 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003343 currentVersion = 141;
3344 }
3345
Svet Ganov13701552017-02-23 12:45:17 -08003346 if (currentVersion == 141) {
Felipe Lemeff355092017-04-03 12:55:02 -07003347 // Version 142: We added the notion of a default and whether the system set
Svet Ganov13701552017-02-23 12:45:17 -08003348 // the setting. This is used for resetting the internal state and we need
3349 // to make sure this value is updated for the existing settings, otherwise
3350 // we would delete system set settings while they should stay unmodified.
3351 SettingsState globalSettings = getGlobalSettingsLocked();
3352 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3353 globalSettings.persistSyncLocked();
3354
3355 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3356 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3357 secureSettings.persistSyncLocked();
3358
3359 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3360 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3361 systemSettings.persistSyncLocked();
3362
3363 currentVersion = 142;
3364 }
3365
Stephen Chen5d0922f2017-03-27 10:28:04 -07003366 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003367 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003368 if (userId == UserHandle.USER_SYSTEM) {
3369 final SettingsState globalSettings = getGlobalSettingsLocked();
3370 Setting currentSetting = globalSettings.getSettingLocked(
3371 Settings.Global.WIFI_WAKEUP_ENABLED);
3372 if (currentSetting.isNull()) {
3373 globalSettings.insertSettingLocked(
3374 Settings.Global.WIFI_WAKEUP_ENABLED,
3375 getContext().getResources().getBoolean(
3376 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3377 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3378 }
3379 }
3380
3381 currentVersion = 143;
3382 }
3383
Felipe Lemeff355092017-04-03 12:55:02 -07003384 if (currentVersion == 143) {
3385 // Version 144: Set a default value for Autofill service.
3386 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3387 final Setting currentSetting = secureSettings
3388 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3389 if (currentSetting.isNull()) {
3390 final String defaultValue = getContext().getResources().getString(
3391 com.android.internal.R.string.config_defaultAutofillService);
3392 if (defaultValue != null) {
3393 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3394 + "for user " + userId);
3395 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3396 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3397 }
3398 }
3399
3400 currentVersion = 144;
3401 }
3402
Jeremy Joslin45caa252017-05-04 11:22:46 -07003403 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003404 // Version 145: Removed
3405 currentVersion = 145;
3406 }
3407
3408 if (currentVersion == 145) {
3409 // Version 146: Set the default value for WIFI_WAKEUP_AVAILABLE.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003410 if (userId == UserHandle.USER_SYSTEM) {
3411 final SettingsState globalSettings = getGlobalSettingsLocked();
3412 final Setting currentSetting = globalSettings.getSettingLocked(
3413 Settings.Global.WIFI_WAKEUP_AVAILABLE);
Amin Shaikh86367962017-06-07 08:58:22 -07003414 final int defaultValue = getContext().getResources().getInteger(
3415 com.android.internal.R.integer.config_wifi_wakeup_available);
3416 globalSettings.insertSettingLocked(
3417 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3418 String.valueOf(defaultValue),
3419 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Jeremy Joslin45caa252017-05-04 11:22:46 -07003420 }
3421
Amin Shaikh86367962017-06-07 08:58:22 -07003422 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003423 }
3424
Felipe Lemeff355092017-04-03 12:55:02 -07003425 // vXXX: Add new settings above this point.
3426
Dan Sandler71f85e92016-07-20 13:46:05 -04003427 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003428 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003429 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003430 + currentVersion +
3431 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3432 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003433 if (DEBUG) {
3434 throw new RuntimeException("db upgrade error");
3435 }
3436 }
3437
Jeff Brown503cffc2015-03-26 18:08:51 -07003438 // Return the current version.
3439 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003440 }
3441 }
Svet Ganov13701552017-02-23 12:45:17 -08003442
3443 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3444 List<String> names = settings.getSettingNamesLocked();
3445 final int nameCount = names.size();
3446 for (int i = 0; i < nameCount; i++) {
3447 String name = names.get(i);
3448 Setting setting = settings.getSettingLocked(name);
3449 if (setting.getDefaultValue() == null) {
3450 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3451 setting.getPackageName());
3452 if (systemSet) {
3453 settings.insertSettingLocked(name, setting.getValue(),
3454 setting.getTag(), true, setting.getPackageName());
3455 }
3456 }
3457 }
3458 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003459 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003460}