blob: 91a4e792bbb81c2ab547503ca37a661b4d85f159 [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;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040043import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080047import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070048import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080049import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070051import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070052import android.os.Looper;
53import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070055import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070056import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070057import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070058import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.os.UserHandle;
60import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070061import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.provider.Settings;
Julia Reynoldsad0d9e02017-02-15 08:41:48 -050063import android.service.notification.NotificationListenerService;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010065import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080066import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000067import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070068import android.util.Slog;
69import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070070import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080071import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040072
Svetoslav683914b2015-01-15 14:22:26 -080073import com.android.internal.annotations.GuardedBy;
74import com.android.internal.content.PackageMonitor;
75import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080076import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070077import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080078import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040079
Svetoslav683914b2015-01-15 14:22:26 -080080import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080081import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080082import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080083import java.io.PrintWriter;
Mark Rathjend891f012017-01-19 04:10:37 +000084import java.nio.charset.StandardCharsets;
Mark Rathjen7599f132017-01-23 14:15:54 -080085import java.nio.ByteBuffer;
86import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000087import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070089import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080090import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000091import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080094import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010095import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080096import java.util.Set;
97import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080098import javax.crypto.Mac;
99import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700100
Svetoslav Ganove080da92016-12-21 17:10:35 -0800101import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800102import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800103import static android.os.Process.SYSTEM_UID;
104
Svetoslav Ganove080da92016-12-21 17:10:35 -0800105
Svetoslav683914b2015-01-15 14:22:26 -0800106/**
107 * <p>
108 * This class is a content provider that publishes the system settings.
109 * It can be accessed via the content provider APIs or via custom call
110 * commands. The latter is a bit faster and is the preferred way to access
111 * the platform settings.
112 * </p>
113 * <p>
114 * There are three settings types, global (with signature level protection
115 * and shared across users), secure (with signature permission level
116 * protection and per user), and system (with dangerous permission level
117 * protection and per user). Global settings are stored under the device owner.
118 * Each of these settings is represented by a {@link
119 * com.android.providers.settings.SettingsState} object mapped to an integer
120 * key derived from the setting type in the most significant bits and user
121 * id in the least significant bits. Settings are synchronously loaded on
122 * instantiation of a SettingsState and asynchronously persisted on mutation.
123 * Settings are stored in the user specific system directory.
124 * </p>
125 * <p>
126 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
127 * and get a warning. Targeting higher API version prohibits this as the
128 * system settings are not a place for apps to save their state. When a package
129 * is removed the settings it added are deleted. Apps cannot delete system
130 * settings added by the platform. System settings values are validated to
131 * ensure the clients do not put bad values. Global and secure settings are
132 * changed only by trusted parties, therefore no validation is performed. Also
133 * there is a limit on the amount of app specific settings that can be added
134 * to prevent unlimited growth of the system process memory footprint.
135 * </p>
136 */
137@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700139 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700141 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800142
143 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700144
Christopher Tate06efb532012-08-24 15:29:27 -0700145 private static final String TABLE_SYSTEM = "system";
146 private static final String TABLE_SECURE = "secure";
147 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800148
149 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private static final String TABLE_FAVORITES = "favorites";
151 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800152 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
153 private static final String TABLE_BOOKMARKS = "bookmarks";
154 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Svetoslav683914b2015-01-15 14:22:26 -0800156 // The set of removed legacy tables.
157 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700158 static {
Svetoslav683914b2015-01-15 14:22:26 -0800159 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
160 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
161 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
162 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
163 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
164 }
Christopher Tate06efb532012-08-24 15:29:27 -0700165
Svetoslav683914b2015-01-15 14:22:26 -0800166 private static final int MUTATION_OPERATION_INSERT = 1;
167 private static final int MUTATION_OPERATION_DELETE = 2;
168 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800169 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400170
Svetoslav683914b2015-01-15 14:22:26 -0800171 private static final String[] ALL_COLUMNS = new String[] {
172 Settings.NameValueTable._ID,
173 Settings.NameValueTable.NAME,
174 Settings.NameValueTable.VALUE
175 };
176
Svet Ganov53a441c2016-04-19 19:38:00 -0700177 public static final int SETTINGS_TYPE_GLOBAL = 0;
178 public static final int SETTINGS_TYPE_SYSTEM = 1;
179 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000180 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800181
Svet Ganov53a441c2016-04-19 19:38:00 -0700182 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
183 public static final int SETTINGS_TYPE_SHIFT = 28;
184
185 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
186 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700187
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800188 // Changes to these global settings are synchronously persisted
189 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
190 static {
191 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
192 }
193
194 // Changes to these secure settings are synchronously persisted
195 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
196 static {
197 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
198 }
199
Svetoslav683914b2015-01-15 14:22:26 -0800200 // Per user secure settings that moved to the for all users global settings.
201 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
202 static {
203 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700204 }
205
Svetoslav683914b2015-01-15 14:22:26 -0800206 // Per user system settings that moved to the for all users global settings.
207 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
208 static {
209 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700210 }
211
Svetoslav683914b2015-01-15 14:22:26 -0800212 // Per user system settings that moved to the per user secure settings.
213 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
214 static {
215 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700216 }
217
Svetoslav683914b2015-01-15 14:22:26 -0800218 // Per all users global settings that moved to the per user secure settings.
219 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
220 static {
221 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700222 }
223
Svetoslav683914b2015-01-15 14:22:26 -0800224 // Per user secure settings that are cloned for the managed profiles of the user.
225 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
226 static {
227 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700228 }
229
Svetoslav683914b2015-01-15 14:22:26 -0800230 // Per user system settings that are cloned for the managed profiles of the user.
231 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
232 static {
233 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400234 }
235
Andre Lago3fa139c2016-08-04 13:53:44 +0100236 // Per user system settings that are cloned from the profile's parent when a dependency
237 // in {@link Settings.Secure} is set to "1".
238 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
239 static {
240 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
241 }
242
Svetoslav683914b2015-01-15 14:22:26 -0800243 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700244
Svetoslav683914b2015-01-15 14:22:26 -0800245 @GuardedBy("mLock")
246 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700247
Svet Ganova8f90262016-05-10 08:44:48 -0700248 @GuardedBy("mLock")
249 private HandlerThread mHandlerThread;
250
Svetoslav7ec28e82015-05-20 17:01:10 -0700251 // We have to call in the user manager with no lock held,
252 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800253
Svetoslav7ec28e82015-05-20 17:01:10 -0700254 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700255 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700256
Svet Ganov53a441c2016-04-19 19:38:00 -0700257 public static int makeKey(int type, int userId) {
258 return (type << SETTINGS_TYPE_SHIFT) | userId;
259 }
260
261 public static int getTypeFromKey(int key) {
262 return key >>> SETTINGS_TYPE_SHIFT;
263 }
264
265 public static int getUserIdFromKey(int key) {
266 return key & ~SETTINGS_TYPE_MASK;
267 }
268
269 public static String settingTypeToString(int type) {
270 switch (type) {
271 case SETTINGS_TYPE_GLOBAL: {
272 return "SETTINGS_GLOBAL";
273 }
274 case SETTINGS_TYPE_SECURE: {
275 return "SETTINGS_SECURE";
276 }
277 case SETTINGS_TYPE_SYSTEM: {
278 return "SETTINGS_SYSTEM";
279 }
Mark Rathjend891f012017-01-19 04:10:37 +0000280 case SETTINGS_TYPE_SSAID: {
281 return "SETTINGS_SSAID";
282 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700283 default: {
284 return "UNKNOWN";
285 }
286 }
287 }
288
289 public static String keyToString(int key) {
290 return "Key[user=" + getUserIdFromKey(key) + ";type="
291 + settingTypeToString(getTypeFromKey(key)) + "]";
292 }
293
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700294 @Override
295 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800296 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800297 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700298 mUserManager = UserManager.get(getContext());
299 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700300 mHandlerThread = new HandlerThread(LOG_TAG,
301 Process.THREAD_PRIORITY_BACKGROUND);
302 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800303 mSettingsRegistry = new SettingsRegistry();
304 }
305 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700306 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700307 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 return true;
309 }
310
Svetoslav683914b2015-01-15 14:22:26 -0800311 @Override
312 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700313 final int requestingUserId = getRequestingUserId(args);
314 switch (method) {
315 case Settings.CALL_METHOD_GET_GLOBAL: {
316 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700317 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800318 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700319
320 case Settings.CALL_METHOD_GET_SECURE: {
321 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700322 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700323 }
324
325 case Settings.CALL_METHOD_GET_SYSTEM: {
326 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700327 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700328 }
329
330 case Settings.CALL_METHOD_PUT_GLOBAL: {
331 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800332 String tag = getSettingTag(args);
333 final boolean makeDefault = getSettingMakeDefault(args);
334 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700335 break;
336 }
337
338 case Settings.CALL_METHOD_PUT_SECURE: {
339 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800340 String tag = getSettingTag(args);
341 final boolean makeDefault = getSettingMakeDefault(args);
342 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700343 break;
344 }
345
346 case Settings.CALL_METHOD_PUT_SYSTEM: {
347 String value = getSettingValue(args);
348 insertSystemSetting(name, value, requestingUserId);
349 break;
350 }
351
Svetoslav Ganove080da92016-12-21 17:10:35 -0800352 case Settings.CALL_METHOD_RESET_GLOBAL: {
353 final int mode = getResetModeEnforcingPermission(args);
354 String tag = getSettingTag(args);
355 resetGlobalSetting(requestingUserId, mode, tag);
356 break;
357 }
358
359 case Settings.CALL_METHOD_RESET_SECURE: {
360 final int mode = getResetModeEnforcingPermission(args);
361 String tag = getSettingTag(args);
362 resetSecureSetting(requestingUserId, mode, tag);
363 break;
364 }
365
Svetoslav7ec28e82015-05-20 17:01:10 -0700366 default: {
367 Slog.w(LOG_TAG, "call() with invalid method: " + method);
368 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700369 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700370
Christopher Tate06efb532012-08-24 15:29:27 -0700371 return null;
372 }
373
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800374 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800375 public String getType(Uri uri) {
376 Arguments args = new Arguments(uri, null, null, true);
377 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378 return "vnd.android.cursor.dir/" + args.table;
379 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700380 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700381 }
382 }
383
384 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800385 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
386 String order) {
387 if (DEBUG) {
388 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389 }
390
Svetoslav683914b2015-01-15 14:22:26 -0800391 Arguments args = new Arguments(uri, where, whereArgs, true);
392 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700393
Svetoslav683914b2015-01-15 14:22:26 -0800394 // If a legacy table that is gone, done.
395 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
396 return new MatrixCursor(normalizedProjection, 0);
397 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700398
Svetoslav7ec28e82015-05-20 17:01:10 -0700399 switch (args.table) {
400 case TABLE_GLOBAL: {
401 if (args.name != null) {
402 Setting setting = getGlobalSetting(args.name);
403 return packageSettingForQuery(setting, normalizedProjection);
404 } else {
405 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700406 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700407 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700408
Svetoslav7ec28e82015-05-20 17:01:10 -0700409 case TABLE_SECURE: {
410 final int userId = UserHandle.getCallingUserId();
411 if (args.name != null) {
412 Setting setting = getSecureSetting(args.name, userId);
413 return packageSettingForQuery(setting, normalizedProjection);
414 } else {
415 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800416 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700417 }
Svetoslav683914b2015-01-15 14:22:26 -0800418
Svetoslav7ec28e82015-05-20 17:01:10 -0700419 case TABLE_SYSTEM: {
420 final int userId = UserHandle.getCallingUserId();
421 if (args.name != null) {
422 Setting setting = getSystemSetting(args.name, userId);
423 return packageSettingForQuery(setting, normalizedProjection);
424 } else {
425 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800426 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700427 }
Svetoslav683914b2015-01-15 14:22:26 -0800428
Svetoslav7ec28e82015-05-20 17:01:10 -0700429 default: {
430 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700431 }
432 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700433 }
434
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700435 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800436 public Uri insert(Uri uri, ContentValues values) {
437 if (DEBUG) {
438 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700439 }
440
Svetoslav683914b2015-01-15 14:22:26 -0800441 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700442
Svetoslav683914b2015-01-15 14:22:26 -0800443 // If a legacy table that is gone, done.
444 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 return null;
446 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700447
Svetoslav683914b2015-01-15 14:22:26 -0800448 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700449 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800450 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700451 }
452
Svetoslav683914b2015-01-15 14:22:26 -0800453 String value = values.getAsString(Settings.Secure.VALUE);
454
Svetoslav7ec28e82015-05-20 17:01:10 -0700455 switch (table) {
456 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800457 if (insertGlobalSetting(name, value, null, false,
458 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700459 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700460 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700461 } break;
462
463 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800464 if (insertSecureSetting(name, value, null, false,
465 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700466 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
467 }
468 } break;
469
470 case TABLE_SYSTEM: {
471 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
472 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
473 }
474 } break;
475
476 default: {
477 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700478 }
479 }
480
Svetoslav683914b2015-01-15 14:22:26 -0800481 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482 }
483
484 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800485 public int bulkInsert(Uri uri, ContentValues[] allValues) {
486 if (DEBUG) {
487 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489
Svetoslav683914b2015-01-15 14:22:26 -0800490 int insertionCount = 0;
491 final int valuesCount = allValues.length;
492 for (int i = 0; i < valuesCount; i++) {
493 ContentValues values = allValues[i];
494 if (insert(uri, values) != null) {
495 insertionCount++;
496 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700497 }
Svetoslav683914b2015-01-15 14:22:26 -0800498
499 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500 }
501
502 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800503 public int delete(Uri uri, String where, String[] whereArgs) {
504 if (DEBUG) {
505 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700507
Svetoslav683914b2015-01-15 14:22:26 -0800508 Arguments args = new Arguments(uri, where, whereArgs, false);
509
510 // If a legacy table that is gone, done.
511 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
512 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700513 }
Svetoslav683914b2015-01-15 14:22:26 -0800514
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700515 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800516 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700517 }
Svetoslav683914b2015-01-15 14:22:26 -0800518
Svetoslav7ec28e82015-05-20 17:01:10 -0700519 switch (args.table) {
520 case TABLE_GLOBAL: {
521 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700522 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700523 }
Svetoslav683914b2015-01-15 14:22:26 -0800524
Svetoslav7ec28e82015-05-20 17:01:10 -0700525 case TABLE_SECURE: {
526 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700527 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700528 }
Svetoslav683914b2015-01-15 14:22:26 -0800529
Svetoslav7ec28e82015-05-20 17:01:10 -0700530 case TABLE_SYSTEM: {
531 final int userId = UserHandle.getCallingUserId();
532 return deleteSystemSetting(args.name, userId) ? 1 : 0;
533 }
534
535 default: {
536 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800537 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700538 }
Svetoslav683914b2015-01-15 14:22:26 -0800539 }
540
541 @Override
542 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
543 if (DEBUG) {
544 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700545 }
Svetoslav683914b2015-01-15 14:22:26 -0800546
547 Arguments args = new Arguments(uri, where, whereArgs, false);
548
549 // If a legacy table that is gone, done.
550 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
551 return 0;
552 }
553
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700554 String name = values.getAsString(Settings.Secure.NAME);
555 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800556 return 0;
557 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700558 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800559
Svetoslav7ec28e82015-05-20 17:01:10 -0700560 switch (args.table) {
561 case TABLE_GLOBAL: {
562 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800563 return updateGlobalSetting(args.name, value, null, false,
564 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700565 }
Svetoslav683914b2015-01-15 14:22:26 -0800566
Svetoslav7ec28e82015-05-20 17:01:10 -0700567 case TABLE_SECURE: {
568 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800569 return updateSecureSetting(args.name, value, null, false,
570 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700571 }
Svetoslav683914b2015-01-15 14:22:26 -0800572
Svetoslav7ec28e82015-05-20 17:01:10 -0700573 case TABLE_SYSTEM: {
574 final int userId = UserHandle.getCallingUserId();
575 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
576 }
Svetoslav683914b2015-01-15 14:22:26 -0800577
Svetoslav7ec28e82015-05-20 17:01:10 -0700578 default: {
579 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800580 }
581 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700582 }
583
584 @Override
585 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100586 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
587 if (userId != UserHandle.getCallingUserId()) {
588 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
589 "Access files from the settings of another user");
590 }
591 uri = ContentProvider.getUriWithoutUserId(uri);
592
Andre Lago3fa139c2016-08-04 13:53:44 +0100593 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700594 final String cacheName;
595 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100596 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700597 cacheName = Settings.System.RINGTONE_CACHE;
598 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100599 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700600 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
601 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100602 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700603 cacheName = Settings.System.ALARM_ALERT_CACHE;
604 } else {
605 throw new FileNotFoundException("Direct file access no longer supported; "
606 + "ringtone playback is available through android.media.Ringtone");
607 }
608
Andre Lago3fa139c2016-08-04 13:53:44 +0100609 int actualCacheOwner;
610 // Redirect cache to parent if ringtone setting is owned by profile parent
611 synchronized (mLock) {
612 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
613 cacheRingtoneSetting);
614 }
615 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700616 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
617 }
618
619 private File getRingtoneCacheDir(int userId) {
620 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
621 cacheDir.mkdir();
622 SELinux.restorecon(cacheDir);
623 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700624 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800625
Eugene Suslad72c3972016-12-27 15:49:30 -0800626 /**
627 * Dump all settings as a proto buf.
628 *
629 * @param fd The file to dump to
630 */
631 void dumpProto(@NonNull FileDescriptor fd) {
632 ProtoOutputStream proto = new ProtoOutputStream(fd);
633
634 synchronized (mLock) {
635 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
636
637 }
638
639 proto.flush();
640 }
641
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700642 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800643 synchronized (mLock) {
644 final long identity = Binder.clearCallingIdentity();
645 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700646 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800647 final int userCount = users.size();
648 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700649 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800650 }
651 } finally {
652 Binder.restoreCallingIdentity(identity);
653 }
654 }
655 }
656
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700657 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700658 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800659 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700660 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
661 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700662 if (globalSettings != null) {
663 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800664 pw.println();
665 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700666 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800667 }
668
669 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700670 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
671 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700672 if (secureSettings != null) {
673 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800674 pw.println();
675 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700676 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700677
Svetoslavb505ccc2015-02-17 12:41:04 -0800678 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700679 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
680 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700681 if (systemSettings != null) {
682 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800683 pw.println();
684 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700685 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800686 }
687
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700688 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
689 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800690
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700691 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800692
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700693 for (int i = 0; i < nameCount; i++) {
694 String name = names.get(i);
695 Setting setting = settingsState.getSettingLocked(name);
696 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
697 pw.print(" name:"); pw.print(toDumpString(name));
698 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800699 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700700 }
701 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800702 if (setting.getDefaultValue() != null) {
703 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800704 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800705 }
706 if (setting.getTag() != null) {
707 pw.print(" tag:"); pw.print(setting.getTag());
708 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800709 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700710 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800711 }
712
Svetoslav7e0683b2015-08-03 16:02:52 -0700713 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700714 if (s != null) {
715 return s;
716 }
717 return "{null}";
718 }
719
Svetoslav683914b2015-01-15 14:22:26 -0800720 private void registerBroadcastReceivers() {
721 IntentFilter userFilter = new IntentFilter();
722 userFilter.addAction(Intent.ACTION_USER_REMOVED);
723 userFilter.addAction(Intent.ACTION_USER_STOPPED);
724
725 getContext().registerReceiver(new BroadcastReceiver() {
726 @Override
727 public void onReceive(Context context, Intent intent) {
728 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700729 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800730
731 switch (intent.getAction()) {
732 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700733 synchronized (mLock) {
734 mSettingsRegistry.removeUserStateLocked(userId, true);
735 }
Svetoslav683914b2015-01-15 14:22:26 -0800736 } break;
737
738 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700739 synchronized (mLock) {
740 mSettingsRegistry.removeUserStateLocked(userId, false);
741 }
Svetoslav683914b2015-01-15 14:22:26 -0800742 } break;
743 }
744 }
745 }, userFilter);
746
747 PackageMonitor monitor = new PackageMonitor() {
748 @Override
749 public void onPackageRemoved(String packageName, int uid) {
750 synchronized (mLock) {
751 mSettingsRegistry.onPackageRemovedLocked(packageName,
752 UserHandle.getUserId(uid));
753 }
754 }
Mark Rathjend891f012017-01-19 04:10:37 +0000755
756 @Override
757 public void onUidRemoved(int uid) {
758 synchronized (mLock) {
759 mSettingsRegistry.onUidRemovedLocked(uid);
760 }
761 }
Svetoslav683914b2015-01-15 14:22:26 -0800762 };
763
764 // package changes
765 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
766 UserHandle.ALL, true);
767 }
768
Svet Ganov53a441c2016-04-19 19:38:00 -0700769 private void startWatchingUserRestrictionChanges() {
770 // TODO: The current design of settings looking different based on user restrictions
771 // should be reworked to keep them separate and system code should check the setting
772 // first followed by checking the user restriction before performing an operation.
773 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
774 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
775 Bundle prevRestrictions) -> {
776 // We are changing the settings affected by restrictions to their current
777 // value with a forced update to ensure that all cross profile dependencies
778 // are taken into account. Also make sure the settings update to.. the same
779 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800780 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
781 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700782 final long identity = Binder.clearCallingIdentity();
783 try {
784 synchronized (mLock) {
785 Setting setting = getSecureSetting(
786 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
787 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800788 setting != null ? setting.getValue() : null, null,
789 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700790 }
791 } finally {
792 Binder.restoreCallingIdentity(identity);
793 }
794 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800795 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
796 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700797 final long identity = Binder.clearCallingIdentity();
798 try {
799 synchronized (mLock) {
800 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800801 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700802 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800803 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700804 }
805 } finally {
806 Binder.restoreCallingIdentity(identity);
807 }
808 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800809 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
810 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700811 final long identity = Binder.clearCallingIdentity();
812 try {
813 synchronized (mLock) {
814 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700816 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800817 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700818 }
819 } finally {
820 Binder.restoreCallingIdentity(identity);
821 }
822 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800823 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
824 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700825 final long identity = Binder.clearCallingIdentity();
826 try {
827 synchronized (mLock) {
828 Setting enable = getGlobalSetting(
829 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800830 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800832 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700833 Setting include = getGlobalSetting(
834 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800835 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700836 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800837 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700838 }
839 } finally {
840 Binder.restoreCallingIdentity(identity);
841 }
842 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800843 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
844 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700845 final long identity = Binder.clearCallingIdentity();
846 try {
847 synchronized (mLock) {
848 Setting setting = getGlobalSetting(
849 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800850 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700851 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800852 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700853 }
854 } finally {
855 Binder.restoreCallingIdentity(identity);
856 }
857 }
858 });
859 }
860
Svetoslav7ec28e82015-05-20 17:01:10 -0700861 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800862 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700863 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800864 }
865
Svetoslav7ec28e82015-05-20 17:01:10 -0700866 synchronized (mLock) {
867 // Get the settings.
868 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700869 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800870
Chad Brubaker97bccee2017-01-05 15:51:41 -0800871 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
872 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800873
Svetoslav7ec28e82015-05-20 17:01:10 -0700874 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800875
Svetoslav7ec28e82015-05-20 17:01:10 -0700876 String[] normalizedProjection = normalizeProjection(projection);
877 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800878
Svetoslav7ec28e82015-05-20 17:01:10 -0700879 // Anyone can get the global settings, so no security checks.
880 for (int i = 0; i < nameCount; i++) {
881 String name = names.get(i);
882 Setting setting = settingsState.getSettingLocked(name);
883 appendSettingToCursor(result, setting);
884 }
885
886 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800887 }
Svetoslav683914b2015-01-15 14:22:26 -0800888 }
889
Svetoslav7ec28e82015-05-20 17:01:10 -0700890 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800891 if (DEBUG) {
892 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
893 }
894
Chad Brubaker97bccee2017-01-05 15:51:41 -0800895 // Ensure the caller can access the setting.
896 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
897
Svetoslav683914b2015-01-15 14:22:26 -0800898 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700899 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700900 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700901 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800902 }
Svetoslav683914b2015-01-15 14:22:26 -0800903 }
904
Svetoslav Ganove080da92016-12-21 17:10:35 -0800905 private boolean updateGlobalSetting(String name, String value, String tag,
906 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800907 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800908 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
909 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
910 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800911 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800912 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
913 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800914 }
915
Svetoslav Ganove080da92016-12-21 17:10:35 -0800916 private boolean insertGlobalSetting(String name, String value, String tag,
917 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700918 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800919 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
920 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
921 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700922 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800923 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
924 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700925 }
926
Svet Ganov53a441c2016-04-19 19:38:00 -0700927 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800928 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
930 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800931 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800932 return mutateGlobalSetting(name, null, null, false, requestingUserId,
933 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800934 }
935
Svetoslav Ganove080da92016-12-21 17:10:35 -0800936 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
937 if (DEBUG) {
938 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
939 + mode + ", " + tag + ")");
940 }
941 mutateGlobalSetting(null, null, tag, false, requestingUserId,
942 MUTATION_OPERATION_RESET, false, mode);
943 }
944
945 private boolean mutateGlobalSetting(String name, String value, String tag,
946 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
947 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800948 // Make sure the caller can change the settings - treated as secure.
949 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
950
Svetoslav683914b2015-01-15 14:22:26 -0800951 // Resolve the userId on whose behalf the call is made.
952 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
953
Makoto Onuki28da2e32015-11-20 11:30:44 -0800954 // If this is a setting that is currently restricted for this user, do not allow
955 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800956 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100957 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800958 return false;
959 }
960
961 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700962 synchronized (mLock) {
963 switch (operation) {
964 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800965 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
966 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800967 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700968 }
Svetoslav683914b2015-01-15 14:22:26 -0800969
Svetoslav7ec28e82015-05-20 17:01:10 -0700970 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700971 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800972 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700973 }
Svetoslav683914b2015-01-15 14:22:26 -0800974
Svetoslav7ec28e82015-05-20 17:01:10 -0700975 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800976 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
977 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800978 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700979 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800980
981 case MUTATION_OPERATION_RESET: {
982 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
983 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
984 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800985 }
986 }
987
988 return false;
989 }
990
Svetoslav7ec28e82015-05-20 17:01:10 -0700991 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800992 if (DEBUG) {
993 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
994 }
995
996 // Resolve the userId on whose behalf the call is made.
997 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
998
Svetoslav7ec28e82015-05-20 17:01:10 -0700999 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001000 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001001
Svetoslav7ec28e82015-05-20 17:01:10 -07001002 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001003
Svetoslav7ec28e82015-05-20 17:01:10 -07001004 String[] normalizedProjection = normalizeProjection(projection);
1005 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001006
Svetoslav7ec28e82015-05-20 17:01:10 -07001007 for (int i = 0; i < nameCount; i++) {
1008 String name = names.get(i);
1009 // Determine the owning user as some profile settings are cloned from the parent.
1010 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1011 name);
Svetoslav683914b2015-01-15 14:22:26 -08001012
Alex Klyubin1991f572017-03-03 14:08:36 -08001013 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1014 // This caller is not permitted to access this setting. Pretend the setting
1015 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001016 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001017 }
Svetoslav683914b2015-01-15 14:22:26 -08001018
Mark Rathjen7599f132017-01-23 14:15:54 -08001019 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001020 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1021 final Setting setting;
1022 if (isNewSsaidSetting(name)) {
1023 setting = getSsaidSettingLocked(owningUserId);
1024 } else {
1025 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1026 name);
1027 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001028 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001029 }
1030
Svetoslav7ec28e82015-05-20 17:01:10 -07001031 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001032 }
Svetoslav683914b2015-01-15 14:22:26 -08001033 }
1034
Svetoslav7ec28e82015-05-20 17:01:10 -07001035 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001036 if (DEBUG) {
1037 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1038 }
1039
1040 // Resolve the userId on whose behalf the call is made.
1041 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1042
Chad Brubaker97bccee2017-01-05 15:51:41 -08001043 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001044 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001045
Svetoslav683914b2015-01-15 14:22:26 -08001046 // Determine the owning user as some profile settings are cloned from the parent.
1047 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1048
Alex Klyubin1991f572017-03-03 14:08:36 -08001049 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1050 // This caller is not permitted to access this setting. Pretend the setting doesn't
1051 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001052 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1053 owningUserId);
1054 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001055 }
1056
1057 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001058 synchronized (mLock) {
Mark Rathjen7599f132017-01-23 14:15:54 -08001059 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001060 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1061 if (isNewSsaidSetting(name)) {
1062 return getSsaidSettingLocked(owningUserId);
1063 }
1064
Svet Ganov53a441c2016-04-19 19:38:00 -07001065 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001066 owningUserId, name);
1067 }
Svetoslav683914b2015-01-15 14:22:26 -08001068 }
1069
Mark Rathjend891f012017-01-19 04:10:37 +00001070 private boolean isNewSsaidSetting(String name) {
1071 return Settings.Secure.ANDROID_ID.equals(name)
1072 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1073 }
1074
1075 private Setting getSsaidSettingLocked(int owningUserId) {
1076 // Get uid of caller (key) used to store ssaid value
1077 String name = Integer.toString(
1078 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1079
1080 if (DEBUG) {
1081 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1082 }
1083
1084 // Retrieve the ssaid from the table if present.
1085 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1086 name);
1087
1088 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001089 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001090 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1091 }
1092
1093 return ssaid;
1094 }
1095
Svetoslav Ganove080da92016-12-21 17:10:35 -08001096 private boolean insertSecureSetting(String name, String value, String tag,
1097 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001098 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001099 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001100 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1101 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001102 }
1103
Svetoslav Ganove080da92016-12-21 17:10:35 -08001104 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1105 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001106 }
1107
Svet Ganov53a441c2016-04-19 19:38:00 -07001108 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001109 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001110 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1111 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001112 }
1113
Svetoslav Ganove080da92016-12-21 17:10:35 -08001114 return mutateSecureSetting(name, null, null, false, requestingUserId,
1115 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001116 }
1117
Svetoslav Ganove080da92016-12-21 17:10:35 -08001118 private boolean updateSecureSetting(String name, String value, String tag,
1119 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001120 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001121 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001122 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1123 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001124 }
1125
Svetoslav Ganove080da92016-12-21 17:10:35 -08001126 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1127 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001128 }
1129
Svetoslav Ganove080da92016-12-21 17:10:35 -08001130 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1131 if (DEBUG) {
1132 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1133 + mode + ", " + tag + ")");
1134 }
1135
1136 mutateSecureSetting(null, null, tag, false, requestingUserId,
1137 MUTATION_OPERATION_RESET, false, mode);
1138 }
1139
1140 private boolean mutateSecureSetting(String name, String value, String tag,
1141 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1142 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001143 // Make sure the caller can change the settings.
1144 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1145
Svetoslav683914b2015-01-15 14:22:26 -08001146 // Resolve the userId on whose behalf the call is made.
1147 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1148
Makoto Onuki28da2e32015-11-20 11:30:44 -08001149 // If this is a setting that is currently restricted for this user, do not allow
1150 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001151 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001152 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001153 return false;
1154 }
1155
1156 // Determine the owning user as some profile settings are cloned from the parent.
1157 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1158
1159 // Only the owning user can change the setting.
1160 if (owningUserId != callingUserId) {
1161 return false;
1162 }
1163
1164 // Special cases for location providers (sigh).
1165 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001166 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1167 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001168 }
1169
1170 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001171 synchronized (mLock) {
1172 switch (operation) {
1173 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001174 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001175 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001176 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001177 }
Svetoslav683914b2015-01-15 14:22:26 -08001178
Svetoslav7ec28e82015-05-20 17:01:10 -07001179 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001180 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001181 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001182 }
Svetoslav683914b2015-01-15 14:22:26 -08001183
Svetoslav7ec28e82015-05-20 17:01:10 -07001184 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001185 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001186 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001187 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001188 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001189
1190 case MUTATION_OPERATION_RESET: {
1191 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1192 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1193 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001194 }
1195 }
1196
1197 return false;
1198 }
1199
Svetoslav7ec28e82015-05-20 17:01:10 -07001200 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001201 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001202 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001203 }
1204
1205 // Resolve the userId on whose behalf the call is made.
1206 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1207
Svetoslav7ec28e82015-05-20 17:01:10 -07001208 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001209 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001210
Svetoslav7ec28e82015-05-20 17:01:10 -07001211 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001212
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 String[] normalizedProjection = normalizeProjection(projection);
1214 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001215
Svetoslav7ec28e82015-05-20 17:01:10 -07001216 for (int i = 0; i < nameCount; i++) {
1217 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001218
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 // Determine the owning user as some profile settings are cloned from the parent.
1220 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1221 name);
Svetoslav683914b2015-01-15 14:22:26 -08001222
Svetoslav7ec28e82015-05-20 17:01:10 -07001223 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001224 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001225 appendSettingToCursor(result, setting);
1226 }
1227
1228 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001229 }
Svetoslav683914b2015-01-15 14:22:26 -08001230 }
1231
Svetoslav7ec28e82015-05-20 17:01:10 -07001232 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001233 if (DEBUG) {
1234 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1235 }
1236
1237 // Resolve the userId on whose behalf the call is made.
1238 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1239
Chad Brubaker97bccee2017-01-05 15:51:41 -08001240 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001241 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001242
Svetoslav683914b2015-01-15 14:22:26 -08001243 // Determine the owning user as some profile settings are cloned from the parent.
1244 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1245
1246 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001247 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001248 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001249 }
Svetoslav683914b2015-01-15 14:22:26 -08001250 }
1251
Svetoslav7ec28e82015-05-20 17:01:10 -07001252 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001253 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001254 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001255 + requestingUserId + ")");
1256 }
1257
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001259 }
1260
Svetoslav7ec28e82015-05-20 17:01:10 -07001261 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001262 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001263 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001264 }
1265
Svetoslav7ec28e82015-05-20 17:01:10 -07001266 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001267 }
1268
Svetoslav7ec28e82015-05-20 17:01:10 -07001269 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001270 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001271 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001272 + requestingUserId + ")");
1273 }
1274
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001276 }
1277
Svetoslav7ec28e82015-05-20 17:01:10 -07001278 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001279 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001280 if (!hasWriteSecureSettingsPermission()) {
1281 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1282 // operation is allowed for the calling package through appops.
1283 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1284 Binder.getCallingUid(), getCallingPackage(), true)) {
1285 return false;
1286 }
Svetoslav683914b2015-01-15 14:22:26 -08001287 }
1288
Svetoslav683914b2015-01-15 14:22:26 -08001289 // Resolve the userId on whose behalf the call is made.
1290 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1291
Svetoslavd8d25e02015-11-20 13:09:26 -08001292 // Enforce what the calling package can mutate the system settings.
1293 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1294
Svetoslav683914b2015-01-15 14:22:26 -08001295 // Determine the owning user as some profile settings are cloned from the parent.
1296 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1297
1298 // Only the owning user id can change the setting.
1299 if (owningUserId != callingUserId) {
1300 return false;
1301 }
1302
Jeff Sharkey413573a2016-02-22 17:52:45 -07001303 // Invalidate any relevant cache files
1304 String cacheName = null;
1305 if (Settings.System.RINGTONE.equals(name)) {
1306 cacheName = Settings.System.RINGTONE_CACHE;
1307 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1308 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1309 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1310 cacheName = Settings.System.ALARM_ALERT_CACHE;
1311 }
1312 if (cacheName != null) {
1313 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001314 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001315 cacheFile.delete();
1316 }
1317
Svetoslav683914b2015-01-15 14:22:26 -08001318 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 synchronized (mLock) {
1320 switch (operation) {
1321 case MUTATION_OPERATION_INSERT: {
1322 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001323 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001324 owningUserId, name, value, null, false, getCallingPackage(),
1325 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001326 }
1327
1328 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001329 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001330 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001331 }
1332
1333 case MUTATION_OPERATION_UPDATE: {
1334 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001335 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001336 owningUserId, name, value, null, false, getCallingPackage(),
1337 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001338 }
Svetoslav683914b2015-01-15 14:22:26 -08001339 }
1340
Svetoslav7ec28e82015-05-20 17:01:10 -07001341 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001342 }
Svetoslav683914b2015-01-15 14:22:26 -08001343 }
1344
Billy Lau6ad2d662015-07-18 00:26:58 +01001345 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001346 // Write secure settings is a more protected permission. If caller has it we are good.
1347 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1348 == PackageManager.PERMISSION_GRANTED) {
1349 return true;
1350 }
1351
Svetoslavf41334b2015-06-23 12:06:03 -07001352 return false;
1353 }
1354
Svetoslav683914b2015-01-15 14:22:26 -08001355 private void validateSystemSettingValue(String name, String value) {
1356 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1357 if (validator != null && !validator.validate(value)) {
1358 throw new IllegalArgumentException("Invalid value: " + value
1359 + " for setting: " + name);
1360 }
1361 }
1362
Alex Klyubin1991f572017-03-03 14:08:36 -08001363 /**
1364 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1365 */
1366 private boolean isSecureSettingAccessible(String name, int callingUserId,
1367 int owningUserId) {
1368 // Special case for location (sigh).
1369 // This check is not inside the name-based checks below because this method performs checks
1370 // only if the calling user ID is not the same as the owning user ID.
1371 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1372 return false;
1373 }
1374
1375 switch (name) {
1376 case "bluetooth_address":
1377 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1378 // address in this secure setting. Secure settings can normally be read by any app,
1379 // which thus enables them to bypass the recently introduced restrictions on access
1380 // to device identifiers.
1381 // To mitigate this we make this setting available only to callers privileged to see
1382 // this device's MAC addresses, same as through public API
1383 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1384 return getContext().checkCallingOrSelfPermission(
1385 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1386 default:
1387 return true;
1388 }
1389 }
1390
Svetoslav683914b2015-01-15 14:22:26 -08001391 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1392 int owningUserId) {
1393 // Optimization - location providers are restricted only for managed profiles.
1394 if (callingUserId == owningUserId) {
1395 return false;
1396 }
1397 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1398 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1399 new UserHandle(callingUserId))) {
1400 return true;
1401 }
1402 return false;
1403 }
1404
Makoto Onuki28da2e32015-11-20 11:30:44 -08001405 /**
1406 * Checks whether changing a setting to a value is prohibited by the corresponding user
1407 * restriction.
1408 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001409 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1410 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001411 *
1412 * @return true if the change is prohibited, false if the change is allowed.
1413 */
1414 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001415 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001416 String restriction;
1417 switch (setting) {
1418 case Settings.Secure.LOCATION_MODE:
1419 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1420 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1421 // here normally, but we still protect it here from a direct provider write.
1422 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1423 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1424 break;
1425
1426 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1427 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1428 // a provider, which should be allowed even if the user restriction is set.
1429 if (value != null && value.startsWith("-")) return false;
1430 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1431 break;
1432
1433 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1434 if ("0".equals(value)) return false;
1435 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1436 break;
1437
1438 case Settings.Global.ADB_ENABLED:
1439 if ("0".equals(value)) return false;
1440 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1441 break;
1442
1443 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1444 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1445 if ("1".equals(value)) return false;
1446 restriction = UserManager.ENSURE_VERIFY_APPS;
1447 break;
1448
1449 case Settings.Global.PREFERRED_NETWORK_MODE:
1450 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1451 break;
1452
Victor Chang9c7b7062016-07-12 23:47:29 +01001453 case Settings.Secure.ALWAYS_ON_VPN_APP:
1454 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1455 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001456 final int appId = UserHandle.getAppId(callingUid);
1457 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001458 return false;
1459 }
1460 restriction = UserManager.DISALLOW_CONFIG_VPN;
1461 break;
1462
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001463 case Settings.Global.SAFE_BOOT_DISALLOWED:
1464 if ("1".equals(value)) return false;
1465 restriction = UserManager.DISALLOW_SAFE_BOOT;
1466 break;
1467
Makoto Onuki28da2e32015-11-20 11:30:44 -08001468 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001469 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001470 if ("0".equals(value)) return false;
1471 restriction = UserManager.DISALLOW_DATA_ROAMING;
1472 break;
1473 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001474 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001475 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001476
1477 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001478 }
1479
1480 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1481 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1482 }
1483
1484 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001485 final int parentId;
1486 // Resolves dependency if setting has a dependency and the calling user has a parent
1487 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1488 && (parentId = getGroupParentLocked(userId)) != userId) {
1489 // The setting has a dependency and the profile has a parent
1490 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001491 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1492 final long token = Binder.clearCallingIdentity();
1493 try {
1494 Setting settingObj = getSecureSetting(dependency, userId);
1495 if (settingObj != null && settingObj.getValue().equals("1")) {
1496 return parentId;
1497 }
1498 } finally {
1499 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001500 }
1501 }
Svetoslav683914b2015-01-15 14:22:26 -08001502 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1503 }
1504
1505 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1506 final int parentId = getGroupParentLocked(userId);
1507 if (parentId != userId && keys.contains(name)) {
1508 return parentId;
1509 }
1510 return userId;
1511 }
1512
Svetoslavf41334b2015-06-23 12:06:03 -07001513 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001514 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001515 // System/root/shell can mutate whatever secure settings they want.
1516 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001517 final int appId = UserHandle.getAppId(callingUid);
1518 if (appId == android.os.Process.SYSTEM_UID
1519 || appId == Process.SHELL_UID
1520 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001521 return;
1522 }
1523
1524 switch (operation) {
1525 case MUTATION_OPERATION_INSERT:
1526 // Insert updates.
1527 case MUTATION_OPERATION_UPDATE: {
1528 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1529 return;
1530 }
1531
1532 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001533 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001534
1535 // Privileged apps can do whatever they want.
1536 if ((packageInfo.applicationInfo.privateFlags
1537 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1538 return;
1539 }
1540
1541 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1542 packageInfo.applicationInfo.targetSdkVersion, name);
1543 } break;
1544
1545 case MUTATION_OPERATION_DELETE: {
1546 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1547 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1548 throw new IllegalArgumentException("You cannot delete system defined"
1549 + " secure settings.");
1550 }
1551
1552 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001553 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001554
1555 // Privileged apps can do whatever they want.
1556 if ((packageInfo.applicationInfo.privateFlags &
1557 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1558 return;
1559 }
1560
1561 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1562 packageInfo.applicationInfo.targetSdkVersion, name);
1563 } break;
1564 }
1565 }
1566
Todd Kennedybe0b8892017-02-15 14:13:52 -08001567 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001568 switch (settingsType) {
1569 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001570 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001571 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001572 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001573 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001574 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001575 default:
1576 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1577 }
1578 }
1579
1580 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001581 boolean instantApp;
1582 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1583 instantApp = false;
1584 } else {
1585 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1586 instantApp = ai.isInstantApp();
1587 }
1588 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001589 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001590 } else {
1591 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1592 }
1593 }
1594
1595 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1596 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1597 return;
1598 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001599 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001600 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001601 return;
1602 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08001603 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001604 throw new SecurityException("Setting " + settingName + " is not accessible from"
1605 + " ephemeral package " + getCallingPackage());
1606 }
1607 }
1608
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001609 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1610 // We always use the callingUid for this lookup. This means that if hypothetically an
1611 // app was installed in user A with cross user and in user B as an Instant App
1612 // the app in A would be able to see all the settings in user B. However since cross
1613 // user is a system permission and the app must be uninstalled in B and then installed as
1614 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001615 ApplicationInfo ai = null;
1616 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001617 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1618 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001619 } catch (RemoteException ignored) {
1620 }
1621 if (ai == null) {
1622 throw new IllegalStateException("Failed to lookup info for package "
1623 + getCallingPackage());
1624 }
1625 return ai;
1626 }
1627
Xiaohui Chen43765b72015-08-31 10:57:33 -07001628 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001629 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001630 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1631 getCallingPackage(), 0, userId);
1632 if (packageInfo != null) {
1633 return packageInfo;
1634 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001635 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001636 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001637 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001638 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001639 }
1640
1641 private int getGroupParentLocked(int userId) {
1642 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001643 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001644 return userId;
1645 }
1646 // We are in the same process with the user manager and the returned
1647 // user info is a cached instance, so just look up instead of cache.
1648 final long identity = Binder.clearCallingIdentity();
1649 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001650 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001651 UserInfo userInfo = mUserManager.getProfileParent(userId);
1652 return (userInfo != null) ? userInfo.id : userId;
1653 } finally {
1654 Binder.restoreCallingIdentity(identity);
1655 }
1656 }
1657
Svetoslav683914b2015-01-15 14:22:26 -08001658 private void enforceWritePermission(String permission) {
1659 if (getContext().checkCallingOrSelfPermission(permission)
1660 != PackageManager.PERMISSION_GRANTED) {
1661 throw new SecurityException("Permission denial: writing to settings requires:"
1662 + permission);
1663 }
1664 }
1665
1666 /*
1667 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1668 * This setting contains a list of the currently enabled location providers.
1669 * But helper functions in android.providers.Settings can enable or disable
1670 * a single provider by using a "+" or "-" prefix before the provider name.
1671 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001672 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1673 * is set, the said method will only allow values with the "-" prefix.
1674 *
Svetoslav683914b2015-01-15 14:22:26 -08001675 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001676 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001677 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1678 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001679 if (TextUtils.isEmpty(value)) {
1680 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001681 }
1682
Svetoslav683914b2015-01-15 14:22:26 -08001683 final char prefix = value.charAt(0);
1684 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001685 if (forceNotify) {
1686 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1687 mSettingsRegistry.notifyForSettingsChange(key,
1688 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1689 }
Svetoslav683914b2015-01-15 14:22:26 -08001690 return false;
1691 }
1692
1693 // skip prefix
1694 value = value.substring(1);
1695
Svetoslav7ec28e82015-05-20 17:01:10 -07001696 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001697 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001698 if (settingValue == null) {
1699 return false;
1700 }
Svetoslav683914b2015-01-15 14:22:26 -08001701
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001702 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001703
1704 int index = oldProviders.indexOf(value);
1705 int end = index + value.length();
1706
1707 // check for commas to avoid matching on partial string
1708 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1709 index = -1;
1710 }
1711
1712 // check for commas to avoid matching on partial string
1713 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1714 index = -1;
1715 }
1716
1717 String newProviders;
1718
1719 if (prefix == '+' && index < 0) {
1720 // append the provider to the list if not present
1721 if (oldProviders.length() == 0) {
1722 newProviders = value;
1723 } else {
1724 newProviders = oldProviders + ',' + value;
1725 }
1726 } else if (prefix == '-' && index >= 0) {
1727 // remove the provider from the list if present
1728 // remove leading or trailing comma
1729 if (index > 0) {
1730 index--;
1731 } else if (end < oldProviders.length()) {
1732 end++;
1733 }
1734
1735 newProviders = oldProviders.substring(0, index);
1736 if (end < oldProviders.length()) {
1737 newProviders += oldProviders.substring(end);
1738 }
1739 } else {
1740 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001741 if (forceNotify) {
1742 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1743 mSettingsRegistry.notifyForSettingsChange(key,
1744 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1745 }
Svetoslav683914b2015-01-15 14:22:26 -08001746 return false;
1747 }
1748
Svet Ganov53a441c2016-04-19 19:38:00 -07001749 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001750 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001751 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001752 }
1753
Svetoslav683914b2015-01-15 14:22:26 -08001754 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1755 int targetSdkVersion, String name) {
1756 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1757 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1758 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1759 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1760 + " This will soon become an error.");
1761 } else {
1762 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1763 + " This will soon become an error.");
1764 }
1765 } else {
1766 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1767 throw new IllegalArgumentException("You cannot change private secure settings.");
1768 } else {
1769 throw new IllegalArgumentException("You cannot keep your settings in"
1770 + " the secure settings.");
1771 }
1772 }
1773 }
1774
1775 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1776 if (requestingUserId == UserHandle.getCallingUserId()) {
1777 return requestingUserId;
1778 }
1779 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1780 Binder.getCallingUid(), requestingUserId, false, true,
1781 "get/set setting for user", null);
1782 }
1783
Svet Ganov53a441c2016-04-19 19:38:00 -07001784 private Bundle packageValueForCallResult(Setting setting,
1785 boolean trackingGeneration) {
1786 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001787 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001788 return NULL_SETTING_BUNDLE;
1789 }
1790 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001791 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001792 Bundle result = new Bundle();
1793 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001794 !setting.isNull() ? setting.getValue() : null);
1795 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001796 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001797 }
1798
1799 private static int getRequestingUserId(Bundle args) {
1800 final int callingUserId = UserHandle.getCallingUserId();
1801 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1802 : callingUserId;
1803 }
1804
Svet Ganov53a441c2016-04-19 19:38:00 -07001805 private boolean isTrackingGeneration(Bundle args) {
1806 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1807 }
1808
Svetoslav683914b2015-01-15 14:22:26 -08001809 private static String getSettingValue(Bundle args) {
1810 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1811 }
1812
Svetoslav Ganove080da92016-12-21 17:10:35 -08001813 private static String getSettingTag(Bundle args) {
1814 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1815 }
1816
1817 private static boolean getSettingMakeDefault(Bundle args) {
1818 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1819 }
1820
1821 private static int getResetModeEnforcingPermission(Bundle args) {
1822 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1823 switch (mode) {
1824 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1825 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1826 throw new SecurityException("Only system, shell/root on a "
1827 + "debuggable build can reset to untrusted defaults");
1828 }
1829 return mode;
1830 }
1831 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1832 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1833 throw new SecurityException("Only system, shell/root on a "
1834 + "debuggable build can reset untrusted changes");
1835 }
1836 return mode;
1837 }
1838 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1839 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1840 throw new SecurityException("Only system, shell/root on a "
1841 + "debuggable build can reset to trusted defaults");
1842 }
1843 return mode;
1844 }
1845 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1846 return mode;
1847 }
1848 }
1849 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1850 }
1851
1852 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1853 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1854 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1855 && (appId == SHELL_UID || appId == ROOT_UID));
1856 }
1857
Svetoslav683914b2015-01-15 14:22:26 -08001858 private static String getValidTableOrThrow(Uri uri) {
1859 if (uri.getPathSegments().size() > 0) {
1860 String table = uri.getPathSegments().get(0);
1861 if (DatabaseHelper.isValidTable(table)) {
1862 return table;
1863 }
1864 throw new IllegalArgumentException("Bad root path: " + table);
1865 }
1866 throw new IllegalArgumentException("Invalid URI:" + uri);
1867 }
1868
1869 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001870 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001871 return new MatrixCursor(projection, 0);
1872 }
1873 MatrixCursor cursor = new MatrixCursor(projection, 1);
1874 appendSettingToCursor(cursor, setting);
1875 return cursor;
1876 }
1877
1878 private static String[] normalizeProjection(String[] projection) {
1879 if (projection == null) {
1880 return ALL_COLUMNS;
1881 }
1882
1883 final int columnCount = projection.length;
1884 for (int i = 0; i < columnCount; i++) {
1885 String column = projection[i];
1886 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1887 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001888 }
1889 }
1890
Svetoslav683914b2015-01-15 14:22:26 -08001891 return projection;
1892 }
1893
1894 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001895 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001896 return;
1897 }
Svetoslav683914b2015-01-15 14:22:26 -08001898 final int columnCount = cursor.getColumnCount();
1899
1900 String[] values = new String[columnCount];
1901
1902 for (int i = 0; i < columnCount; i++) {
1903 String column = cursor.getColumnName(i);
1904
1905 switch (column) {
1906 case Settings.NameValueTable._ID: {
1907 values[i] = setting.getId();
1908 } break;
1909
1910 case Settings.NameValueTable.NAME: {
1911 values[i] = setting.getName();
1912 } break;
1913
1914 case Settings.NameValueTable.VALUE: {
1915 values[i] = setting.getValue();
1916 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001917 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001918 }
1919
Svetoslav683914b2015-01-15 14:22:26 -08001920 cursor.addRow(values);
1921 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001922
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001923 private static boolean isKeyValid(String key) {
1924 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1925 }
1926
Svetoslav683914b2015-01-15 14:22:26 -08001927 private static final class Arguments {
1928 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1929 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1930
1931 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1932 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1933
1934 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1935 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1936
1937 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1938 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1939
1940 public final String table;
1941 public final String name;
1942
1943 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1944 final int segmentSize = uri.getPathSegments().size();
1945 switch (segmentSize) {
1946 case 1: {
1947 if (where != null
1948 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1949 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1950 && whereArgs.length == 1) {
1951 name = whereArgs[0];
1952 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001953 return;
Svetoslav683914b2015-01-15 14:22:26 -08001954 } else if (where != null
1955 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1956 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1957 final int startIndex = Math.max(where.indexOf("'"),
1958 where.indexOf("\"")) + 1;
1959 final int endIndex = Math.max(where.lastIndexOf("'"),
1960 where.lastIndexOf("\""));
1961 name = where.substring(startIndex, endIndex);
1962 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001963 return;
Svetoslav683914b2015-01-15 14:22:26 -08001964 } else if (supportAll && where == null && whereArgs == null) {
1965 name = null;
1966 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001967 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001968 }
Svetoslav683914b2015-01-15 14:22:26 -08001969 } break;
1970
Svetoslav28494652015-02-12 14:11:42 -08001971 case 2: {
1972 if (where == null && whereArgs == null) {
1973 name = uri.getPathSegments().get(1);
1974 table = computeTableForSetting(uri, name);
1975 return;
1976 }
1977 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001978 }
Svetoslav28494652015-02-12 14:11:42 -08001979
1980 EventLogTags.writeUnsupportedSettingsQuery(
1981 uri.toSafeString(), where, Arrays.toString(whereArgs));
1982 String message = String.format( "Supported SQL:\n"
1983 + " uri content://some_table/some_property with null where and where args\n"
1984 + " uri content://some_table with query name=? and single name as arg\n"
1985 + " uri content://some_table with query name=some_name and null args\n"
1986 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1987 Arrays.toString(whereArgs));
1988 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001989 }
1990
Svetoslav28494652015-02-12 14:11:42 -08001991 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001992 String table = getValidTableOrThrow(uri);
1993
1994 if (name != null) {
1995 if (sSystemMovedToSecureSettings.contains(name)) {
1996 table = TABLE_SECURE;
1997 }
1998
1999 if (sSystemMovedToGlobalSettings.contains(name)) {
2000 table = TABLE_GLOBAL;
2001 }
2002
2003 if (sSecureMovedToGlobalSettings.contains(name)) {
2004 table = TABLE_GLOBAL;
2005 }
2006
2007 if (sGlobalMovedToSecureSettings.contains(name)) {
2008 table = TABLE_SECURE;
2009 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002010 }
Svetoslav683914b2015-01-15 14:22:26 -08002011
2012 return table;
2013 }
2014 }
2015
2016 final class SettingsRegistry {
2017 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2018
Svetoslav683914b2015-01-15 14:22:26 -08002019 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2020 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2021 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002022 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2023
2024 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002025
2026 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2027
Svet Ganov53a441c2016-04-19 19:38:00 -07002028 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002029
Svetoslav7e0683b2015-08-03 16:02:52 -07002030 private final Handler mHandler;
2031
Svet Ganov53a441c2016-04-19 19:38:00 -07002032 private final BackupManager mBackupManager;
2033
Svetoslav683914b2015-01-15 14:22:26 -08002034 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002035 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002036 mGenerationRegistry = new GenerationRegistry(mLock);
2037 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002038 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002039 syncSsaidTableOnStart();
2040 }
2041
2042 private void generateUserKeyLocked(int userId) {
2043 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002044 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002045 final SecureRandom rand = new SecureRandom();
2046 rand.nextBytes(keyBytes);
2047
2048 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002049 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002050
2051 // Store the key in the ssaid table.
2052 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2053 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2054 true, SettingsState.SYSTEM_PACKAGE_NAME);
2055
2056 if (!success) {
2057 throw new IllegalStateException("Ssaid settings not accessible");
2058 }
2059 }
2060
Mark Rathjen7599f132017-01-23 14:15:54 -08002061 private byte[] getLengthPrefix(byte[] data) {
2062 return ByteBuffer.allocate(4).putInt(data.length).array();
2063 }
2064
Mark Rathjend891f012017-01-19 04:10:37 +00002065 public Setting generateSsaidLocked(String packageName, int userId) {
2066 final PackageInfo packageInfo;
2067 try {
2068 packageInfo = mPackageManager.getPackageInfo(packageName,
2069 PackageManager.GET_SIGNATURES, userId);
2070 } catch (RemoteException e) {
2071 throw new IllegalStateException("Package info doesn't exist");
2072 }
2073
2074 // Read the user's key from the ssaid table.
2075 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002076 if (userKeySetting == null || userKeySetting.isNull()
2077 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002078 // Lazy initialize and store the user key.
2079 generateUserKeyLocked(userId);
2080 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002081 if (userKeySetting == null || userKeySetting.isNull()
2082 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002083 throw new IllegalStateException("User key not accessible");
2084 }
2085 }
2086 final String userKey = userKeySetting.getValue();
2087
2088 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002089 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2090
2091 // Validate that the key is of expected length.
2092 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2093 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002094 throw new IllegalStateException("User key invalid");
2095 }
2096
Mark Rathjen7599f132017-01-23 14:15:54 -08002097 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002098 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002099 m = Mac.getInstance("HmacSHA256");
2100 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002101 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002102 throw new IllegalStateException("HmacSHA256 is not available", e);
2103 } catch (InvalidKeyException e) {
2104 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002105 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002106
2107 // Mac the package name and each of the signatures.
2108 byte[] packageNameBytes = packageInfo.packageName.getBytes(StandardCharsets.UTF_8);
2109 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2110 m.update(packageNameBytes);
2111 for (int i = 0; i < packageInfo.signatures.length; i++) {
2112 byte[] sig = packageInfo.signatures[i].toByteArray();
2113 m.update(getLengthPrefix(sig), 0, 4);
2114 m.update(sig);
2115 }
Mark Rathjend891f012017-01-19 04:10:37 +00002116
2117 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002118 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2119 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002120
2121 // Save the ssaid in the ssaid table.
2122 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2123 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2124 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2125 packageName);
2126
2127 if (!success) {
2128 throw new IllegalStateException("Ssaid settings not accessible");
2129 }
2130
2131 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2132 }
2133
2134 public void syncSsaidTableOnStart() {
2135 synchronized (mLock) {
2136 // Verify that each user's packages and ssaid's are in sync.
2137 for (UserInfo user : mUserManager.getUsers(true)) {
2138 // Get all uids for the user's packages.
2139 final List<PackageInfo> packages;
2140 try {
2141 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2142 } catch (RemoteException e) {
2143 throw new IllegalStateException("Package manager not available");
2144 }
2145 final Set<String> appUids = new HashSet<>();
2146 for (PackageInfo info : packages) {
2147 appUids.add(Integer.toString(info.applicationInfo.uid));
2148 }
2149
2150 // Get all uids currently stored in the user's ssaid table.
2151 final Set<String> ssaidUids = new HashSet<>(
2152 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2153 ssaidUids.remove(SSAID_USER_KEY);
2154
2155 // Perform a set difference for the appUids and ssaidUids.
2156 ssaidUids.removeAll(appUids);
2157
2158 // If there are ssaidUids left over they need to be removed from the table.
2159 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2160 user.id);
2161 for (String uid : ssaidUids) {
2162 ssaidSettings.deleteSettingLocked(uid);
2163 }
2164 }
2165 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002166 }
2167
Svetoslav683914b2015-01-15 14:22:26 -08002168 public List<String> getSettingsNamesLocked(int type, int userId) {
2169 final int key = makeKey(type, userId);
2170 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002171 if (settingsState == null) {
2172 return new ArrayList<String>();
2173 }
Svetoslav683914b2015-01-15 14:22:26 -08002174 return settingsState.getSettingNamesLocked();
2175 }
2176
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002177 public SparseBooleanArray getKnownUsersLocked() {
2178 SparseBooleanArray users = new SparseBooleanArray();
2179 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2180 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2181 }
2182 return users;
2183 }
2184
Svetoslav683914b2015-01-15 14:22:26 -08002185 public SettingsState getSettingsLocked(int type, int userId) {
2186 final int key = makeKey(type, userId);
2187 return peekSettingsStateLocked(key);
2188 }
2189
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002190 public boolean ensureSettingsForUserLocked(int userId) {
2191 // First make sure this user actually exists.
2192 if (mUserManager.getUserInfo(userId) == null) {
2193 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2194 return false;
2195 }
2196
Svetoslav683914b2015-01-15 14:22:26 -08002197 // Migrate the setting for this user if needed.
2198 migrateLegacySettingsForUserIfNeededLocked(userId);
2199
2200 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002201 if (userId == UserHandle.USER_SYSTEM) {
2202 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002203 ensureSettingsStateLocked(globalKey);
2204 }
2205
2206 // Ensure secure settings loaded.
2207 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2208 ensureSettingsStateLocked(secureKey);
2209
2210 // Make sure the secure settings have an Android id set.
2211 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2212 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2213
2214 // Ensure system settings loaded.
2215 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2216 ensureSettingsStateLocked(systemKey);
2217
Mark Rathjend891f012017-01-19 04:10:37 +00002218 // Ensure secure settings loaded.
2219 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2220 ensureSettingsStateLocked(ssaidKey);
2221
Svetoslav683914b2015-01-15 14:22:26 -08002222 // Upgrade the settings to the latest version.
2223 UpgradeController upgrader = new UpgradeController(userId);
2224 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002225 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002226 }
2227
2228 private void ensureSettingsStateLocked(int key) {
2229 if (mSettingsStates.get(key) == null) {
2230 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002231 SettingsState settingsState = new SettingsState(getContext(), mLock,
2232 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002233 mSettingsStates.put(key, settingsState);
2234 }
2235 }
2236
2237 public void removeUserStateLocked(int userId, boolean permanently) {
2238 // We always keep the global settings in memory.
2239
2240 // Nuke system settings.
2241 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2242 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2243 if (systemSettingsState != null) {
2244 if (permanently) {
2245 mSettingsStates.remove(systemKey);
2246 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002247 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002248 systemSettingsState.destroyLocked(new Runnable() {
2249 @Override
2250 public void run() {
2251 mSettingsStates.remove(systemKey);
2252 }
2253 });
2254 }
2255 }
2256
2257 // Nuke secure settings.
2258 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2259 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2260 if (secureSettingsState != null) {
2261 if (permanently) {
2262 mSettingsStates.remove(secureKey);
2263 secureSettingsState.destroyLocked(null);
2264 } else {
2265 secureSettingsState.destroyLocked(new Runnable() {
2266 @Override
2267 public void run() {
2268 mSettingsStates.remove(secureKey);
2269 }
2270 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002271 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002272 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002273
Mark Rathjend891f012017-01-19 04:10:37 +00002274 // Nuke ssaid settings.
2275 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2276 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2277 if (ssaidSettingsState != null) {
2278 if (permanently) {
2279 mSettingsStates.remove(ssaidKey);
2280 ssaidSettingsState.destroyLocked(null);
2281 } else {
2282 ssaidSettingsState.destroyLocked(new Runnable() {
2283 @Override
2284 public void run() {
2285 mSettingsStates.remove(ssaidKey);
2286 }
2287 });
2288 }
2289 }
2290
Svet Ganov53a441c2016-04-19 19:38:00 -07002291 // Nuke generation tracking data
2292 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002293 }
2294
Svetoslav683914b2015-01-15 14:22:26 -08002295 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002296 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2297 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002298 final int key = makeKey(type, userId);
2299
Svetoslav Ganove080da92016-12-21 17:10:35 -08002300 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002301 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002302 if (settingsState != null) {
2303 success = settingsState.insertSettingLocked(name, value,
2304 tag, makeDefault, packageName);
2305 }
Svetoslav683914b2015-01-15 14:22:26 -08002306
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002307 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2308 settingsState.persistSyncLocked();
2309 }
2310
Svet Ganov53a441c2016-04-19 19:38:00 -07002311 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002312 notifyForSettingsChange(key, name);
2313 }
2314 return success;
2315 }
2316
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002317 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2318 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002319 final int key = makeKey(type, userId);
2320
Svetoslav Ganove080da92016-12-21 17:10:35 -08002321 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002322 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002323 if (settingsState != null) {
2324 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002325 }
Svetoslav683914b2015-01-15 14:22:26 -08002326
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002327 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2328 settingsState.persistSyncLocked();
2329 }
2330
Svet Ganov53a441c2016-04-19 19:38:00 -07002331 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002332 notifyForSettingsChange(key, name);
2333 }
2334 return success;
2335 }
2336
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002337 public boolean updateSettingLocked(int type, int userId, String name, String value,
2338 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2339 Set<String> criticalSettings) {
2340 final int key = makeKey(type, userId);
2341
2342 boolean success = false;
2343 SettingsState settingsState = peekSettingsStateLocked(key);
2344 if (settingsState != null) {
2345 success = settingsState.updateSettingLocked(name, value, tag,
2346 makeDefault, packageName);
2347 }
2348
2349 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2350 settingsState.persistSyncLocked();
2351 }
2352
2353 if (forceNotify || success) {
2354 notifyForSettingsChange(key, name);
2355 }
2356
2357 return success;
2358 }
2359
Svetoslav683914b2015-01-15 14:22:26 -08002360 public Setting getSettingLocked(int type, int userId, String name) {
2361 final int key = makeKey(type, userId);
2362
2363 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002364 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002365 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002366 }
Mark Rathjend891f012017-01-19 04:10:37 +00002367
2368 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002369 return settingsState.getSettingLocked(name);
2370 }
2371
Svetoslav Ganove080da92016-12-21 17:10:35 -08002372 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2373 String tag) {
2374 final int key = makeKey(type, userId);
2375 SettingsState settingsState = peekSettingsStateLocked(key);
2376 if (settingsState == null) {
2377 return;
2378 }
2379
2380 switch (mode) {
2381 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2382 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002383 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002384 Setting setting = settingsState.getSettingLocked(name);
2385 if (packageName.equals(setting.getPackageName())) {
2386 if (tag != null && !tag.equals(setting.getTag())) {
2387 continue;
2388 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002389 if (settingsState.resetSettingLocked(name)) {
2390 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002391 notifyForSettingsChange(key, name);
2392 }
2393 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002394 if (someSettingChanged) {
2395 settingsState.persistSyncLocked();
2396 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002397 }
2398 } break;
2399
2400 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2401 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002402 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002403 Setting setting = settingsState.getSettingLocked(name);
2404 if (!SettingsState.isSystemPackage(getContext(),
2405 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002406 if (settingsState.resetSettingLocked(name)) {
2407 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002408 notifyForSettingsChange(key, name);
2409 }
2410 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002411 if (someSettingChanged) {
2412 settingsState.persistSyncLocked();
2413 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002414 }
2415 } break;
2416
2417 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2418 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002419 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002420 Setting setting = settingsState.getSettingLocked(name);
2421 if (!SettingsState.isSystemPackage(getContext(),
2422 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002423 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002424 if (settingsState.resetSettingLocked(name)) {
2425 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002426 notifyForSettingsChange(key, name);
2427 }
2428 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002429 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002430 notifyForSettingsChange(key, name);
2431 }
2432 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002433 if (someSettingChanged) {
2434 settingsState.persistSyncLocked();
2435 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002436 }
2437 } break;
2438
2439 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2440 for (String name : settingsState.getSettingNamesLocked()) {
2441 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002442 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002443 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002444 if (settingsState.resetSettingLocked(name)) {
2445 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002446 notifyForSettingsChange(key, name);
2447 }
2448 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002449 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002450 notifyForSettingsChange(key, name);
2451 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002452 if (someSettingChanged) {
2453 settingsState.persistSyncLocked();
2454 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002455 }
2456 } break;
2457 }
2458 }
2459
Svetoslav683914b2015-01-15 14:22:26 -08002460 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002461 // Global and secure settings are signature protected. Apps signed
2462 // by the platform certificate are generally not uninstalled and
2463 // the main exception is tests. We trust components signed
2464 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002465
2466 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2467 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002468 if (systemSettings != null) {
2469 systemSettings.onPackageRemovedLocked(packageName);
2470 }
Svetoslav683914b2015-01-15 14:22:26 -08002471 }
2472
Mark Rathjend891f012017-01-19 04:10:37 +00002473 public void onUidRemovedLocked(int uid) {
2474 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2475 UserHandle.getUserId(uid));
2476 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2477 }
2478
Svetoslav683914b2015-01-15 14:22:26 -08002479 private SettingsState peekSettingsStateLocked(int key) {
2480 SettingsState settingsState = mSettingsStates.get(key);
2481 if (settingsState != null) {
2482 return settingsState;
2483 }
2484
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002485 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2486 return null;
2487 }
Svetoslav683914b2015-01-15 14:22:26 -08002488 return mSettingsStates.get(key);
2489 }
2490
2491 private void migrateAllLegacySettingsIfNeeded() {
2492 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002493 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002494 File globalFile = getSettingsFile(key);
2495 if (globalFile.exists()) {
2496 return;
2497 }
2498
2499 final long identity = Binder.clearCallingIdentity();
2500 try {
2501 List<UserInfo> users = mUserManager.getUsers(true);
2502
2503 final int userCount = users.size();
2504 for (int i = 0; i < userCount; i++) {
2505 final int userId = users.get(i).id;
2506
2507 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2508 SQLiteDatabase database = dbHelper.getWritableDatabase();
2509 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2510
2511 // Upgrade to the latest version.
2512 UpgradeController upgrader = new UpgradeController(userId);
2513 upgrader.upgradeIfNeededLocked();
2514
2515 // Drop from memory if not a running user.
2516 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2517 removeUserStateLocked(userId, false);
2518 }
2519 }
2520 } finally {
2521 Binder.restoreCallingIdentity(identity);
2522 }
2523 }
2524 }
2525
2526 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2527 // Every user has secure settings and if no file we need to migrate.
2528 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2529 File secureFile = getSettingsFile(secureKey);
2530 if (secureFile.exists()) {
2531 return;
2532 }
2533
2534 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2535 SQLiteDatabase database = dbHelper.getWritableDatabase();
2536
2537 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2538 }
2539
2540 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2541 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002542 // Move over the system settings.
2543 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2544 ensureSettingsStateLocked(systemKey);
2545 SettingsState systemSettings = mSettingsStates.get(systemKey);
2546 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2547 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002548
2549 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002550 // Do this after System settings, since this is the first thing we check when deciding
2551 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002552 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2553 ensureSettingsStateLocked(secureKey);
2554 SettingsState secureSettings = mSettingsStates.get(secureKey);
2555 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2556 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2557 secureSettings.persistSyncLocked();
2558
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002559 // Move over the global settings if owner.
2560 // Do this last, since this is the first thing we check when deciding
2561 // to skip over migration from db to xml for owner user.
2562 if (userId == UserHandle.USER_SYSTEM) {
2563 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2564 ensureSettingsStateLocked(globalKey);
2565 SettingsState globalSettings = mSettingsStates.get(globalKey);
2566 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2567 globalSettings.persistSyncLocked();
2568 }
Svetoslav683914b2015-01-15 14:22:26 -08002569
2570 // Drop the database as now all is moved and persisted.
2571 if (DROP_DATABASE_ON_MIGRATION) {
2572 dbHelper.dropDatabase();
2573 } else {
2574 dbHelper.backupDatabase();
2575 }
2576 }
2577
2578 private void migrateLegacySettingsLocked(SettingsState settingsState,
2579 SQLiteDatabase database, String table) {
2580 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2581 queryBuilder.setTables(table);
2582
2583 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2584 null, null, null, null, null);
2585
2586 if (cursor == null) {
2587 return;
2588 }
2589
2590 try {
2591 if (!cursor.moveToFirst()) {
2592 return;
2593 }
2594
2595 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2596 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2597
2598 settingsState.setVersionLocked(database.getVersion());
2599
2600 while (!cursor.isAfterLast()) {
2601 String name = cursor.getString(nameColumnIdx);
2602 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002603 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002604 SettingsState.SYSTEM_PACKAGE_NAME);
2605 cursor.moveToNext();
2606 }
2607 } finally {
2608 cursor.close();
2609 }
2610 }
2611
2612 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2613 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2614
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002615 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002616 return;
2617 }
2618
2619 final int userId = getUserIdFromKey(secureSettings.mKey);
2620
2621 final UserInfo user;
2622 final long identity = Binder.clearCallingIdentity();
2623 try {
2624 user = mUserManager.getUserInfo(userId);
2625 } finally {
2626 Binder.restoreCallingIdentity(identity);
2627 }
2628 if (user == null) {
2629 // Can happen due to races when deleting users - treat as benign.
2630 return;
2631 }
2632
2633 String androidId = Long.toHexString(new SecureRandom().nextLong());
2634 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002635 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002636
2637 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2638 + "] for user " + userId);
2639
2640 // Write a drop box entry if it's a restricted profile
2641 if (user.isRestricted()) {
2642 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2643 Context.DROPBOX_SERVICE);
2644 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2645 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2646 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2647 }
2648 }
2649 }
2650
2651 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002652 final int userId = getUserIdFromKey(key);
2653 Uri uri = getNotificationUriFor(key, name);
2654
Phil Weaver83fec002016-05-11 10:55:29 -07002655 mGenerationRegistry.incrementGeneration(key);
2656
Svetoslav7e0683b2015-08-03 16:02:52 -07002657 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2658 userId, 0, uri).sendToTarget();
2659
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002660 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002661 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2662 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002663 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2664 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002665 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002666 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2667 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002668 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002669
Svet Ganov53a441c2016-04-19 19:38:00 -07002670 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002671 }
2672
Svet Ganov53a441c2016-04-19 19:38:00 -07002673 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002674 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002675 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002676 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002677 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002678 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002679 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002680 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002681 final int key = makeKey(type, profileId);
2682 mGenerationRegistry.incrementGeneration(key);
2683
2684 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002685 }
2686 }
2687 }
Svetoslav683914b2015-01-15 14:22:26 -08002688 }
2689
Svetoslav683914b2015-01-15 14:22:26 -08002690 private boolean isGlobalSettingsKey(int key) {
2691 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2692 }
2693
2694 private boolean isSystemSettingsKey(int key) {
2695 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2696 }
2697
2698 private boolean isSecureSettingsKey(int key) {
2699 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2700 }
2701
Mark Rathjend891f012017-01-19 04:10:37 +00002702 private boolean isSsaidSettingsKey(int key) {
2703 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2704 }
2705
Svetoslav683914b2015-01-15 14:22:26 -08002706 private File getSettingsFile(int key) {
2707 if (isGlobalSettingsKey(key)) {
2708 final int userId = getUserIdFromKey(key);
2709 return new File(Environment.getUserSystemDirectory(userId),
2710 SETTINGS_FILE_GLOBAL);
2711 } else if (isSystemSettingsKey(key)) {
2712 final int userId = getUserIdFromKey(key);
2713 return new File(Environment.getUserSystemDirectory(userId),
2714 SETTINGS_FILE_SYSTEM);
2715 } else if (isSecureSettingsKey(key)) {
2716 final int userId = getUserIdFromKey(key);
2717 return new File(Environment.getUserSystemDirectory(userId),
2718 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002719 } else if (isSsaidSettingsKey(key)) {
2720 final int userId = getUserIdFromKey(key);
2721 return new File(Environment.getUserSystemDirectory(userId),
2722 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002723 } else {
2724 throw new IllegalArgumentException("Invalid settings key:" + key);
2725 }
2726 }
2727
2728 private Uri getNotificationUriFor(int key, String name) {
2729 if (isGlobalSettingsKey(key)) {
2730 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2731 : Settings.Global.CONTENT_URI;
2732 } else if (isSecureSettingsKey(key)) {
2733 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2734 : Settings.Secure.CONTENT_URI;
2735 } else if (isSystemSettingsKey(key)) {
2736 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2737 : Settings.System.CONTENT_URI;
2738 } else {
2739 throw new IllegalArgumentException("Invalid settings key:" + key);
2740 }
2741 }
2742
2743 private int getMaxBytesPerPackageForType(int type) {
2744 switch (type) {
2745 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002746 case SETTINGS_TYPE_SECURE:
2747 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002748 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2749 }
2750
2751 default: {
2752 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2753 }
2754 }
2755 }
2756
Svetoslav7e0683b2015-08-03 16:02:52 -07002757 private final class MyHandler extends Handler {
2758 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2759 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2760
2761 public MyHandler(Looper looper) {
2762 super(looper);
2763 }
2764
2765 @Override
2766 public void handleMessage(Message msg) {
2767 switch (msg.what) {
2768 case MSG_NOTIFY_URI_CHANGED: {
2769 final int userId = msg.arg1;
2770 Uri uri = (Uri) msg.obj;
2771 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2772 if (DEBUG) {
2773 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2774 }
2775 } break;
2776
2777 case MSG_NOTIFY_DATA_CHANGED: {
2778 mBackupManager.dataChanged();
2779 } break;
2780 }
2781 }
2782 }
2783
Svetoslav683914b2015-01-15 14:22:26 -08002784 private final class UpgradeController {
Svet Ganov13701552017-02-23 12:45:17 -08002785 private static final int SETTINGS_VERSION = 142;
Svetoslav683914b2015-01-15 14:22:26 -08002786
2787 private final int mUserId;
2788
2789 public UpgradeController(int userId) {
2790 mUserId = userId;
2791 }
2792
2793 public void upgradeIfNeededLocked() {
2794 // The version of all settings for a user is the same (all users have secure).
2795 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002796 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002797
2798 // Try an update from the current state.
2799 final int oldVersion = secureSettings.getVersionLocked();
2800 final int newVersion = SETTINGS_VERSION;
2801
Svet Ganovc9755bc2015-03-28 13:21:22 -07002802 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002803 if (oldVersion == newVersion) {
2804 return;
2805 }
2806
2807 // Try to upgrade.
2808 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2809
2810 // If upgrade failed start from scratch and upgrade.
2811 if (curVersion != newVersion) {
2812 // Drop state we have for this user.
2813 removeUserStateLocked(mUserId, true);
2814
2815 // Recreate the database.
2816 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2817 SQLiteDatabase database = dbHelper.getWritableDatabase();
2818 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2819
2820 // Migrate the settings for this user.
2821 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2822
2823 // Now upgrade should work fine.
2824 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002825
2826 // Make a note what happened, so we don't wonder why data was lost
2827 String reason = "Settings rebuilt! Current version: "
2828 + curVersion + " while expected: " + newVersion;
2829 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002830 Settings.Global.DATABASE_DOWNGRADE_REASON,
2831 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002832 }
2833
2834 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002835 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002836 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002837 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002838 globalSettings.setVersionLocked(newVersion);
2839 }
2840
2841 // Set the secure settings version.
2842 secureSettings.setVersionLocked(newVersion);
2843
2844 // Set the system settings version.
2845 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002846 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002847 systemSettings.setVersionLocked(newVersion);
2848 }
2849
2850 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002851 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002852 }
2853
2854 private SettingsState getSecureSettingsLocked(int userId) {
2855 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2856 }
2857
Mark Rathjend891f012017-01-19 04:10:37 +00002858 private SettingsState getSsaidSettingsLocked(int userId) {
2859 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2860 }
2861
Svetoslav683914b2015-01-15 14:22:26 -08002862 private SettingsState getSystemSettingsLocked(int userId) {
2863 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2864 }
2865
Jeff Brown503cffc2015-03-26 18:08:51 -07002866 /**
2867 * You must perform all necessary mutations to bring the settings
2868 * for this user from the old to the new version. When you add a new
2869 * upgrade step you *must* update SETTINGS_VERSION.
2870 *
2871 * This is an example of moving a setting from secure to global.
2872 *
2873 * // v119: Example settings changes.
2874 * if (currentVersion == 118) {
2875 * if (userId == UserHandle.USER_OWNER) {
2876 * // Remove from the secure settings.
2877 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2878 * String name = "example_setting_to_move";
2879 * String value = secureSettings.getSetting(name);
2880 * secureSettings.deleteSetting(name);
2881 *
2882 * // Add to the global settings.
2883 * SettingsState globalSettings = getGlobalSettingsLocked();
2884 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2885 * }
2886 *
2887 * // Update the current version.
2888 * currentVersion = 119;
2889 * }
2890 */
Svetoslav683914b2015-01-15 14:22:26 -08002891 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2892 if (DEBUG) {
2893 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2894 + oldVersion + " to version: " + newVersion);
2895 }
2896
Jeff Brown503cffc2015-03-26 18:08:51 -07002897 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002898
John Spurlocke11ae112015-05-11 16:09:03 -04002899 // v119: Reset zen + ringer mode.
2900 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002901 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002902 final SettingsState globalSettings = getGlobalSettingsLocked();
2903 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002904 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2905 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002906 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002907 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2908 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002909 }
2910 currentVersion = 119;
2911 }
2912
Jason Monk27bbb2d2015-03-31 16:46:39 -04002913 // v120: Add double tap to wake setting.
2914 if (currentVersion == 119) {
2915 SettingsState secureSettings = getSecureSettingsLocked(userId);
2916 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2917 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002918 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002919 SettingsState.SYSTEM_PACKAGE_NAME);
2920
2921 currentVersion = 120;
2922 }
2923
Svetoslav7e0683b2015-08-03 16:02:52 -07002924 if (currentVersion == 120) {
2925 // Before 121, we used a different string encoding logic. We just bump the
2926 // version here; SettingsState knows how to handle pre-version 120 files.
2927 currentVersion = 121;
2928 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002929
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002930 if (currentVersion == 121) {
2931 // Version 122: allow OEMs to set a default payment component in resources.
2932 // Note that we only write the default if no default has been set;
2933 // if there is, we just leave the default at whatever it currently is.
2934 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2935 String defaultComponent = (getContext().getResources().getString(
2936 R.string.def_nfc_payment_component));
2937 Setting currentSetting = secureSettings.getSettingLocked(
2938 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2939 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002940 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002941 secureSettings.insertSettingLocked(
2942 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002943 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002944 }
2945 currentVersion = 122;
2946 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002947
2948 if (currentVersion == 122) {
2949 // Version 123: Adding a default value for the ability to add a user from
2950 // the lock screen.
2951 if (userId == UserHandle.USER_SYSTEM) {
2952 final SettingsState globalSettings = getGlobalSettingsLocked();
2953 Setting currentSetting = globalSettings.getSettingLocked(
2954 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002955 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002956 globalSettings.insertSettingLocked(
2957 Settings.Global.ADD_USERS_WHEN_LOCKED,
2958 getContext().getResources().getBoolean(
2959 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002960 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002961 }
2962 }
2963 currentVersion = 123;
2964 }
Bryce Leebd179282015-12-17 19:01:37 -08002965
2966 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002967 final SettingsState globalSettings = getGlobalSettingsLocked();
2968 String defaultDisabledProfiles = (getContext().getResources().getString(
2969 R.string.def_bluetooth_disabled_profiles));
2970 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002971 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002972 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002973 }
2974
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002975 if (currentVersion == 124) {
2976 // Version 124: allow OEMs to set a default value for whether IME should be
2977 // shown when a physical keyboard is connected.
2978 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2979 Setting currentSetting = secureSettings.getSettingLocked(
2980 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002981 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002982 secureSettings.insertSettingLocked(
2983 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2984 getContext().getResources().getBoolean(
2985 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002986 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002987 }
2988 currentVersion = 125;
2989 }
2990
Ruben Brunk98576cf2016-03-07 18:54:28 -08002991 if (currentVersion == 125) {
2992 // Version 125: Allow OEMs to set the default VR service.
2993 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2994
2995 Setting currentSetting = secureSettings.getSettingLocked(
2996 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002997 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002998 ArraySet<ComponentName> l =
2999 SystemConfig.getInstance().getDefaultVrComponents();
3000
3001 if (l != null && !l.isEmpty()) {
3002 StringBuilder b = new StringBuilder();
3003 boolean start = true;
3004 for (ComponentName c : l) {
3005 if (!start) {
3006 b.append(':');
3007 }
3008 b.append(c.flattenToString());
3009 start = false;
3010 }
3011 secureSettings.insertSettingLocked(
3012 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003013 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003014 }
3015
3016 }
3017 currentVersion = 126;
3018 }
3019
Daniel U02ba6122016-04-01 18:41:42 +01003020 if (currentVersion == 126) {
3021 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3022 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3023 if (mUserManager.isManagedProfile(userId)) {
3024 final SettingsState systemSecureSettings =
3025 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3026
3027 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3028 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003029 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003030 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3031 secureSettings.insertSettingLocked(
3032 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003033 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003034 SettingsState.SYSTEM_PACKAGE_NAME);
3035 }
3036
3037 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3038 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003039 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003040 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3041 secureSettings.insertSettingLocked(
3042 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003043 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003044 SettingsState.SYSTEM_PACKAGE_NAME);
3045 }
3046 }
3047 currentVersion = 127;
3048 }
3049
Steven Ngdc20ba62016-04-26 18:19:04 +01003050 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003051 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003052 currentVersion = 128;
3053 }
3054
Julia Reynolds1f721e12016-07-11 08:50:58 -04003055 if (currentVersion == 128) {
3056 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3057 // the new apps are appended to the list of already approved apps.
3058 final SettingsState systemSecureSettings =
3059 getSecureSettingsLocked(userId);
3060
3061 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3062 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3063 String defaultPolicyAccess = getContext().getResources().getString(
3064 com.android.internal.R.string.config_defaultDndAccessPackages);
3065 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3066 if (policyAccess.isNull()) {
3067 systemSecureSettings.insertSettingLocked(
3068 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003069 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003070 SettingsState.SYSTEM_PACKAGE_NAME);
3071 } else {
3072 StringBuilder currentSetting =
3073 new StringBuilder(policyAccess.getValue());
3074 currentSetting.append(":");
3075 currentSetting.append(defaultPolicyAccess);
3076 systemSecureSettings.updateSettingLocked(
3077 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003078 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003079 SettingsState.SYSTEM_PACKAGE_NAME);
3080 }
3081 }
3082
3083 currentVersion = 129;
3084 }
3085
Dan Sandler71f85e92016-07-20 13:46:05 -04003086 if (currentVersion == 129) {
3087 // default longpress timeout changed from 500 to 400. If unchanged from the old
3088 // default, update to the new default.
3089 final SettingsState systemSecureSettings =
3090 getSecureSettingsLocked(userId);
3091 final String oldValue = systemSecureSettings.getSettingLocked(
3092 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3093 if (TextUtils.equals("500", oldValue)) {
3094 systemSecureSettings.insertSettingLocked(
3095 Settings.Secure.LONG_PRESS_TIMEOUT,
3096 String.valueOf(getContext().getResources().getInteger(
3097 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003098 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003099 }
3100 currentVersion = 130;
3101 }
3102
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003103 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003104 // Split Ambient settings
3105 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3106 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3107 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3108
3109 if (dozeExplicitlyDisabled) {
3110 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003111 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003112 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003113 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003114 }
3115 currentVersion = 131;
3116 }
3117
3118 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003119 // Initialize new multi-press timeout to default value
3120 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3121 final String oldValue = systemSecureSettings.getSettingLocked(
3122 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3123 if (TextUtils.equals(null, oldValue)) {
3124 systemSecureSettings.insertSettingLocked(
3125 Settings.Secure.MULTI_PRESS_TIMEOUT,
3126 String.valueOf(getContext().getResources().getInteger(
3127 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003128 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003129 }
3130
Adrian Roos69741a22016-10-21 14:49:17 -07003131 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003132 }
3133
Adrian Roos69741a22016-10-21 14:49:17 -07003134 if (currentVersion == 132) {
3135 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003136 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3137 String defaultSyncParentSounds = (getContext().getResources()
3138 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3139 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003140 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3141 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003142 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003143 }
3144
Adrian Roos69741a22016-10-21 14:49:17 -07003145 if (currentVersion == 133) {
3146 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003147 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3148 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3149 null) {
3150 String defaultEndButtonBehavior = Integer.toString(getContext()
3151 .getResources().getInteger(R.integer.def_end_button_behavior));
3152 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003153 defaultEndButtonBehavior, null, true,
3154 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003155 }
Adrian Roos69741a22016-10-21 14:49:17 -07003156 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003157 }
3158
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003159 if (currentVersion == 134) {
3160 // Remove setting that specifies if magnification values should be preserved.
3161 // This setting defaulted to true and never has a UI.
3162 getSecureSettingsLocked(userId).deleteSettingLocked(
3163 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3164 currentVersion = 135;
3165 }
3166
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003167 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003168 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003169 currentVersion = 136;
3170 }
3171
Mark Rathjend891f012017-01-19 04:10:37 +00003172 if (currentVersion == 136) {
3173 // Version 136: Store legacy SSAID for all apps currently installed on the
3174 // device as first step in migrating SSAID to be unique per application.
3175
3176 final boolean isUpgrade;
3177 try {
3178 isUpgrade = mPackageManager.isUpgrade();
3179 } catch (RemoteException e) {
3180 throw new IllegalStateException("Package manager not available");
3181 }
3182 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3183 // user data or first boot on a new device should use new ssaid generation.
3184 if (isUpgrade) {
3185 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003186 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3187 userId, Settings.Secure.ANDROID_ID);
3188 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3189 || legacySsaidSetting.getValue() == null) {
3190 throw new IllegalStateException("Legacy ssaid not accessible");
3191 }
3192 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003193
3194 // Fill each uid with the legacy ssaid to be backwards compatible.
3195 final List<PackageInfo> packages;
3196 try {
3197 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3198 } catch (RemoteException e) {
3199 throw new IllegalStateException("Package manager not available");
3200 }
3201
3202 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3203 for (PackageInfo info : packages) {
3204 // Check if the UID already has an entry in the table.
3205 final String uid = Integer.toString(info.applicationInfo.uid);
3206 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3207
3208 if (ssaid.isNull() || ssaid.getValue() == null) {
3209 // Android Id doesn't exist for this package so create it.
3210 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3211 info.packageName);
3212 }
3213 }
3214 }
3215
3216 currentVersion = 137;
3217 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003218 if (currentVersion == 137) {
3219 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3220 // default value set to 1. The user can no longer change the value of this
3221 // setting through the UI.
3222 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3223 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003224 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3225 && secureSetting.getSettingLocked(
3226 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3227
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003228 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3229 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003230 // For managed profiles with profile owners, DevicePolicyManagerService
3231 // may want to set the user restriction in this case
3232 secureSetting.insertSettingLocked(
3233 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3234 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003235 }
3236 currentVersion = 138;
3237 }
Mark Rathjend891f012017-01-19 04:10:37 +00003238
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003239 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003240 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003241 currentVersion = 139;
3242 }
3243
Phil Weaver385912e2017-02-10 10:06:56 -08003244 if (currentVersion == 139) {
3245 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3246 // the user can no longer change the value of this setting through the UI.
3247 // Force to true.
3248 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3249 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3250 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3251 currentVersion = 140;
3252 }
3253
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003254 if (currentVersion == 140) {
3255 // Version 141: One-time grant of notification listener privileges
3256 // to packages specified in overlay.
3257 String defaultListenerAccess = getContext().getResources().getString(
3258 com.android.internal.R.string.config_defaultListenerAccessPackages);
3259 if (defaultListenerAccess != null) {
3260 StringBuffer newListeners = new StringBuffer();
3261 for (String whitelistPkg : defaultListenerAccess.split(":")) {
3262 // Gather all notification listener components for candidate pkgs.
3263 Intent serviceIntent =
3264 new Intent(NotificationListenerService.SERVICE_INTERFACE)
3265 .setPackage(whitelistPkg);
3266 List<ResolveInfo> installedServices =
3267 getContext().getPackageManager().queryIntentServicesAsUser(
3268 serviceIntent,
3269 PackageManager.GET_SERVICES
3270 | PackageManager.GET_META_DATA
3271 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3272 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
3273 userId);
3274
3275 for (int i = 0, count = installedServices.size(); i < count; i++) {
3276 ResolveInfo resolveInfo = installedServices.get(i);
3277 ServiceInfo info = resolveInfo.serviceInfo;
3278 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
3279 .equals(info.permission)) {
3280 continue;
3281 }
3282 newListeners.append(":")
3283 .append(info.getComponentName().flattenToString());
3284 }
3285 }
3286
3287 if (newListeners.length() > 0) {
3288 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3289 final Setting existingSetting = secureSetting.getSettingLocked(
3290 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
3291 if (existingSetting.isNull()) {
3292 secureSetting.insertSettingLocked(
3293 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3294 newListeners.toString(), null, true,
3295 SettingsState.SYSTEM_PACKAGE_NAME);
3296 } else {
3297 StringBuilder currentSetting =
3298 new StringBuilder(existingSetting.getValue());
3299 currentSetting.append(newListeners.toString());
3300 secureSetting.updateSettingLocked(
3301 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3302 currentSetting.toString(), null, true,
3303 SettingsState.SYSTEM_PACKAGE_NAME);
3304 }
3305 }
3306 }
3307 currentVersion = 141;
3308 }
3309
Svet Ganov13701552017-02-23 12:45:17 -08003310 if (currentVersion == 141) {
3311 // Version 141: We added the notion of a default and whether the system set
3312 // the setting. This is used for resetting the internal state and we need
3313 // to make sure this value is updated for the existing settings, otherwise
3314 // we would delete system set settings while they should stay unmodified.
3315 SettingsState globalSettings = getGlobalSettingsLocked();
3316 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3317 globalSettings.persistSyncLocked();
3318
3319 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3320 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3321 secureSettings.persistSyncLocked();
3322
3323 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3324 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3325 systemSettings.persistSyncLocked();
3326
3327 currentVersion = 142;
3328 }
3329
Dan Sandler71f85e92016-07-20 13:46:05 -04003330 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003331 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003332 + newVersion + " left it at "
3333 + currentVersion + " instead; this is probably a bug", new Throwable());
3334 if (DEBUG) {
3335 throw new RuntimeException("db upgrade error");
3336 }
3337 }
3338
Jeff Brown503cffc2015-03-26 18:08:51 -07003339 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003340
Jeff Brown503cffc2015-03-26 18:08:51 -07003341 // Return the current version.
3342 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003343 }
3344 }
Svet Ganov13701552017-02-23 12:45:17 -08003345
3346 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3347 List<String> names = settings.getSettingNamesLocked();
3348 final int nameCount = names.size();
3349 for (int i = 0; i < nameCount; i++) {
3350 String name = names.get(i);
3351 Setting setting = settings.getSettingLocked(name);
3352 if (setting.getDefaultValue() == null) {
3353 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3354 setting.getPackageName());
3355 if (systemSet) {
3356 settings.insertSettingLocked(name, setting.getValue(),
3357 setting.getTag(), true, setting.getPackageName());
3358 }
3359 }
3360 }
3361 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003362 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003363}