blob: 4b304b2353b3e19e1cd517b0f9e8599d6844ca9d [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 }
1145 if (instantSsaid != null) {
1146 // Use the stored value if it is still valid.
1147 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
1148 return ssaid;
1149 }
1150 // The value has changed, update the stored value.
1151 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1152 SETTINGS_TYPE_SSAID, owningUserId);
1153 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1154 true, callingPkg.packageName);
1155 if (!success) {
1156 throw new IllegalStateException("Failed to update instant app android id");
1157 }
1158 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId, name);
1159 }
Mark Rathjend891f012017-01-19 04:10:37 +00001160
1161 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001162 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Christopher Tateb218e762017-04-05 16:34:07 -07001163 return mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001164 }
1165
1166 return ssaid;
1167 }
1168
Svetoslav Ganove080da92016-12-21 17:10:35 -08001169 private boolean insertSecureSetting(String name, String value, String tag,
1170 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001171 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001172 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001173 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1174 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001175 }
1176
Svetoslav Ganove080da92016-12-21 17:10:35 -08001177 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1178 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001179 }
1180
Svet Ganov53a441c2016-04-19 19:38:00 -07001181 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001182 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001183 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1184 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001185 }
1186
Svetoslav Ganove080da92016-12-21 17:10:35 -08001187 return mutateSecureSetting(name, null, null, false, requestingUserId,
1188 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001189 }
1190
Svetoslav Ganove080da92016-12-21 17:10:35 -08001191 private boolean updateSecureSetting(String name, String value, String tag,
1192 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001193 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001194 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001195 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1196 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001197 }
1198
Svetoslav Ganove080da92016-12-21 17:10:35 -08001199 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1200 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001201 }
1202
Svetoslav Ganove080da92016-12-21 17:10:35 -08001203 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1204 if (DEBUG) {
1205 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1206 + mode + ", " + tag + ")");
1207 }
1208
1209 mutateSecureSetting(null, null, tag, false, requestingUserId,
1210 MUTATION_OPERATION_RESET, false, mode);
1211 }
1212
1213 private boolean mutateSecureSetting(String name, String value, String tag,
1214 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1215 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001216 // Make sure the caller can change the settings.
1217 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1218
Svetoslav683914b2015-01-15 14:22:26 -08001219 // Resolve the userId on whose behalf the call is made.
1220 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1221
Makoto Onuki28da2e32015-11-20 11:30:44 -08001222 // If this is a setting that is currently restricted for this user, do not allow
1223 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001224 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001225 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001226 return false;
1227 }
1228
1229 // Determine the owning user as some profile settings are cloned from the parent.
1230 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1231
1232 // Only the owning user can change the setting.
1233 if (owningUserId != callingUserId) {
1234 return false;
1235 }
1236
1237 // Special cases for location providers (sigh).
1238 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001239 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1240 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001241 }
1242
1243 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001244 synchronized (mLock) {
1245 switch (operation) {
1246 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001247 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001248 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001249 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001250 }
Svetoslav683914b2015-01-15 14:22:26 -08001251
Svetoslav7ec28e82015-05-20 17:01:10 -07001252 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001253 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001254 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 }
Svetoslav683914b2015-01-15 14:22:26 -08001256
Svetoslav7ec28e82015-05-20 17:01:10 -07001257 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001258 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001259 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001260 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001261 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001262
1263 case MUTATION_OPERATION_RESET: {
1264 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1265 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1266 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001267 }
1268 }
1269
1270 return false;
1271 }
1272
Svetoslav7ec28e82015-05-20 17:01:10 -07001273 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001274 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001276 }
1277
1278 // Resolve the userId on whose behalf the call is made.
1279 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1280
Svetoslav7ec28e82015-05-20 17:01:10 -07001281 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001282 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001283
Svetoslav7ec28e82015-05-20 17:01:10 -07001284 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001285
Svetoslav7ec28e82015-05-20 17:01:10 -07001286 String[] normalizedProjection = normalizeProjection(projection);
1287 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001288
Svetoslav7ec28e82015-05-20 17:01:10 -07001289 for (int i = 0; i < nameCount; i++) {
1290 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001291
Svetoslav7ec28e82015-05-20 17:01:10 -07001292 // Determine the owning user as some profile settings are cloned from the parent.
1293 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1294 name);
Svetoslav683914b2015-01-15 14:22:26 -08001295
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001297 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001298 appendSettingToCursor(result, setting);
1299 }
1300
1301 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001302 }
Svetoslav683914b2015-01-15 14:22:26 -08001303 }
1304
Svetoslav7ec28e82015-05-20 17:01:10 -07001305 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001306 if (DEBUG) {
1307 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1308 }
1309
1310 // Resolve the userId on whose behalf the call is made.
1311 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1312
Chad Brubakera6830e72017-04-28 17:34:36 -07001313 // Ensure the caller can access the setting.
1314 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001315
Svetoslav683914b2015-01-15 14:22:26 -08001316 // Determine the owning user as some profile settings are cloned from the parent.
1317 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1318
1319 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001320 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001321 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001322 }
Svetoslav683914b2015-01-15 14:22:26 -08001323 }
1324
Svetoslav7ec28e82015-05-20 17:01:10 -07001325 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001326 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001327 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001328 + requestingUserId + ")");
1329 }
1330
Svetoslav7ec28e82015-05-20 17:01:10 -07001331 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001332 }
1333
Svetoslav7ec28e82015-05-20 17:01:10 -07001334 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001335 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001336 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001337 }
1338
Svetoslav7ec28e82015-05-20 17:01:10 -07001339 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001340 }
1341
Svetoslav7ec28e82015-05-20 17:01:10 -07001342 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001343 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001344 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001345 + requestingUserId + ")");
1346 }
1347
Svetoslav7ec28e82015-05-20 17:01:10 -07001348 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001349 }
1350
Svetoslav7ec28e82015-05-20 17:01:10 -07001351 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001352 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001353 if (!hasWriteSecureSettingsPermission()) {
1354 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1355 // operation is allowed for the calling package through appops.
1356 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1357 Binder.getCallingUid(), getCallingPackage(), true)) {
1358 return false;
1359 }
Svetoslav683914b2015-01-15 14:22:26 -08001360 }
1361
Svetoslav683914b2015-01-15 14:22:26 -08001362 // Resolve the userId on whose behalf the call is made.
1363 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1364
Svetoslavd8d25e02015-11-20 13:09:26 -08001365 // Enforce what the calling package can mutate the system settings.
1366 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1367
Svetoslav683914b2015-01-15 14:22:26 -08001368 // Determine the owning user as some profile settings are cloned from the parent.
1369 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1370
1371 // Only the owning user id can change the setting.
1372 if (owningUserId != callingUserId) {
1373 return false;
1374 }
1375
Jeff Sharkey413573a2016-02-22 17:52:45 -07001376 // Invalidate any relevant cache files
1377 String cacheName = null;
1378 if (Settings.System.RINGTONE.equals(name)) {
1379 cacheName = Settings.System.RINGTONE_CACHE;
1380 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1381 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1382 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1383 cacheName = Settings.System.ALARM_ALERT_CACHE;
1384 }
1385 if (cacheName != null) {
1386 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001387 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001388 cacheFile.delete();
1389 }
1390
Svetoslav683914b2015-01-15 14:22:26 -08001391 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001392 synchronized (mLock) {
1393 switch (operation) {
1394 case MUTATION_OPERATION_INSERT: {
1395 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001396 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001397 owningUserId, name, value, null, false, getCallingPackage(),
1398 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001399 }
1400
1401 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001402 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001403 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001404 }
1405
1406 case MUTATION_OPERATION_UPDATE: {
1407 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001408 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001409 owningUserId, name, value, null, false, getCallingPackage(),
1410 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001411 }
Svetoslav683914b2015-01-15 14:22:26 -08001412 }
1413
Svetoslav7ec28e82015-05-20 17:01:10 -07001414 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001415 }
Svetoslav683914b2015-01-15 14:22:26 -08001416 }
1417
Billy Lau6ad2d662015-07-18 00:26:58 +01001418 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001419 // Write secure settings is a more protected permission. If caller has it we are good.
1420 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1421 == PackageManager.PERMISSION_GRANTED) {
1422 return true;
1423 }
1424
Svetoslavf41334b2015-06-23 12:06:03 -07001425 return false;
1426 }
1427
Svetoslav683914b2015-01-15 14:22:26 -08001428 private void validateSystemSettingValue(String name, String value) {
1429 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1430 if (validator != null && !validator.validate(value)) {
1431 throw new IllegalArgumentException("Invalid value: " + value
1432 + " for setting: " + name);
1433 }
1434 }
1435
Alex Klyubin1991f572017-03-03 14:08:36 -08001436 /**
1437 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1438 */
1439 private boolean isSecureSettingAccessible(String name, int callingUserId,
1440 int owningUserId) {
1441 // Special case for location (sigh).
1442 // This check is not inside the name-based checks below because this method performs checks
1443 // only if the calling user ID is not the same as the owning user ID.
1444 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1445 return false;
1446 }
1447
1448 switch (name) {
1449 case "bluetooth_address":
1450 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1451 // address in this secure setting. Secure settings can normally be read by any app,
1452 // which thus enables them to bypass the recently introduced restrictions on access
1453 // to device identifiers.
1454 // To mitigate this we make this setting available only to callers privileged to see
1455 // this device's MAC addresses, same as through public API
1456 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1457 return getContext().checkCallingOrSelfPermission(
1458 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1459 default:
1460 return true;
1461 }
1462 }
1463
Svetoslav683914b2015-01-15 14:22:26 -08001464 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1465 int owningUserId) {
1466 // Optimization - location providers are restricted only for managed profiles.
1467 if (callingUserId == owningUserId) {
1468 return false;
1469 }
1470 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1471 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1472 new UserHandle(callingUserId))) {
1473 return true;
1474 }
1475 return false;
1476 }
1477
Makoto Onuki28da2e32015-11-20 11:30:44 -08001478 /**
1479 * Checks whether changing a setting to a value is prohibited by the corresponding user
1480 * restriction.
1481 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001482 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1483 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001484 *
1485 * @return true if the change is prohibited, false if the change is allowed.
1486 */
1487 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001488 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001489 String restriction;
1490 switch (setting) {
1491 case Settings.Secure.LOCATION_MODE:
1492 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1493 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1494 // here normally, but we still protect it here from a direct provider write.
1495 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1496 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1497 break;
1498
1499 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1500 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1501 // a provider, which should be allowed even if the user restriction is set.
1502 if (value != null && value.startsWith("-")) return false;
1503 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1504 break;
1505
1506 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1507 if ("0".equals(value)) return false;
1508 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1509 break;
1510
1511 case Settings.Global.ADB_ENABLED:
1512 if ("0".equals(value)) return false;
1513 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1514 break;
1515
1516 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1517 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1518 if ("1".equals(value)) return false;
1519 restriction = UserManager.ENSURE_VERIFY_APPS;
1520 break;
1521
1522 case Settings.Global.PREFERRED_NETWORK_MODE:
1523 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1524 break;
1525
Victor Chang9c7b7062016-07-12 23:47:29 +01001526 case Settings.Secure.ALWAYS_ON_VPN_APP:
1527 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1528 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001529 final int appId = UserHandle.getAppId(callingUid);
1530 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001531 return false;
1532 }
1533 restriction = UserManager.DISALLOW_CONFIG_VPN;
1534 break;
1535
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001536 case Settings.Global.SAFE_BOOT_DISALLOWED:
1537 if ("1".equals(value)) return false;
1538 restriction = UserManager.DISALLOW_SAFE_BOOT;
1539 break;
1540
Makoto Onuki28da2e32015-11-20 11:30:44 -08001541 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001542 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001543 if ("0".equals(value)) return false;
1544 restriction = UserManager.DISALLOW_DATA_ROAMING;
1545 break;
1546 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001547 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001548 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001549
1550 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001551 }
1552
1553 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1554 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1555 }
1556
1557 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001558 final int parentId;
1559 // Resolves dependency if setting has a dependency and the calling user has a parent
1560 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1561 && (parentId = getGroupParentLocked(userId)) != userId) {
1562 // The setting has a dependency and the profile has a parent
1563 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001564 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1565 final long token = Binder.clearCallingIdentity();
1566 try {
1567 Setting settingObj = getSecureSetting(dependency, userId);
1568 if (settingObj != null && settingObj.getValue().equals("1")) {
1569 return parentId;
1570 }
1571 } finally {
1572 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001573 }
1574 }
Svetoslav683914b2015-01-15 14:22:26 -08001575 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1576 }
1577
1578 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1579 final int parentId = getGroupParentLocked(userId);
1580 if (parentId != userId && keys.contains(name)) {
1581 return parentId;
1582 }
1583 return userId;
1584 }
1585
Svetoslavf41334b2015-06-23 12:06:03 -07001586 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001587 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001588 // System/root/shell can mutate whatever secure settings they want.
1589 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001590 final int appId = UserHandle.getAppId(callingUid);
1591 if (appId == android.os.Process.SYSTEM_UID
1592 || appId == Process.SHELL_UID
1593 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001594 return;
1595 }
1596
1597 switch (operation) {
1598 case MUTATION_OPERATION_INSERT:
1599 // Insert updates.
1600 case MUTATION_OPERATION_UPDATE: {
1601 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1602 return;
1603 }
1604
1605 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001606 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001607
1608 // Privileged apps can do whatever they want.
1609 if ((packageInfo.applicationInfo.privateFlags
1610 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1611 return;
1612 }
1613
1614 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1615 packageInfo.applicationInfo.targetSdkVersion, name);
1616 } break;
1617
1618 case MUTATION_OPERATION_DELETE: {
1619 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1620 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1621 throw new IllegalArgumentException("You cannot delete system defined"
1622 + " secure settings.");
1623 }
1624
1625 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001626 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001627
1628 // Privileged apps can do whatever they want.
1629 if ((packageInfo.applicationInfo.privateFlags &
1630 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1631 return;
1632 }
1633
1634 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1635 packageInfo.applicationInfo.targetSdkVersion, name);
1636 } break;
1637 }
1638 }
1639
Todd Kennedybe0b8892017-02-15 14:13:52 -08001640 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001641 switch (settingsType) {
1642 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001643 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001644 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001645 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001646 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001647 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001648 default:
1649 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1650 }
1651 }
1652
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001653 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1654 switch (settingsType) {
1655 case SETTINGS_TYPE_GLOBAL:
1656 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1657 case SETTINGS_TYPE_SYSTEM:
1658 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1659 case SETTINGS_TYPE_SECURE:
1660 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1661 default:
1662 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1663 }
1664 }
1665
Chad Brubaker97bccee2017-01-05 15:51:41 -08001666 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001667 boolean instantApp;
1668 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1669 instantApp = false;
1670 } else {
1671 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1672 instantApp = ai.isInstantApp();
1673 }
1674 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001675 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001676 } else {
1677 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1678 }
1679 }
1680
Chad Brubakera6830e72017-04-28 17:34:36 -07001681 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001682 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1683 return;
1684 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001685 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001686 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001687 return;
1688 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001689 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1690 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001691 throw new SecurityException("Setting " + settingName + " is not accessible from"
1692 + " ephemeral package " + getCallingPackage());
1693 }
1694 }
1695
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001696 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1697 // We always use the callingUid for this lookup. This means that if hypothetically an
1698 // app was installed in user A with cross user and in user B as an Instant App
1699 // the app in A would be able to see all the settings in user B. However since cross
1700 // user is a system permission and the app must be uninstalled in B and then installed as
1701 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001702 ApplicationInfo ai = null;
1703 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001704 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1705 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001706 } catch (RemoteException ignored) {
1707 }
1708 if (ai == null) {
1709 throw new IllegalStateException("Failed to lookup info for package "
1710 + getCallingPackage());
1711 }
1712 return ai;
1713 }
1714
Xiaohui Chen43765b72015-08-31 10:57:33 -07001715 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001716 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001717 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1718 getCallingPackage(), 0, userId);
1719 if (packageInfo != null) {
1720 return packageInfo;
1721 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001722 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001723 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001724 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001725 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001726 }
1727
1728 private int getGroupParentLocked(int userId) {
1729 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001730 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001731 return userId;
1732 }
1733 // We are in the same process with the user manager and the returned
1734 // user info is a cached instance, so just look up instead of cache.
1735 final long identity = Binder.clearCallingIdentity();
1736 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001737 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001738 UserInfo userInfo = mUserManager.getProfileParent(userId);
1739 return (userInfo != null) ? userInfo.id : userId;
1740 } finally {
1741 Binder.restoreCallingIdentity(identity);
1742 }
1743 }
1744
Svetoslav683914b2015-01-15 14:22:26 -08001745 private void enforceWritePermission(String permission) {
1746 if (getContext().checkCallingOrSelfPermission(permission)
1747 != PackageManager.PERMISSION_GRANTED) {
1748 throw new SecurityException("Permission denial: writing to settings requires:"
1749 + permission);
1750 }
1751 }
1752
1753 /*
1754 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1755 * This setting contains a list of the currently enabled location providers.
1756 * But helper functions in android.providers.Settings can enable or disable
1757 * a single provider by using a "+" or "-" prefix before the provider name.
1758 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001759 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1760 * is set, the said method will only allow values with the "-" prefix.
1761 *
Svetoslav683914b2015-01-15 14:22:26 -08001762 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001763 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001764 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1765 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001766 if (TextUtils.isEmpty(value)) {
1767 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001768 }
1769
Svetoslav683914b2015-01-15 14:22:26 -08001770 final char prefix = value.charAt(0);
1771 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001772 if (forceNotify) {
1773 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1774 mSettingsRegistry.notifyForSettingsChange(key,
1775 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1776 }
Svetoslav683914b2015-01-15 14:22:26 -08001777 return false;
1778 }
1779
1780 // skip prefix
1781 value = value.substring(1);
1782
Svetoslav7ec28e82015-05-20 17:01:10 -07001783 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001784 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001785 if (settingValue == null) {
1786 return false;
1787 }
Svetoslav683914b2015-01-15 14:22:26 -08001788
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001789 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001790
1791 int index = oldProviders.indexOf(value);
1792 int end = index + value.length();
1793
1794 // check for commas to avoid matching on partial string
1795 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1796 index = -1;
1797 }
1798
1799 // check for commas to avoid matching on partial string
1800 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1801 index = -1;
1802 }
1803
1804 String newProviders;
1805
1806 if (prefix == '+' && index < 0) {
1807 // append the provider to the list if not present
1808 if (oldProviders.length() == 0) {
1809 newProviders = value;
1810 } else {
1811 newProviders = oldProviders + ',' + value;
1812 }
1813 } else if (prefix == '-' && index >= 0) {
1814 // remove the provider from the list if present
1815 // remove leading or trailing comma
1816 if (index > 0) {
1817 index--;
1818 } else if (end < oldProviders.length()) {
1819 end++;
1820 }
1821
1822 newProviders = oldProviders.substring(0, index);
1823 if (end < oldProviders.length()) {
1824 newProviders += oldProviders.substring(end);
1825 }
1826 } else {
1827 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001828 if (forceNotify) {
1829 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1830 mSettingsRegistry.notifyForSettingsChange(key,
1831 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1832 }
Svetoslav683914b2015-01-15 14:22:26 -08001833 return false;
1834 }
1835
Svet Ganov53a441c2016-04-19 19:38:00 -07001836 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001837 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001838 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001839 }
1840
Svetoslav683914b2015-01-15 14:22:26 -08001841 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1842 int targetSdkVersion, String name) {
1843 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1844 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1845 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1846 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1847 + " This will soon become an error.");
1848 } else {
1849 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1850 + " This will soon become an error.");
1851 }
1852 } else {
1853 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1854 throw new IllegalArgumentException("You cannot change private secure settings.");
1855 } else {
1856 throw new IllegalArgumentException("You cannot keep your settings in"
1857 + " the secure settings.");
1858 }
1859 }
1860 }
1861
1862 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1863 if (requestingUserId == UserHandle.getCallingUserId()) {
1864 return requestingUserId;
1865 }
1866 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1867 Binder.getCallingUid(), requestingUserId, false, true,
1868 "get/set setting for user", null);
1869 }
1870
Svet Ganov53a441c2016-04-19 19:38:00 -07001871 private Bundle packageValueForCallResult(Setting setting,
1872 boolean trackingGeneration) {
1873 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001874 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001875 return NULL_SETTING_BUNDLE;
1876 }
1877 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001878 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001879 Bundle result = new Bundle();
1880 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001881 !setting.isNull() ? setting.getValue() : null);
1882 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001883 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001884 }
1885
1886 private static int getRequestingUserId(Bundle args) {
1887 final int callingUserId = UserHandle.getCallingUserId();
1888 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1889 : callingUserId;
1890 }
1891
Svet Ganov53a441c2016-04-19 19:38:00 -07001892 private boolean isTrackingGeneration(Bundle args) {
1893 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1894 }
1895
Svetoslav683914b2015-01-15 14:22:26 -08001896 private static String getSettingValue(Bundle args) {
1897 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1898 }
1899
Svetoslav Ganove080da92016-12-21 17:10:35 -08001900 private static String getSettingTag(Bundle args) {
1901 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1902 }
1903
1904 private static boolean getSettingMakeDefault(Bundle args) {
1905 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1906 }
1907
1908 private static int getResetModeEnforcingPermission(Bundle args) {
1909 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1910 switch (mode) {
1911 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1912 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1913 throw new SecurityException("Only system, shell/root on a "
1914 + "debuggable build can reset to untrusted defaults");
1915 }
1916 return mode;
1917 }
1918 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1919 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1920 throw new SecurityException("Only system, shell/root on a "
1921 + "debuggable build can reset untrusted changes");
1922 }
1923 return mode;
1924 }
1925 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1926 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1927 throw new SecurityException("Only system, shell/root on a "
1928 + "debuggable build can reset to trusted defaults");
1929 }
1930 return mode;
1931 }
1932 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1933 return mode;
1934 }
1935 }
1936 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1937 }
1938
1939 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1940 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1941 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1942 && (appId == SHELL_UID || appId == ROOT_UID));
1943 }
1944
Svetoslav683914b2015-01-15 14:22:26 -08001945 private static String getValidTableOrThrow(Uri uri) {
1946 if (uri.getPathSegments().size() > 0) {
1947 String table = uri.getPathSegments().get(0);
1948 if (DatabaseHelper.isValidTable(table)) {
1949 return table;
1950 }
1951 throw new IllegalArgumentException("Bad root path: " + table);
1952 }
1953 throw new IllegalArgumentException("Invalid URI:" + uri);
1954 }
1955
1956 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001957 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001958 return new MatrixCursor(projection, 0);
1959 }
1960 MatrixCursor cursor = new MatrixCursor(projection, 1);
1961 appendSettingToCursor(cursor, setting);
1962 return cursor;
1963 }
1964
1965 private static String[] normalizeProjection(String[] projection) {
1966 if (projection == null) {
1967 return ALL_COLUMNS;
1968 }
1969
1970 final int columnCount = projection.length;
1971 for (int i = 0; i < columnCount; i++) {
1972 String column = projection[i];
1973 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1974 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001975 }
1976 }
1977
Svetoslav683914b2015-01-15 14:22:26 -08001978 return projection;
1979 }
1980
1981 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001982 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001983 return;
1984 }
Svetoslav683914b2015-01-15 14:22:26 -08001985 final int columnCount = cursor.getColumnCount();
1986
1987 String[] values = new String[columnCount];
1988
1989 for (int i = 0; i < columnCount; i++) {
1990 String column = cursor.getColumnName(i);
1991
1992 switch (column) {
1993 case Settings.NameValueTable._ID: {
1994 values[i] = setting.getId();
1995 } break;
1996
1997 case Settings.NameValueTable.NAME: {
1998 values[i] = setting.getName();
1999 } break;
2000
2001 case Settings.NameValueTable.VALUE: {
2002 values[i] = setting.getValue();
2003 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002004 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002005 }
2006
Svetoslav683914b2015-01-15 14:22:26 -08002007 cursor.addRow(values);
2008 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002009
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002010 private static boolean isKeyValid(String key) {
2011 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2012 }
2013
Svetoslav683914b2015-01-15 14:22:26 -08002014 private static final class Arguments {
2015 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2016 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2017
2018 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2019 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2020
2021 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2022 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2023
2024 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2025 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2026
2027 public final String table;
2028 public final String name;
2029
2030 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2031 final int segmentSize = uri.getPathSegments().size();
2032 switch (segmentSize) {
2033 case 1: {
2034 if (where != null
2035 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2036 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2037 && whereArgs.length == 1) {
2038 name = whereArgs[0];
2039 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002040 return;
Svetoslav683914b2015-01-15 14:22:26 -08002041 } else if (where != null
2042 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2043 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2044 final int startIndex = Math.max(where.indexOf("'"),
2045 where.indexOf("\"")) + 1;
2046 final int endIndex = Math.max(where.lastIndexOf("'"),
2047 where.lastIndexOf("\""));
2048 name = where.substring(startIndex, endIndex);
2049 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002050 return;
Svetoslav683914b2015-01-15 14:22:26 -08002051 } else if (supportAll && where == null && whereArgs == null) {
2052 name = null;
2053 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002054 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002055 }
Svetoslav683914b2015-01-15 14:22:26 -08002056 } break;
2057
Svetoslav28494652015-02-12 14:11:42 -08002058 case 2: {
2059 if (where == null && whereArgs == null) {
2060 name = uri.getPathSegments().get(1);
2061 table = computeTableForSetting(uri, name);
2062 return;
2063 }
2064 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002065 }
Svetoslav28494652015-02-12 14:11:42 -08002066
2067 EventLogTags.writeUnsupportedSettingsQuery(
2068 uri.toSafeString(), where, Arrays.toString(whereArgs));
2069 String message = String.format( "Supported SQL:\n"
2070 + " uri content://some_table/some_property with null where and where args\n"
2071 + " uri content://some_table with query name=? and single name as arg\n"
2072 + " uri content://some_table with query name=some_name and null args\n"
2073 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2074 Arrays.toString(whereArgs));
2075 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002076 }
2077
Svetoslav28494652015-02-12 14:11:42 -08002078 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002079 String table = getValidTableOrThrow(uri);
2080
2081 if (name != null) {
2082 if (sSystemMovedToSecureSettings.contains(name)) {
2083 table = TABLE_SECURE;
2084 }
2085
2086 if (sSystemMovedToGlobalSettings.contains(name)) {
2087 table = TABLE_GLOBAL;
2088 }
2089
2090 if (sSecureMovedToGlobalSettings.contains(name)) {
2091 table = TABLE_GLOBAL;
2092 }
2093
2094 if (sGlobalMovedToSecureSettings.contains(name)) {
2095 table = TABLE_SECURE;
2096 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002097 }
Svetoslav683914b2015-01-15 14:22:26 -08002098
2099 return table;
2100 }
2101 }
2102
2103 final class SettingsRegistry {
2104 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2105
Svetoslav683914b2015-01-15 14:22:26 -08002106 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2107 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2108 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002109 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2110
2111 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002112
2113 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2114
Svet Ganov53a441c2016-04-19 19:38:00 -07002115 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002116
Svetoslav7e0683b2015-08-03 16:02:52 -07002117 private final Handler mHandler;
2118
Svet Ganov53a441c2016-04-19 19:38:00 -07002119 private final BackupManager mBackupManager;
2120
Amith Yamasani39452022017-03-21 15:23:47 -07002121 private String mSettingsCreationBuildId;
2122
Svetoslav683914b2015-01-15 14:22:26 -08002123 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002124 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002125 mGenerationRegistry = new GenerationRegistry(mLock);
2126 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002127 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002128 syncSsaidTableOnStart();
2129 }
2130
2131 private void generateUserKeyLocked(int userId) {
2132 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002133 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002134 final SecureRandom rand = new SecureRandom();
2135 rand.nextBytes(keyBytes);
2136
2137 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002138 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002139
2140 // Store the key in the ssaid table.
2141 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2142 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2143 true, SettingsState.SYSTEM_PACKAGE_NAME);
2144
2145 if (!success) {
2146 throw new IllegalStateException("Ssaid settings not accessible");
2147 }
2148 }
2149
Mark Rathjen7599f132017-01-23 14:15:54 -08002150 private byte[] getLengthPrefix(byte[] data) {
2151 return ByteBuffer.allocate(4).putInt(data.length).array();
2152 }
2153
Christopher Tateb218e762017-04-05 16:34:07 -07002154 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002155 // Read the user's key from the ssaid table.
2156 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002157 if (userKeySetting == null || userKeySetting.isNull()
2158 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002159 // Lazy initialize and store the user key.
2160 generateUserKeyLocked(userId);
2161 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002162 if (userKeySetting == null || userKeySetting.isNull()
2163 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002164 throw new IllegalStateException("User key not accessible");
2165 }
2166 }
2167 final String userKey = userKeySetting.getValue();
2168
2169 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002170 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2171
2172 // Validate that the key is of expected length.
2173 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2174 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002175 throw new IllegalStateException("User key invalid");
2176 }
2177
Mark Rathjen7599f132017-01-23 14:15:54 -08002178 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002179 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002180 m = Mac.getInstance("HmacSHA256");
2181 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002182 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002183 throw new IllegalStateException("HmacSHA256 is not available", e);
2184 } catch (InvalidKeyException e) {
2185 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002186 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002187
2188 // Mac the package name and each of the signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002189 final String packageName = callingPkg.packageName;
2190 byte[] packageNameBytes = packageName.getBytes(StandardCharsets.UTF_8);
Mark Rathjen7599f132017-01-23 14:15:54 -08002191 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2192 m.update(packageNameBytes);
Christopher Tateb218e762017-04-05 16:34:07 -07002193 for (int i = 0; i < callingPkg.signatures.length; i++) {
2194 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002195 m.update(getLengthPrefix(sig), 0, 4);
2196 m.update(sig);
2197 }
Mark Rathjend891f012017-01-19 04:10:37 +00002198
2199 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002200 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2201 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002202
2203 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002204 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002205 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2206 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2207 packageName);
2208
2209 if (!success) {
2210 throw new IllegalStateException("Ssaid settings not accessible");
2211 }
2212
2213 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2214 }
2215
2216 public void syncSsaidTableOnStart() {
2217 synchronized (mLock) {
2218 // Verify that each user's packages and ssaid's are in sync.
2219 for (UserInfo user : mUserManager.getUsers(true)) {
2220 // Get all uids for the user's packages.
2221 final List<PackageInfo> packages;
2222 try {
2223 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2224 } catch (RemoteException e) {
2225 throw new IllegalStateException("Package manager not available");
2226 }
2227 final Set<String> appUids = new HashSet<>();
2228 for (PackageInfo info : packages) {
2229 appUids.add(Integer.toString(info.applicationInfo.uid));
2230 }
2231
2232 // Get all uids currently stored in the user's ssaid table.
2233 final Set<String> ssaidUids = new HashSet<>(
2234 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2235 ssaidUids.remove(SSAID_USER_KEY);
2236
2237 // Perform a set difference for the appUids and ssaidUids.
2238 ssaidUids.removeAll(appUids);
2239
2240 // If there are ssaidUids left over they need to be removed from the table.
2241 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2242 user.id);
2243 for (String uid : ssaidUids) {
2244 ssaidSettings.deleteSettingLocked(uid);
2245 }
2246 }
2247 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002248 }
2249
Svetoslav683914b2015-01-15 14:22:26 -08002250 public List<String> getSettingsNamesLocked(int type, int userId) {
2251 final int key = makeKey(type, userId);
2252 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002253 if (settingsState == null) {
2254 return new ArrayList<String>();
2255 }
Svetoslav683914b2015-01-15 14:22:26 -08002256 return settingsState.getSettingNamesLocked();
2257 }
2258
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002259 public SparseBooleanArray getKnownUsersLocked() {
2260 SparseBooleanArray users = new SparseBooleanArray();
2261 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2262 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2263 }
2264 return users;
2265 }
2266
Svetoslav683914b2015-01-15 14:22:26 -08002267 public SettingsState getSettingsLocked(int type, int userId) {
2268 final int key = makeKey(type, userId);
2269 return peekSettingsStateLocked(key);
2270 }
2271
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002272 public boolean ensureSettingsForUserLocked(int userId) {
2273 // First make sure this user actually exists.
2274 if (mUserManager.getUserInfo(userId) == null) {
2275 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2276 return false;
2277 }
2278
Svetoslav683914b2015-01-15 14:22:26 -08002279 // Migrate the setting for this user if needed.
2280 migrateLegacySettingsForUserIfNeededLocked(userId);
2281
2282 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002283 if (userId == UserHandle.USER_SYSTEM) {
2284 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002285 ensureSettingsStateLocked(globalKey);
2286 }
2287
2288 // Ensure secure settings loaded.
2289 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2290 ensureSettingsStateLocked(secureKey);
2291
2292 // Make sure the secure settings have an Android id set.
2293 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2294 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2295
2296 // Ensure system settings loaded.
2297 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2298 ensureSettingsStateLocked(systemKey);
2299
Mark Rathjend891f012017-01-19 04:10:37 +00002300 // Ensure secure settings loaded.
2301 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2302 ensureSettingsStateLocked(ssaidKey);
2303
Svetoslav683914b2015-01-15 14:22:26 -08002304 // Upgrade the settings to the latest version.
2305 UpgradeController upgrader = new UpgradeController(userId);
2306 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002307 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002308 }
2309
2310 private void ensureSettingsStateLocked(int key) {
2311 if (mSettingsStates.get(key) == null) {
2312 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002313 SettingsState settingsState = new SettingsState(getContext(), mLock,
2314 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002315 mSettingsStates.put(key, settingsState);
2316 }
2317 }
2318
2319 public void removeUserStateLocked(int userId, boolean permanently) {
2320 // We always keep the global settings in memory.
2321
2322 // Nuke system settings.
2323 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2324 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2325 if (systemSettingsState != null) {
2326 if (permanently) {
2327 mSettingsStates.remove(systemKey);
2328 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002329 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002330 systemSettingsState.destroyLocked(new Runnable() {
2331 @Override
2332 public void run() {
2333 mSettingsStates.remove(systemKey);
2334 }
2335 });
2336 }
2337 }
2338
2339 // Nuke secure settings.
2340 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2341 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2342 if (secureSettingsState != null) {
2343 if (permanently) {
2344 mSettingsStates.remove(secureKey);
2345 secureSettingsState.destroyLocked(null);
2346 } else {
2347 secureSettingsState.destroyLocked(new Runnable() {
2348 @Override
2349 public void run() {
2350 mSettingsStates.remove(secureKey);
2351 }
2352 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002353 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002354 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002355
Mark Rathjend891f012017-01-19 04:10:37 +00002356 // Nuke ssaid settings.
2357 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2358 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2359 if (ssaidSettingsState != null) {
2360 if (permanently) {
2361 mSettingsStates.remove(ssaidKey);
2362 ssaidSettingsState.destroyLocked(null);
2363 } else {
2364 ssaidSettingsState.destroyLocked(new Runnable() {
2365 @Override
2366 public void run() {
2367 mSettingsStates.remove(ssaidKey);
2368 }
2369 });
2370 }
2371 }
2372
Svet Ganov53a441c2016-04-19 19:38:00 -07002373 // Nuke generation tracking data
2374 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002375 }
2376
Svetoslav683914b2015-01-15 14:22:26 -08002377 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002378 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2379 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002380 final int key = makeKey(type, userId);
2381
Svetoslav Ganove080da92016-12-21 17:10:35 -08002382 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002383 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002384 if (settingsState != null) {
2385 success = settingsState.insertSettingLocked(name, value,
2386 tag, makeDefault, packageName);
2387 }
Svetoslav683914b2015-01-15 14:22:26 -08002388
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002389 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2390 settingsState.persistSyncLocked();
2391 }
2392
Svet Ganov53a441c2016-04-19 19:38:00 -07002393 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002394 notifyForSettingsChange(key, name);
2395 }
2396 return success;
2397 }
2398
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002399 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2400 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002401 final int key = makeKey(type, userId);
2402
Svetoslav Ganove080da92016-12-21 17:10:35 -08002403 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002404 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002405 if (settingsState != null) {
2406 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002407 }
Svetoslav683914b2015-01-15 14:22:26 -08002408
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002409 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2410 settingsState.persistSyncLocked();
2411 }
2412
Svet Ganov53a441c2016-04-19 19:38:00 -07002413 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002414 notifyForSettingsChange(key, name);
2415 }
2416 return success;
2417 }
2418
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002419 public boolean updateSettingLocked(int type, int userId, String name, String value,
2420 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2421 Set<String> criticalSettings) {
2422 final int key = makeKey(type, userId);
2423
2424 boolean success = false;
2425 SettingsState settingsState = peekSettingsStateLocked(key);
2426 if (settingsState != null) {
2427 success = settingsState.updateSettingLocked(name, value, tag,
2428 makeDefault, packageName);
2429 }
2430
2431 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2432 settingsState.persistSyncLocked();
2433 }
2434
2435 if (forceNotify || success) {
2436 notifyForSettingsChange(key, name);
2437 }
2438
2439 return success;
2440 }
2441
Svetoslav683914b2015-01-15 14:22:26 -08002442 public Setting getSettingLocked(int type, int userId, String name) {
2443 final int key = makeKey(type, userId);
2444
2445 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002446 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002447 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002448 }
Mark Rathjend891f012017-01-19 04:10:37 +00002449
2450 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002451 return settingsState.getSettingLocked(name);
2452 }
2453
Svetoslav Ganove080da92016-12-21 17:10:35 -08002454 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2455 String tag) {
2456 final int key = makeKey(type, userId);
2457 SettingsState settingsState = peekSettingsStateLocked(key);
2458 if (settingsState == null) {
2459 return;
2460 }
2461
2462 switch (mode) {
2463 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2464 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002465 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002466 Setting setting = settingsState.getSettingLocked(name);
2467 if (packageName.equals(setting.getPackageName())) {
2468 if (tag != null && !tag.equals(setting.getTag())) {
2469 continue;
2470 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002471 if (settingsState.resetSettingLocked(name)) {
2472 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002473 notifyForSettingsChange(key, name);
2474 }
2475 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002476 if (someSettingChanged) {
2477 settingsState.persistSyncLocked();
2478 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002479 }
2480 } break;
2481
2482 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2483 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002484 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002485 Setting setting = settingsState.getSettingLocked(name);
2486 if (!SettingsState.isSystemPackage(getContext(),
2487 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002488 if (settingsState.resetSettingLocked(name)) {
2489 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002490 notifyForSettingsChange(key, name);
2491 }
2492 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002493 if (someSettingChanged) {
2494 settingsState.persistSyncLocked();
2495 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002496 }
2497 } break;
2498
2499 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2500 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002501 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002502 Setting setting = settingsState.getSettingLocked(name);
2503 if (!SettingsState.isSystemPackage(getContext(),
2504 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002505 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002506 if (settingsState.resetSettingLocked(name)) {
2507 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002508 notifyForSettingsChange(key, name);
2509 }
2510 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002511 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002512 notifyForSettingsChange(key, name);
2513 }
2514 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002515 if (someSettingChanged) {
2516 settingsState.persistSyncLocked();
2517 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002518 }
2519 } break;
2520
2521 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2522 for (String name : settingsState.getSettingNamesLocked()) {
2523 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002524 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002525 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002526 if (settingsState.resetSettingLocked(name)) {
2527 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002528 notifyForSettingsChange(key, name);
2529 }
2530 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002531 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002532 notifyForSettingsChange(key, name);
2533 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002534 if (someSettingChanged) {
2535 settingsState.persistSyncLocked();
2536 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002537 }
2538 } break;
2539 }
2540 }
2541
Svetoslav683914b2015-01-15 14:22:26 -08002542 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002543 // Global and secure settings are signature protected. Apps signed
2544 // by the platform certificate are generally not uninstalled and
2545 // the main exception is tests. We trust components signed
2546 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002547
2548 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2549 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002550 if (systemSettings != null) {
2551 systemSettings.onPackageRemovedLocked(packageName);
2552 }
Svetoslav683914b2015-01-15 14:22:26 -08002553 }
2554
Mark Rathjend891f012017-01-19 04:10:37 +00002555 public void onUidRemovedLocked(int uid) {
2556 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2557 UserHandle.getUserId(uid));
2558 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2559 }
2560
Svetoslav683914b2015-01-15 14:22:26 -08002561 private SettingsState peekSettingsStateLocked(int key) {
2562 SettingsState settingsState = mSettingsStates.get(key);
2563 if (settingsState != null) {
2564 return settingsState;
2565 }
2566
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002567 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2568 return null;
2569 }
Svetoslav683914b2015-01-15 14:22:26 -08002570 return mSettingsStates.get(key);
2571 }
2572
2573 private void migrateAllLegacySettingsIfNeeded() {
2574 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002575 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002576 File globalFile = getSettingsFile(key);
2577 if (globalFile.exists()) {
2578 return;
2579 }
2580
Amith Yamasani39452022017-03-21 15:23:47 -07002581 mSettingsCreationBuildId = Build.ID;
2582
Svetoslav683914b2015-01-15 14:22:26 -08002583 final long identity = Binder.clearCallingIdentity();
2584 try {
2585 List<UserInfo> users = mUserManager.getUsers(true);
2586
2587 final int userCount = users.size();
2588 for (int i = 0; i < userCount; i++) {
2589 final int userId = users.get(i).id;
2590
2591 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2592 SQLiteDatabase database = dbHelper.getWritableDatabase();
2593 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2594
2595 // Upgrade to the latest version.
2596 UpgradeController upgrader = new UpgradeController(userId);
2597 upgrader.upgradeIfNeededLocked();
2598
2599 // Drop from memory if not a running user.
2600 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2601 removeUserStateLocked(userId, false);
2602 }
2603 }
2604 } finally {
2605 Binder.restoreCallingIdentity(identity);
2606 }
2607 }
2608 }
2609
2610 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2611 // Every user has secure settings and if no file we need to migrate.
2612 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2613 File secureFile = getSettingsFile(secureKey);
2614 if (secureFile.exists()) {
2615 return;
2616 }
2617
2618 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2619 SQLiteDatabase database = dbHelper.getWritableDatabase();
2620
2621 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2622 }
2623
2624 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2625 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002626 // Move over the system settings.
2627 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2628 ensureSettingsStateLocked(systemKey);
2629 SettingsState systemSettings = mSettingsStates.get(systemKey);
2630 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2631 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002632
2633 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002634 // Do this after System settings, since this is the first thing we check when deciding
2635 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002636 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2637 ensureSettingsStateLocked(secureKey);
2638 SettingsState secureSettings = mSettingsStates.get(secureKey);
2639 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2640 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2641 secureSettings.persistSyncLocked();
2642
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002643 // Move over the global settings if owner.
2644 // Do this last, since this is the first thing we check when deciding
2645 // to skip over migration from db to xml for owner user.
2646 if (userId == UserHandle.USER_SYSTEM) {
2647 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2648 ensureSettingsStateLocked(globalKey);
2649 SettingsState globalSettings = mSettingsStates.get(globalKey);
2650 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002651 // If this was just created
2652 if (mSettingsCreationBuildId != null) {
2653 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2654 mSettingsCreationBuildId, null, true,
2655 SettingsState.SYSTEM_PACKAGE_NAME);
2656 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002657 globalSettings.persistSyncLocked();
2658 }
Svetoslav683914b2015-01-15 14:22:26 -08002659
2660 // Drop the database as now all is moved and persisted.
2661 if (DROP_DATABASE_ON_MIGRATION) {
2662 dbHelper.dropDatabase();
2663 } else {
2664 dbHelper.backupDatabase();
2665 }
2666 }
2667
2668 private void migrateLegacySettingsLocked(SettingsState settingsState,
2669 SQLiteDatabase database, String table) {
2670 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2671 queryBuilder.setTables(table);
2672
2673 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2674 null, null, null, null, null);
2675
2676 if (cursor == null) {
2677 return;
2678 }
2679
2680 try {
2681 if (!cursor.moveToFirst()) {
2682 return;
2683 }
2684
2685 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2686 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2687
2688 settingsState.setVersionLocked(database.getVersion());
2689
2690 while (!cursor.isAfterLast()) {
2691 String name = cursor.getString(nameColumnIdx);
2692 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002693 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002694 SettingsState.SYSTEM_PACKAGE_NAME);
2695 cursor.moveToNext();
2696 }
2697 } finally {
2698 cursor.close();
2699 }
2700 }
2701
2702 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2703 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2704
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002705 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002706 return;
2707 }
2708
2709 final int userId = getUserIdFromKey(secureSettings.mKey);
2710
2711 final UserInfo user;
2712 final long identity = Binder.clearCallingIdentity();
2713 try {
2714 user = mUserManager.getUserInfo(userId);
2715 } finally {
2716 Binder.restoreCallingIdentity(identity);
2717 }
2718 if (user == null) {
2719 // Can happen due to races when deleting users - treat as benign.
2720 return;
2721 }
2722
2723 String androidId = Long.toHexString(new SecureRandom().nextLong());
2724 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002725 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002726
2727 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2728 + "] for user " + userId);
2729
2730 // Write a drop box entry if it's a restricted profile
2731 if (user.isRestricted()) {
2732 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2733 Context.DROPBOX_SERVICE);
2734 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2735 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2736 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2737 }
2738 }
2739 }
2740
2741 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002742 final int userId = getUserIdFromKey(key);
2743 Uri uri = getNotificationUriFor(key, name);
2744
Phil Weaver83fec002016-05-11 10:55:29 -07002745 mGenerationRegistry.incrementGeneration(key);
2746
Svetoslav7e0683b2015-08-03 16:02:52 -07002747 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2748 userId, 0, uri).sendToTarget();
2749
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002750 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002751 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2752 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002753 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2754 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002755 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002756 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2757 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002758 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002759
Svet Ganov53a441c2016-04-19 19:38:00 -07002760 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002761 }
2762
Svet Ganov53a441c2016-04-19 19:38:00 -07002763 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002764 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002765 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002766 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002767 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002768 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002769 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002770 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002771 final int key = makeKey(type, profileId);
2772 mGenerationRegistry.incrementGeneration(key);
2773
2774 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002775 }
2776 }
2777 }
Svetoslav683914b2015-01-15 14:22:26 -08002778 }
2779
Svetoslav683914b2015-01-15 14:22:26 -08002780 private boolean isGlobalSettingsKey(int key) {
2781 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2782 }
2783
2784 private boolean isSystemSettingsKey(int key) {
2785 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2786 }
2787
2788 private boolean isSecureSettingsKey(int key) {
2789 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2790 }
2791
Mark Rathjend891f012017-01-19 04:10:37 +00002792 private boolean isSsaidSettingsKey(int key) {
2793 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2794 }
2795
Svetoslav683914b2015-01-15 14:22:26 -08002796 private File getSettingsFile(int key) {
2797 if (isGlobalSettingsKey(key)) {
2798 final int userId = getUserIdFromKey(key);
2799 return new File(Environment.getUserSystemDirectory(userId),
2800 SETTINGS_FILE_GLOBAL);
2801 } else if (isSystemSettingsKey(key)) {
2802 final int userId = getUserIdFromKey(key);
2803 return new File(Environment.getUserSystemDirectory(userId),
2804 SETTINGS_FILE_SYSTEM);
2805 } else if (isSecureSettingsKey(key)) {
2806 final int userId = getUserIdFromKey(key);
2807 return new File(Environment.getUserSystemDirectory(userId),
2808 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002809 } else if (isSsaidSettingsKey(key)) {
2810 final int userId = getUserIdFromKey(key);
2811 return new File(Environment.getUserSystemDirectory(userId),
2812 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002813 } else {
2814 throw new IllegalArgumentException("Invalid settings key:" + key);
2815 }
2816 }
2817
2818 private Uri getNotificationUriFor(int key, String name) {
2819 if (isGlobalSettingsKey(key)) {
2820 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2821 : Settings.Global.CONTENT_URI;
2822 } else if (isSecureSettingsKey(key)) {
2823 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2824 : Settings.Secure.CONTENT_URI;
2825 } else if (isSystemSettingsKey(key)) {
2826 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2827 : Settings.System.CONTENT_URI;
2828 } else {
2829 throw new IllegalArgumentException("Invalid settings key:" + key);
2830 }
2831 }
2832
2833 private int getMaxBytesPerPackageForType(int type) {
2834 switch (type) {
2835 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002836 case SETTINGS_TYPE_SECURE:
2837 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002838 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2839 }
2840
2841 default: {
2842 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2843 }
2844 }
2845 }
2846
Svetoslav7e0683b2015-08-03 16:02:52 -07002847 private final class MyHandler extends Handler {
2848 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2849 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2850
2851 public MyHandler(Looper looper) {
2852 super(looper);
2853 }
2854
2855 @Override
2856 public void handleMessage(Message msg) {
2857 switch (msg.what) {
2858 case MSG_NOTIFY_URI_CHANGED: {
2859 final int userId = msg.arg1;
2860 Uri uri = (Uri) msg.obj;
2861 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2862 if (DEBUG) {
2863 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2864 }
2865 } break;
2866
2867 case MSG_NOTIFY_DATA_CHANGED: {
2868 mBackupManager.dataChanged();
2869 } break;
2870 }
2871 }
2872 }
2873
Svetoslav683914b2015-01-15 14:22:26 -08002874 private final class UpgradeController {
Felipe Lemeff355092017-04-03 12:55:02 -07002875 private static final int SETTINGS_VERSION = 144;
Svetoslav683914b2015-01-15 14:22:26 -08002876
2877 private final int mUserId;
2878
2879 public UpgradeController(int userId) {
2880 mUserId = userId;
2881 }
2882
2883 public void upgradeIfNeededLocked() {
2884 // The version of all settings for a user is the same (all users have secure).
2885 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002886 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002887
2888 // Try an update from the current state.
2889 final int oldVersion = secureSettings.getVersionLocked();
2890 final int newVersion = SETTINGS_VERSION;
2891
Svet Ganovc9755bc2015-03-28 13:21:22 -07002892 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002893 if (oldVersion == newVersion) {
2894 return;
2895 }
2896
2897 // Try to upgrade.
2898 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2899
2900 // If upgrade failed start from scratch and upgrade.
2901 if (curVersion != newVersion) {
2902 // Drop state we have for this user.
2903 removeUserStateLocked(mUserId, true);
2904
2905 // Recreate the database.
2906 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2907 SQLiteDatabase database = dbHelper.getWritableDatabase();
2908 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2909
2910 // Migrate the settings for this user.
2911 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2912
2913 // Now upgrade should work fine.
2914 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002915
2916 // Make a note what happened, so we don't wonder why data was lost
2917 String reason = "Settings rebuilt! Current version: "
2918 + curVersion + " while expected: " + newVersion;
2919 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002920 Settings.Global.DATABASE_DOWNGRADE_REASON,
2921 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002922 }
2923
2924 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002925 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002926 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002927 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002928 globalSettings.setVersionLocked(newVersion);
2929 }
2930
2931 // Set the secure settings version.
2932 secureSettings.setVersionLocked(newVersion);
2933
2934 // Set the system settings version.
2935 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002936 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002937 systemSettings.setVersionLocked(newVersion);
2938 }
2939
2940 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002941 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002942 }
2943
2944 private SettingsState getSecureSettingsLocked(int userId) {
2945 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2946 }
2947
Mark Rathjend891f012017-01-19 04:10:37 +00002948 private SettingsState getSsaidSettingsLocked(int userId) {
2949 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2950 }
2951
Svetoslav683914b2015-01-15 14:22:26 -08002952 private SettingsState getSystemSettingsLocked(int userId) {
2953 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2954 }
2955
Jeff Brown503cffc2015-03-26 18:08:51 -07002956 /**
2957 * You must perform all necessary mutations to bring the settings
2958 * for this user from the old to the new version. When you add a new
2959 * upgrade step you *must* update SETTINGS_VERSION.
2960 *
2961 * This is an example of moving a setting from secure to global.
2962 *
2963 * // v119: Example settings changes.
2964 * if (currentVersion == 118) {
2965 * if (userId == UserHandle.USER_OWNER) {
2966 * // Remove from the secure settings.
2967 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2968 * String name = "example_setting_to_move";
2969 * String value = secureSettings.getSetting(name);
2970 * secureSettings.deleteSetting(name);
2971 *
2972 * // Add to the global settings.
2973 * SettingsState globalSettings = getGlobalSettingsLocked();
2974 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2975 * }
2976 *
2977 * // Update the current version.
2978 * currentVersion = 119;
2979 * }
2980 */
Svetoslav683914b2015-01-15 14:22:26 -08002981 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2982 if (DEBUG) {
2983 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2984 + oldVersion + " to version: " + newVersion);
2985 }
2986
Jeff Brown503cffc2015-03-26 18:08:51 -07002987 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002988
John Spurlocke11ae112015-05-11 16:09:03 -04002989 // v119: Reset zen + ringer mode.
2990 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002991 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002992 final SettingsState globalSettings = getGlobalSettingsLocked();
2993 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002994 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2995 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002996 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002997 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2998 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002999 }
3000 currentVersion = 119;
3001 }
3002
Jason Monk27bbb2d2015-03-31 16:46:39 -04003003 // v120: Add double tap to wake setting.
3004 if (currentVersion == 119) {
3005 SettingsState secureSettings = getSecureSettingsLocked(userId);
3006 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3007 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003008 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003009 SettingsState.SYSTEM_PACKAGE_NAME);
3010
3011 currentVersion = 120;
3012 }
3013
Svetoslav7e0683b2015-08-03 16:02:52 -07003014 if (currentVersion == 120) {
3015 // Before 121, we used a different string encoding logic. We just bump the
3016 // version here; SettingsState knows how to handle pre-version 120 files.
3017 currentVersion = 121;
3018 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003019
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003020 if (currentVersion == 121) {
3021 // Version 122: allow OEMs to set a default payment component in resources.
3022 // Note that we only write the default if no default has been set;
3023 // if there is, we just leave the default at whatever it currently is.
3024 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3025 String defaultComponent = (getContext().getResources().getString(
3026 R.string.def_nfc_payment_component));
3027 Setting currentSetting = secureSettings.getSettingLocked(
3028 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3029 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003030 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003031 secureSettings.insertSettingLocked(
3032 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003033 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003034 }
3035 currentVersion = 122;
3036 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003037
3038 if (currentVersion == 122) {
3039 // Version 123: Adding a default value for the ability to add a user from
3040 // the lock screen.
3041 if (userId == UserHandle.USER_SYSTEM) {
3042 final SettingsState globalSettings = getGlobalSettingsLocked();
3043 Setting currentSetting = globalSettings.getSettingLocked(
3044 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003045 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003046 globalSettings.insertSettingLocked(
3047 Settings.Global.ADD_USERS_WHEN_LOCKED,
3048 getContext().getResources().getBoolean(
3049 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003050 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003051 }
3052 }
3053 currentVersion = 123;
3054 }
Bryce Leebd179282015-12-17 19:01:37 -08003055
3056 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003057 final SettingsState globalSettings = getGlobalSettingsLocked();
3058 String defaultDisabledProfiles = (getContext().getResources().getString(
3059 R.string.def_bluetooth_disabled_profiles));
3060 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003061 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003062 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003063 }
3064
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003065 if (currentVersion == 124) {
3066 // Version 124: allow OEMs to set a default value for whether IME should be
3067 // shown when a physical keyboard is connected.
3068 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3069 Setting currentSetting = secureSettings.getSettingLocked(
3070 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003071 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003072 secureSettings.insertSettingLocked(
3073 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3074 getContext().getResources().getBoolean(
3075 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003076 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003077 }
3078 currentVersion = 125;
3079 }
3080
Ruben Brunk98576cf2016-03-07 18:54:28 -08003081 if (currentVersion == 125) {
3082 // Version 125: Allow OEMs to set the default VR service.
3083 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3084
3085 Setting currentSetting = secureSettings.getSettingLocked(
3086 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003087 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003088 ArraySet<ComponentName> l =
3089 SystemConfig.getInstance().getDefaultVrComponents();
3090
3091 if (l != null && !l.isEmpty()) {
3092 StringBuilder b = new StringBuilder();
3093 boolean start = true;
3094 for (ComponentName c : l) {
3095 if (!start) {
3096 b.append(':');
3097 }
3098 b.append(c.flattenToString());
3099 start = false;
3100 }
3101 secureSettings.insertSettingLocked(
3102 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003103 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003104 }
3105
3106 }
3107 currentVersion = 126;
3108 }
3109
Daniel U02ba6122016-04-01 18:41:42 +01003110 if (currentVersion == 126) {
3111 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3112 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3113 if (mUserManager.isManagedProfile(userId)) {
3114 final SettingsState systemSecureSettings =
3115 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3116
3117 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3118 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003119 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003120 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3121 secureSettings.insertSettingLocked(
3122 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003123 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003124 SettingsState.SYSTEM_PACKAGE_NAME);
3125 }
3126
3127 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3128 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003129 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003130 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3131 secureSettings.insertSettingLocked(
3132 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003133 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003134 SettingsState.SYSTEM_PACKAGE_NAME);
3135 }
3136 }
3137 currentVersion = 127;
3138 }
3139
Steven Ngdc20ba62016-04-26 18:19:04 +01003140 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003141 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003142 currentVersion = 128;
3143 }
3144
Julia Reynolds1f721e12016-07-11 08:50:58 -04003145 if (currentVersion == 128) {
3146 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3147 // the new apps are appended to the list of already approved apps.
3148 final SettingsState systemSecureSettings =
3149 getSecureSettingsLocked(userId);
3150
3151 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3152 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3153 String defaultPolicyAccess = getContext().getResources().getString(
3154 com.android.internal.R.string.config_defaultDndAccessPackages);
3155 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3156 if (policyAccess.isNull()) {
3157 systemSecureSettings.insertSettingLocked(
3158 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003159 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003160 SettingsState.SYSTEM_PACKAGE_NAME);
3161 } else {
3162 StringBuilder currentSetting =
3163 new StringBuilder(policyAccess.getValue());
3164 currentSetting.append(":");
3165 currentSetting.append(defaultPolicyAccess);
3166 systemSecureSettings.updateSettingLocked(
3167 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003168 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003169 SettingsState.SYSTEM_PACKAGE_NAME);
3170 }
3171 }
3172
3173 currentVersion = 129;
3174 }
3175
Dan Sandler71f85e92016-07-20 13:46:05 -04003176 if (currentVersion == 129) {
3177 // default longpress timeout changed from 500 to 400. If unchanged from the old
3178 // default, update to the new default.
3179 final SettingsState systemSecureSettings =
3180 getSecureSettingsLocked(userId);
3181 final String oldValue = systemSecureSettings.getSettingLocked(
3182 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3183 if (TextUtils.equals("500", oldValue)) {
3184 systemSecureSettings.insertSettingLocked(
3185 Settings.Secure.LONG_PRESS_TIMEOUT,
3186 String.valueOf(getContext().getResources().getInteger(
3187 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003188 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003189 }
3190 currentVersion = 130;
3191 }
3192
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003193 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003194 // Split Ambient settings
3195 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3196 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3197 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3198
3199 if (dozeExplicitlyDisabled) {
3200 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003201 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003202 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003203 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003204 }
3205 currentVersion = 131;
3206 }
3207
3208 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003209 // Initialize new multi-press timeout to default value
3210 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3211 final String oldValue = systemSecureSettings.getSettingLocked(
3212 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3213 if (TextUtils.equals(null, oldValue)) {
3214 systemSecureSettings.insertSettingLocked(
3215 Settings.Secure.MULTI_PRESS_TIMEOUT,
3216 String.valueOf(getContext().getResources().getInteger(
3217 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003218 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003219 }
3220
Adrian Roos69741a22016-10-21 14:49:17 -07003221 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003222 }
3223
Adrian Roos69741a22016-10-21 14:49:17 -07003224 if (currentVersion == 132) {
3225 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003226 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3227 String defaultSyncParentSounds = (getContext().getResources()
3228 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3229 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003230 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3231 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003232 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003233 }
3234
Adrian Roos69741a22016-10-21 14:49:17 -07003235 if (currentVersion == 133) {
3236 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003237 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3238 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3239 null) {
3240 String defaultEndButtonBehavior = Integer.toString(getContext()
3241 .getResources().getInteger(R.integer.def_end_button_behavior));
3242 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003243 defaultEndButtonBehavior, null, true,
3244 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003245 }
Adrian Roos69741a22016-10-21 14:49:17 -07003246 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003247 }
3248
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003249 if (currentVersion == 134) {
3250 // Remove setting that specifies if magnification values should be preserved.
3251 // This setting defaulted to true and never has a UI.
3252 getSecureSettingsLocked(userId).deleteSettingLocked(
3253 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3254 currentVersion = 135;
3255 }
3256
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003257 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003258 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003259 currentVersion = 136;
3260 }
3261
Mark Rathjend891f012017-01-19 04:10:37 +00003262 if (currentVersion == 136) {
3263 // Version 136: Store legacy SSAID for all apps currently installed on the
3264 // device as first step in migrating SSAID to be unique per application.
3265
3266 final boolean isUpgrade;
3267 try {
3268 isUpgrade = mPackageManager.isUpgrade();
3269 } catch (RemoteException e) {
3270 throw new IllegalStateException("Package manager not available");
3271 }
3272 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3273 // user data or first boot on a new device should use new ssaid generation.
3274 if (isUpgrade) {
3275 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003276 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3277 userId, Settings.Secure.ANDROID_ID);
3278 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3279 || legacySsaidSetting.getValue() == null) {
3280 throw new IllegalStateException("Legacy ssaid not accessible");
3281 }
3282 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003283
3284 // Fill each uid with the legacy ssaid to be backwards compatible.
3285 final List<PackageInfo> packages;
3286 try {
3287 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3288 } catch (RemoteException e) {
3289 throw new IllegalStateException("Package manager not available");
3290 }
3291
3292 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3293 for (PackageInfo info : packages) {
3294 // Check if the UID already has an entry in the table.
3295 final String uid = Integer.toString(info.applicationInfo.uid);
3296 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3297
3298 if (ssaid.isNull() || ssaid.getValue() == null) {
3299 // Android Id doesn't exist for this package so create it.
3300 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3301 info.packageName);
3302 }
3303 }
3304 }
3305
3306 currentVersion = 137;
3307 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003308 if (currentVersion == 137) {
3309 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3310 // default value set to 1. The user can no longer change the value of this
3311 // setting through the UI.
3312 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3313 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003314 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3315 && secureSetting.getSettingLocked(
3316 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3317
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003318 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3319 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003320 // For managed profiles with profile owners, DevicePolicyManagerService
3321 // may want to set the user restriction in this case
3322 secureSetting.insertSettingLocked(
3323 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3324 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003325 }
3326 currentVersion = 138;
3327 }
Mark Rathjend891f012017-01-19 04:10:37 +00003328
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003329 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003330 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003331 currentVersion = 139;
3332 }
3333
Phil Weaver385912e2017-02-10 10:06:56 -08003334 if (currentVersion == 139) {
3335 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3336 // the user can no longer change the value of this setting through the UI.
3337 // Force to true.
3338 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3339 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3340 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3341 currentVersion = 140;
3342 }
3343
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003344 if (currentVersion == 140) {
3345 // Version 141: One-time grant of notification listener privileges
3346 // to packages specified in overlay.
3347 String defaultListenerAccess = getContext().getResources().getString(
3348 com.android.internal.R.string.config_defaultListenerAccessPackages);
3349 if (defaultListenerAccess != null) {
3350 StringBuffer newListeners = new StringBuffer();
3351 for (String whitelistPkg : defaultListenerAccess.split(":")) {
3352 // Gather all notification listener components for candidate pkgs.
3353 Intent serviceIntent =
3354 new Intent(NotificationListenerService.SERVICE_INTERFACE)
3355 .setPackage(whitelistPkg);
3356 List<ResolveInfo> installedServices =
3357 getContext().getPackageManager().queryIntentServicesAsUser(
3358 serviceIntent,
3359 PackageManager.GET_SERVICES
3360 | PackageManager.GET_META_DATA
3361 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3362 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
3363 userId);
3364
3365 for (int i = 0, count = installedServices.size(); i < count; i++) {
3366 ResolveInfo resolveInfo = installedServices.get(i);
3367 ServiceInfo info = resolveInfo.serviceInfo;
3368 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
3369 .equals(info.permission)) {
3370 continue;
3371 }
3372 newListeners.append(":")
3373 .append(info.getComponentName().flattenToString());
3374 }
3375 }
3376
3377 if (newListeners.length() > 0) {
3378 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3379 final Setting existingSetting = secureSetting.getSettingLocked(
3380 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
3381 if (existingSetting.isNull()) {
3382 secureSetting.insertSettingLocked(
3383 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3384 newListeners.toString(), null, true,
3385 SettingsState.SYSTEM_PACKAGE_NAME);
3386 } else {
3387 StringBuilder currentSetting =
3388 new StringBuilder(existingSetting.getValue());
3389 currentSetting.append(newListeners.toString());
3390 secureSetting.updateSettingLocked(
3391 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3392 currentSetting.toString(), null, true,
3393 SettingsState.SYSTEM_PACKAGE_NAME);
3394 }
3395 }
3396 }
3397 currentVersion = 141;
3398 }
3399
Svet Ganov13701552017-02-23 12:45:17 -08003400 if (currentVersion == 141) {
Felipe Lemeff355092017-04-03 12:55:02 -07003401 // Version 142: We added the notion of a default and whether the system set
Svet Ganov13701552017-02-23 12:45:17 -08003402 // the setting. This is used for resetting the internal state and we need
3403 // to make sure this value is updated for the existing settings, otherwise
3404 // we would delete system set settings while they should stay unmodified.
3405 SettingsState globalSettings = getGlobalSettingsLocked();
3406 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3407 globalSettings.persistSyncLocked();
3408
3409 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3410 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3411 secureSettings.persistSyncLocked();
3412
3413 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3414 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3415 systemSettings.persistSyncLocked();
3416
3417 currentVersion = 142;
3418 }
3419
Stephen Chen5d0922f2017-03-27 10:28:04 -07003420 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003421 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003422 if (userId == UserHandle.USER_SYSTEM) {
3423 final SettingsState globalSettings = getGlobalSettingsLocked();
3424 Setting currentSetting = globalSettings.getSettingLocked(
3425 Settings.Global.WIFI_WAKEUP_ENABLED);
3426 if (currentSetting.isNull()) {
3427 globalSettings.insertSettingLocked(
3428 Settings.Global.WIFI_WAKEUP_ENABLED,
3429 getContext().getResources().getBoolean(
3430 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3431 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3432 }
3433 }
3434
3435 currentVersion = 143;
3436 }
3437
Felipe Lemeff355092017-04-03 12:55:02 -07003438 if (currentVersion == 143) {
3439 // Version 144: Set a default value for Autofill service.
3440 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3441 final Setting currentSetting = secureSettings
3442 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3443 if (currentSetting.isNull()) {
3444 final String defaultValue = getContext().getResources().getString(
3445 com.android.internal.R.string.config_defaultAutofillService);
3446 if (defaultValue != null) {
3447 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3448 + "for user " + userId);
3449 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3450 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3451 }
3452 }
3453
3454 currentVersion = 144;
3455 }
3456
3457 // vXXX: Add new settings above this point.
3458
Dan Sandler71f85e92016-07-20 13:46:05 -04003459 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003460 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003461 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003462 + currentVersion +
3463 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3464 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003465 if (DEBUG) {
3466 throw new RuntimeException("db upgrade error");
3467 }
3468 }
3469
Jeff Brown503cffc2015-03-26 18:08:51 -07003470 // Return the current version.
3471 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003472 }
3473 }
Svet Ganov13701552017-02-23 12:45:17 -08003474
3475 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3476 List<String> names = settings.getSettingNamesLocked();
3477 final int nameCount = names.size();
3478 for (int i = 0; i < nameCount; i++) {
3479 String name = names.get(i);
3480 Setting setting = settings.getSettingLocked(name);
3481 if (setting.getDefaultValue() == null) {
3482 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3483 setting.getPackageName());
3484 if (systemSet) {
3485 settings.insertSettingLocked(name, setting.getValue(),
3486 setting.getTag(), true, setting.getPackageName());
3487 }
3488 }
3489 }
3490 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003491 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003492}