blob: 0916abebcc499f3be07309ac3b0a5f15a70fe3c1 [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) {
1581 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001582 if (ai.isInstantApp()) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001583 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001584 } else {
1585 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1586 }
1587 }
1588
1589 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1590 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1591 return;
1592 }
1593 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001594 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001595 return;
1596 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08001597 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001598 throw new SecurityException("Setting " + settingName + " is not accessible from"
1599 + " ephemeral package " + getCallingPackage());
1600 }
1601 }
1602
1603 private ApplicationInfo getCallingApplicationInfoOrThrow(int userId) {
1604 ApplicationInfo ai = null;
1605 try {
1606 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0 , userId);
1607 } catch (RemoteException ignored) {
1608 }
1609 if (ai == null) {
1610 throw new IllegalStateException("Failed to lookup info for package "
1611 + getCallingPackage());
1612 }
1613 return ai;
1614 }
1615
Xiaohui Chen43765b72015-08-31 10:57:33 -07001616 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001617 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001618 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1619 getCallingPackage(), 0, userId);
1620 if (packageInfo != null) {
1621 return packageInfo;
1622 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001623 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001624 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001625 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001626 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001627 }
1628
1629 private int getGroupParentLocked(int userId) {
1630 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001631 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001632 return userId;
1633 }
1634 // We are in the same process with the user manager and the returned
1635 // user info is a cached instance, so just look up instead of cache.
1636 final long identity = Binder.clearCallingIdentity();
1637 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001638 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001639 UserInfo userInfo = mUserManager.getProfileParent(userId);
1640 return (userInfo != null) ? userInfo.id : userId;
1641 } finally {
1642 Binder.restoreCallingIdentity(identity);
1643 }
1644 }
1645
Svetoslav683914b2015-01-15 14:22:26 -08001646 private void enforceWritePermission(String permission) {
1647 if (getContext().checkCallingOrSelfPermission(permission)
1648 != PackageManager.PERMISSION_GRANTED) {
1649 throw new SecurityException("Permission denial: writing to settings requires:"
1650 + permission);
1651 }
1652 }
1653
1654 /*
1655 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1656 * This setting contains a list of the currently enabled location providers.
1657 * But helper functions in android.providers.Settings can enable or disable
1658 * a single provider by using a "+" or "-" prefix before the provider name.
1659 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001660 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1661 * is set, the said method will only allow values with the "-" prefix.
1662 *
Svetoslav683914b2015-01-15 14:22:26 -08001663 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001664 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001665 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1666 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001667 if (TextUtils.isEmpty(value)) {
1668 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001669 }
1670
Svetoslav683914b2015-01-15 14:22:26 -08001671 final char prefix = value.charAt(0);
1672 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001673 if (forceNotify) {
1674 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1675 mSettingsRegistry.notifyForSettingsChange(key,
1676 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1677 }
Svetoslav683914b2015-01-15 14:22:26 -08001678 return false;
1679 }
1680
1681 // skip prefix
1682 value = value.substring(1);
1683
Svetoslav7ec28e82015-05-20 17:01:10 -07001684 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001685 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001686 if (settingValue == null) {
1687 return false;
1688 }
Svetoslav683914b2015-01-15 14:22:26 -08001689
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001690 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001691
1692 int index = oldProviders.indexOf(value);
1693 int end = index + value.length();
1694
1695 // check for commas to avoid matching on partial string
1696 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1697 index = -1;
1698 }
1699
1700 // check for commas to avoid matching on partial string
1701 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1702 index = -1;
1703 }
1704
1705 String newProviders;
1706
1707 if (prefix == '+' && index < 0) {
1708 // append the provider to the list if not present
1709 if (oldProviders.length() == 0) {
1710 newProviders = value;
1711 } else {
1712 newProviders = oldProviders + ',' + value;
1713 }
1714 } else if (prefix == '-' && index >= 0) {
1715 // remove the provider from the list if present
1716 // remove leading or trailing comma
1717 if (index > 0) {
1718 index--;
1719 } else if (end < oldProviders.length()) {
1720 end++;
1721 }
1722
1723 newProviders = oldProviders.substring(0, index);
1724 if (end < oldProviders.length()) {
1725 newProviders += oldProviders.substring(end);
1726 }
1727 } else {
1728 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001729 if (forceNotify) {
1730 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1731 mSettingsRegistry.notifyForSettingsChange(key,
1732 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1733 }
Svetoslav683914b2015-01-15 14:22:26 -08001734 return false;
1735 }
1736
Svet Ganov53a441c2016-04-19 19:38:00 -07001737 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001738 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001739 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001740 }
1741
Svetoslav683914b2015-01-15 14:22:26 -08001742 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1743 int targetSdkVersion, String name) {
1744 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1745 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1746 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1747 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1748 + " This will soon become an error.");
1749 } else {
1750 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1751 + " This will soon become an error.");
1752 }
1753 } else {
1754 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1755 throw new IllegalArgumentException("You cannot change private secure settings.");
1756 } else {
1757 throw new IllegalArgumentException("You cannot keep your settings in"
1758 + " the secure settings.");
1759 }
1760 }
1761 }
1762
1763 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1764 if (requestingUserId == UserHandle.getCallingUserId()) {
1765 return requestingUserId;
1766 }
1767 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1768 Binder.getCallingUid(), requestingUserId, false, true,
1769 "get/set setting for user", null);
1770 }
1771
Svet Ganov53a441c2016-04-19 19:38:00 -07001772 private Bundle packageValueForCallResult(Setting setting,
1773 boolean trackingGeneration) {
1774 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001775 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001776 return NULL_SETTING_BUNDLE;
1777 }
1778 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001779 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001780 Bundle result = new Bundle();
1781 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001782 !setting.isNull() ? setting.getValue() : null);
1783 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001784 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001785 }
1786
1787 private static int getRequestingUserId(Bundle args) {
1788 final int callingUserId = UserHandle.getCallingUserId();
1789 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1790 : callingUserId;
1791 }
1792
Svet Ganov53a441c2016-04-19 19:38:00 -07001793 private boolean isTrackingGeneration(Bundle args) {
1794 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1795 }
1796
Svetoslav683914b2015-01-15 14:22:26 -08001797 private static String getSettingValue(Bundle args) {
1798 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1799 }
1800
Svetoslav Ganove080da92016-12-21 17:10:35 -08001801 private static String getSettingTag(Bundle args) {
1802 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1803 }
1804
1805 private static boolean getSettingMakeDefault(Bundle args) {
1806 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1807 }
1808
1809 private static int getResetModeEnforcingPermission(Bundle args) {
1810 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1811 switch (mode) {
1812 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1813 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1814 throw new SecurityException("Only system, shell/root on a "
1815 + "debuggable build can reset to untrusted defaults");
1816 }
1817 return mode;
1818 }
1819 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1820 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1821 throw new SecurityException("Only system, shell/root on a "
1822 + "debuggable build can reset untrusted changes");
1823 }
1824 return mode;
1825 }
1826 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1827 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1828 throw new SecurityException("Only system, shell/root on a "
1829 + "debuggable build can reset to trusted defaults");
1830 }
1831 return mode;
1832 }
1833 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1834 return mode;
1835 }
1836 }
1837 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1838 }
1839
1840 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1841 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1842 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1843 && (appId == SHELL_UID || appId == ROOT_UID));
1844 }
1845
Svetoslav683914b2015-01-15 14:22:26 -08001846 private static String getValidTableOrThrow(Uri uri) {
1847 if (uri.getPathSegments().size() > 0) {
1848 String table = uri.getPathSegments().get(0);
1849 if (DatabaseHelper.isValidTable(table)) {
1850 return table;
1851 }
1852 throw new IllegalArgumentException("Bad root path: " + table);
1853 }
1854 throw new IllegalArgumentException("Invalid URI:" + uri);
1855 }
1856
1857 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001858 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001859 return new MatrixCursor(projection, 0);
1860 }
1861 MatrixCursor cursor = new MatrixCursor(projection, 1);
1862 appendSettingToCursor(cursor, setting);
1863 return cursor;
1864 }
1865
1866 private static String[] normalizeProjection(String[] projection) {
1867 if (projection == null) {
1868 return ALL_COLUMNS;
1869 }
1870
1871 final int columnCount = projection.length;
1872 for (int i = 0; i < columnCount; i++) {
1873 String column = projection[i];
1874 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1875 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001876 }
1877 }
1878
Svetoslav683914b2015-01-15 14:22:26 -08001879 return projection;
1880 }
1881
1882 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001883 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001884 return;
1885 }
Svetoslav683914b2015-01-15 14:22:26 -08001886 final int columnCount = cursor.getColumnCount();
1887
1888 String[] values = new String[columnCount];
1889
1890 for (int i = 0; i < columnCount; i++) {
1891 String column = cursor.getColumnName(i);
1892
1893 switch (column) {
1894 case Settings.NameValueTable._ID: {
1895 values[i] = setting.getId();
1896 } break;
1897
1898 case Settings.NameValueTable.NAME: {
1899 values[i] = setting.getName();
1900 } break;
1901
1902 case Settings.NameValueTable.VALUE: {
1903 values[i] = setting.getValue();
1904 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001905 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001906 }
1907
Svetoslav683914b2015-01-15 14:22:26 -08001908 cursor.addRow(values);
1909 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001910
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001911 private static boolean isKeyValid(String key) {
1912 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1913 }
1914
Svetoslav683914b2015-01-15 14:22:26 -08001915 private static final class Arguments {
1916 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1917 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1918
1919 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1920 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1921
1922 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1923 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1924
1925 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1926 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1927
1928 public final String table;
1929 public final String name;
1930
1931 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1932 final int segmentSize = uri.getPathSegments().size();
1933 switch (segmentSize) {
1934 case 1: {
1935 if (where != null
1936 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1937 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1938 && whereArgs.length == 1) {
1939 name = whereArgs[0];
1940 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001941 return;
Svetoslav683914b2015-01-15 14:22:26 -08001942 } else if (where != null
1943 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1944 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1945 final int startIndex = Math.max(where.indexOf("'"),
1946 where.indexOf("\"")) + 1;
1947 final int endIndex = Math.max(where.lastIndexOf("'"),
1948 where.lastIndexOf("\""));
1949 name = where.substring(startIndex, endIndex);
1950 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001951 return;
Svetoslav683914b2015-01-15 14:22:26 -08001952 } else if (supportAll && where == null && whereArgs == null) {
1953 name = null;
1954 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001955 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001956 }
Svetoslav683914b2015-01-15 14:22:26 -08001957 } break;
1958
Svetoslav28494652015-02-12 14:11:42 -08001959 case 2: {
1960 if (where == null && whereArgs == null) {
1961 name = uri.getPathSegments().get(1);
1962 table = computeTableForSetting(uri, name);
1963 return;
1964 }
1965 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001966 }
Svetoslav28494652015-02-12 14:11:42 -08001967
1968 EventLogTags.writeUnsupportedSettingsQuery(
1969 uri.toSafeString(), where, Arrays.toString(whereArgs));
1970 String message = String.format( "Supported SQL:\n"
1971 + " uri content://some_table/some_property with null where and where args\n"
1972 + " uri content://some_table with query name=? and single name as arg\n"
1973 + " uri content://some_table with query name=some_name and null args\n"
1974 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1975 Arrays.toString(whereArgs));
1976 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001977 }
1978
Svetoslav28494652015-02-12 14:11:42 -08001979 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001980 String table = getValidTableOrThrow(uri);
1981
1982 if (name != null) {
1983 if (sSystemMovedToSecureSettings.contains(name)) {
1984 table = TABLE_SECURE;
1985 }
1986
1987 if (sSystemMovedToGlobalSettings.contains(name)) {
1988 table = TABLE_GLOBAL;
1989 }
1990
1991 if (sSecureMovedToGlobalSettings.contains(name)) {
1992 table = TABLE_GLOBAL;
1993 }
1994
1995 if (sGlobalMovedToSecureSettings.contains(name)) {
1996 table = TABLE_SECURE;
1997 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001998 }
Svetoslav683914b2015-01-15 14:22:26 -08001999
2000 return table;
2001 }
2002 }
2003
2004 final class SettingsRegistry {
2005 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2006
Svetoslav683914b2015-01-15 14:22:26 -08002007 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2008 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2009 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002010 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2011
2012 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002013
2014 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2015
Svet Ganov53a441c2016-04-19 19:38:00 -07002016 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002017
Svetoslav7e0683b2015-08-03 16:02:52 -07002018 private final Handler mHandler;
2019
Svet Ganov53a441c2016-04-19 19:38:00 -07002020 private final BackupManager mBackupManager;
2021
Svetoslav683914b2015-01-15 14:22:26 -08002022 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002023 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002024 mGenerationRegistry = new GenerationRegistry(mLock);
2025 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002026 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002027 syncSsaidTableOnStart();
2028 }
2029
2030 private void generateUserKeyLocked(int userId) {
2031 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002032 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002033 final SecureRandom rand = new SecureRandom();
2034 rand.nextBytes(keyBytes);
2035
2036 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002037 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002038
2039 // Store the key in the ssaid table.
2040 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2041 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2042 true, SettingsState.SYSTEM_PACKAGE_NAME);
2043
2044 if (!success) {
2045 throw new IllegalStateException("Ssaid settings not accessible");
2046 }
2047 }
2048
Mark Rathjen7599f132017-01-23 14:15:54 -08002049 private byte[] getLengthPrefix(byte[] data) {
2050 return ByteBuffer.allocate(4).putInt(data.length).array();
2051 }
2052
Mark Rathjend891f012017-01-19 04:10:37 +00002053 public Setting generateSsaidLocked(String packageName, int userId) {
2054 final PackageInfo packageInfo;
2055 try {
2056 packageInfo = mPackageManager.getPackageInfo(packageName,
2057 PackageManager.GET_SIGNATURES, userId);
2058 } catch (RemoteException e) {
2059 throw new IllegalStateException("Package info doesn't exist");
2060 }
2061
2062 // Read the user's key from the ssaid table.
2063 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002064 if (userKeySetting == null || userKeySetting.isNull()
2065 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002066 // Lazy initialize and store the user key.
2067 generateUserKeyLocked(userId);
2068 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002069 if (userKeySetting == null || userKeySetting.isNull()
2070 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002071 throw new IllegalStateException("User key not accessible");
2072 }
2073 }
2074 final String userKey = userKeySetting.getValue();
2075
2076 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002077 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2078
2079 // Validate that the key is of expected length.
2080 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2081 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002082 throw new IllegalStateException("User key invalid");
2083 }
2084
Mark Rathjen7599f132017-01-23 14:15:54 -08002085 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002086 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002087 m = Mac.getInstance("HmacSHA256");
2088 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002089 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002090 throw new IllegalStateException("HmacSHA256 is not available", e);
2091 } catch (InvalidKeyException e) {
2092 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002093 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002094
2095 // Mac the package name and each of the signatures.
2096 byte[] packageNameBytes = packageInfo.packageName.getBytes(StandardCharsets.UTF_8);
2097 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2098 m.update(packageNameBytes);
2099 for (int i = 0; i < packageInfo.signatures.length; i++) {
2100 byte[] sig = packageInfo.signatures[i].toByteArray();
2101 m.update(getLengthPrefix(sig), 0, 4);
2102 m.update(sig);
2103 }
Mark Rathjend891f012017-01-19 04:10:37 +00002104
2105 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002106 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2107 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002108
2109 // Save the ssaid in the ssaid table.
2110 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2111 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2112 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2113 packageName);
2114
2115 if (!success) {
2116 throw new IllegalStateException("Ssaid settings not accessible");
2117 }
2118
2119 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2120 }
2121
2122 public void syncSsaidTableOnStart() {
2123 synchronized (mLock) {
2124 // Verify that each user's packages and ssaid's are in sync.
2125 for (UserInfo user : mUserManager.getUsers(true)) {
2126 // Get all uids for the user's packages.
2127 final List<PackageInfo> packages;
2128 try {
2129 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2130 } catch (RemoteException e) {
2131 throw new IllegalStateException("Package manager not available");
2132 }
2133 final Set<String> appUids = new HashSet<>();
2134 for (PackageInfo info : packages) {
2135 appUids.add(Integer.toString(info.applicationInfo.uid));
2136 }
2137
2138 // Get all uids currently stored in the user's ssaid table.
2139 final Set<String> ssaidUids = new HashSet<>(
2140 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2141 ssaidUids.remove(SSAID_USER_KEY);
2142
2143 // Perform a set difference for the appUids and ssaidUids.
2144 ssaidUids.removeAll(appUids);
2145
2146 // If there are ssaidUids left over they need to be removed from the table.
2147 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2148 user.id);
2149 for (String uid : ssaidUids) {
2150 ssaidSettings.deleteSettingLocked(uid);
2151 }
2152 }
2153 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002154 }
2155
Svetoslav683914b2015-01-15 14:22:26 -08002156 public List<String> getSettingsNamesLocked(int type, int userId) {
2157 final int key = makeKey(type, userId);
2158 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002159 if (settingsState == null) {
2160 return new ArrayList<String>();
2161 }
Svetoslav683914b2015-01-15 14:22:26 -08002162 return settingsState.getSettingNamesLocked();
2163 }
2164
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002165 public SparseBooleanArray getKnownUsersLocked() {
2166 SparseBooleanArray users = new SparseBooleanArray();
2167 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2168 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2169 }
2170 return users;
2171 }
2172
Svetoslav683914b2015-01-15 14:22:26 -08002173 public SettingsState getSettingsLocked(int type, int userId) {
2174 final int key = makeKey(type, userId);
2175 return peekSettingsStateLocked(key);
2176 }
2177
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002178 public boolean ensureSettingsForUserLocked(int userId) {
2179 // First make sure this user actually exists.
2180 if (mUserManager.getUserInfo(userId) == null) {
2181 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2182 return false;
2183 }
2184
Svetoslav683914b2015-01-15 14:22:26 -08002185 // Migrate the setting for this user if needed.
2186 migrateLegacySettingsForUserIfNeededLocked(userId);
2187
2188 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002189 if (userId == UserHandle.USER_SYSTEM) {
2190 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002191 ensureSettingsStateLocked(globalKey);
2192 }
2193
2194 // Ensure secure settings loaded.
2195 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2196 ensureSettingsStateLocked(secureKey);
2197
2198 // Make sure the secure settings have an Android id set.
2199 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2200 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2201
2202 // Ensure system settings loaded.
2203 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2204 ensureSettingsStateLocked(systemKey);
2205
Mark Rathjend891f012017-01-19 04:10:37 +00002206 // Ensure secure settings loaded.
2207 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2208 ensureSettingsStateLocked(ssaidKey);
2209
Svetoslav683914b2015-01-15 14:22:26 -08002210 // Upgrade the settings to the latest version.
2211 UpgradeController upgrader = new UpgradeController(userId);
2212 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002213 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002214 }
2215
2216 private void ensureSettingsStateLocked(int key) {
2217 if (mSettingsStates.get(key) == null) {
2218 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002219 SettingsState settingsState = new SettingsState(getContext(), mLock,
2220 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002221 mSettingsStates.put(key, settingsState);
2222 }
2223 }
2224
2225 public void removeUserStateLocked(int userId, boolean permanently) {
2226 // We always keep the global settings in memory.
2227
2228 // Nuke system settings.
2229 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2230 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2231 if (systemSettingsState != null) {
2232 if (permanently) {
2233 mSettingsStates.remove(systemKey);
2234 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002235 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002236 systemSettingsState.destroyLocked(new Runnable() {
2237 @Override
2238 public void run() {
2239 mSettingsStates.remove(systemKey);
2240 }
2241 });
2242 }
2243 }
2244
2245 // Nuke secure settings.
2246 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2247 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2248 if (secureSettingsState != null) {
2249 if (permanently) {
2250 mSettingsStates.remove(secureKey);
2251 secureSettingsState.destroyLocked(null);
2252 } else {
2253 secureSettingsState.destroyLocked(new Runnable() {
2254 @Override
2255 public void run() {
2256 mSettingsStates.remove(secureKey);
2257 }
2258 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002259 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002260 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002261
Mark Rathjend891f012017-01-19 04:10:37 +00002262 // Nuke ssaid settings.
2263 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2264 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2265 if (ssaidSettingsState != null) {
2266 if (permanently) {
2267 mSettingsStates.remove(ssaidKey);
2268 ssaidSettingsState.destroyLocked(null);
2269 } else {
2270 ssaidSettingsState.destroyLocked(new Runnable() {
2271 @Override
2272 public void run() {
2273 mSettingsStates.remove(ssaidKey);
2274 }
2275 });
2276 }
2277 }
2278
Svet Ganov53a441c2016-04-19 19:38:00 -07002279 // Nuke generation tracking data
2280 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002281 }
2282
Svetoslav683914b2015-01-15 14:22:26 -08002283 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002284 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2285 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002286 final int key = makeKey(type, userId);
2287
Svetoslav Ganove080da92016-12-21 17:10:35 -08002288 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002289 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002290 if (settingsState != null) {
2291 success = settingsState.insertSettingLocked(name, value,
2292 tag, makeDefault, packageName);
2293 }
Svetoslav683914b2015-01-15 14:22:26 -08002294
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002295 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2296 settingsState.persistSyncLocked();
2297 }
2298
Svet Ganov53a441c2016-04-19 19:38:00 -07002299 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002300 notifyForSettingsChange(key, name);
2301 }
2302 return success;
2303 }
2304
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002305 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2306 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002307 final int key = makeKey(type, userId);
2308
Svetoslav Ganove080da92016-12-21 17:10:35 -08002309 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002310 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002311 if (settingsState != null) {
2312 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002313 }
Svetoslav683914b2015-01-15 14:22:26 -08002314
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002315 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2316 settingsState.persistSyncLocked();
2317 }
2318
Svet Ganov53a441c2016-04-19 19:38:00 -07002319 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002320 notifyForSettingsChange(key, name);
2321 }
2322 return success;
2323 }
2324
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002325 public boolean updateSettingLocked(int type, int userId, String name, String value,
2326 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2327 Set<String> criticalSettings) {
2328 final int key = makeKey(type, userId);
2329
2330 boolean success = false;
2331 SettingsState settingsState = peekSettingsStateLocked(key);
2332 if (settingsState != null) {
2333 success = settingsState.updateSettingLocked(name, value, tag,
2334 makeDefault, packageName);
2335 }
2336
2337 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2338 settingsState.persistSyncLocked();
2339 }
2340
2341 if (forceNotify || success) {
2342 notifyForSettingsChange(key, name);
2343 }
2344
2345 return success;
2346 }
2347
Svetoslav683914b2015-01-15 14:22:26 -08002348 public Setting getSettingLocked(int type, int userId, String name) {
2349 final int key = makeKey(type, userId);
2350
2351 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002352 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002353 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002354 }
Mark Rathjend891f012017-01-19 04:10:37 +00002355
2356 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002357 return settingsState.getSettingLocked(name);
2358 }
2359
Svetoslav Ganove080da92016-12-21 17:10:35 -08002360 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2361 String tag) {
2362 final int key = makeKey(type, userId);
2363 SettingsState settingsState = peekSettingsStateLocked(key);
2364 if (settingsState == null) {
2365 return;
2366 }
2367
2368 switch (mode) {
2369 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2370 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002371 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002372 Setting setting = settingsState.getSettingLocked(name);
2373 if (packageName.equals(setting.getPackageName())) {
2374 if (tag != null && !tag.equals(setting.getTag())) {
2375 continue;
2376 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002377 if (settingsState.resetSettingLocked(name)) {
2378 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002379 notifyForSettingsChange(key, name);
2380 }
2381 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002382 if (someSettingChanged) {
2383 settingsState.persistSyncLocked();
2384 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002385 }
2386 } break;
2387
2388 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2389 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002390 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002391 Setting setting = settingsState.getSettingLocked(name);
2392 if (!SettingsState.isSystemPackage(getContext(),
2393 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002394 if (settingsState.resetSettingLocked(name)) {
2395 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002396 notifyForSettingsChange(key, name);
2397 }
2398 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002399 if (someSettingChanged) {
2400 settingsState.persistSyncLocked();
2401 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002402 }
2403 } break;
2404
2405 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2406 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002407 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002408 Setting setting = settingsState.getSettingLocked(name);
2409 if (!SettingsState.isSystemPackage(getContext(),
2410 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002411 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002412 if (settingsState.resetSettingLocked(name)) {
2413 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002414 notifyForSettingsChange(key, name);
2415 }
2416 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002417 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002418 notifyForSettingsChange(key, name);
2419 }
2420 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002421 if (someSettingChanged) {
2422 settingsState.persistSyncLocked();
2423 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002424 }
2425 } break;
2426
2427 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2428 for (String name : settingsState.getSettingNamesLocked()) {
2429 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002430 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002431 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002432 if (settingsState.resetSettingLocked(name)) {
2433 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002434 notifyForSettingsChange(key, name);
2435 }
2436 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002437 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002438 notifyForSettingsChange(key, name);
2439 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002440 if (someSettingChanged) {
2441 settingsState.persistSyncLocked();
2442 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002443 }
2444 } break;
2445 }
2446 }
2447
Svetoslav683914b2015-01-15 14:22:26 -08002448 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002449 // Global and secure settings are signature protected. Apps signed
2450 // by the platform certificate are generally not uninstalled and
2451 // the main exception is tests. We trust components signed
2452 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002453
2454 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2455 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002456 if (systemSettings != null) {
2457 systemSettings.onPackageRemovedLocked(packageName);
2458 }
Svetoslav683914b2015-01-15 14:22:26 -08002459 }
2460
Mark Rathjend891f012017-01-19 04:10:37 +00002461 public void onUidRemovedLocked(int uid) {
2462 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2463 UserHandle.getUserId(uid));
2464 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2465 }
2466
Svetoslav683914b2015-01-15 14:22:26 -08002467 private SettingsState peekSettingsStateLocked(int key) {
2468 SettingsState settingsState = mSettingsStates.get(key);
2469 if (settingsState != null) {
2470 return settingsState;
2471 }
2472
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002473 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2474 return null;
2475 }
Svetoslav683914b2015-01-15 14:22:26 -08002476 return mSettingsStates.get(key);
2477 }
2478
2479 private void migrateAllLegacySettingsIfNeeded() {
2480 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002481 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002482 File globalFile = getSettingsFile(key);
2483 if (globalFile.exists()) {
2484 return;
2485 }
2486
2487 final long identity = Binder.clearCallingIdentity();
2488 try {
2489 List<UserInfo> users = mUserManager.getUsers(true);
2490
2491 final int userCount = users.size();
2492 for (int i = 0; i < userCount; i++) {
2493 final int userId = users.get(i).id;
2494
2495 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2496 SQLiteDatabase database = dbHelper.getWritableDatabase();
2497 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2498
2499 // Upgrade to the latest version.
2500 UpgradeController upgrader = new UpgradeController(userId);
2501 upgrader.upgradeIfNeededLocked();
2502
2503 // Drop from memory if not a running user.
2504 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2505 removeUserStateLocked(userId, false);
2506 }
2507 }
2508 } finally {
2509 Binder.restoreCallingIdentity(identity);
2510 }
2511 }
2512 }
2513
2514 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2515 // Every user has secure settings and if no file we need to migrate.
2516 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2517 File secureFile = getSettingsFile(secureKey);
2518 if (secureFile.exists()) {
2519 return;
2520 }
2521
2522 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2523 SQLiteDatabase database = dbHelper.getWritableDatabase();
2524
2525 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2526 }
2527
2528 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2529 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002530 // Move over the system settings.
2531 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2532 ensureSettingsStateLocked(systemKey);
2533 SettingsState systemSettings = mSettingsStates.get(systemKey);
2534 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2535 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002536
2537 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002538 // Do this after System settings, since this is the first thing we check when deciding
2539 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002540 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2541 ensureSettingsStateLocked(secureKey);
2542 SettingsState secureSettings = mSettingsStates.get(secureKey);
2543 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2544 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2545 secureSettings.persistSyncLocked();
2546
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002547 // Move over the global settings if owner.
2548 // Do this last, since this is the first thing we check when deciding
2549 // to skip over migration from db to xml for owner user.
2550 if (userId == UserHandle.USER_SYSTEM) {
2551 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2552 ensureSettingsStateLocked(globalKey);
2553 SettingsState globalSettings = mSettingsStates.get(globalKey);
2554 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2555 globalSettings.persistSyncLocked();
2556 }
Svetoslav683914b2015-01-15 14:22:26 -08002557
2558 // Drop the database as now all is moved and persisted.
2559 if (DROP_DATABASE_ON_MIGRATION) {
2560 dbHelper.dropDatabase();
2561 } else {
2562 dbHelper.backupDatabase();
2563 }
2564 }
2565
2566 private void migrateLegacySettingsLocked(SettingsState settingsState,
2567 SQLiteDatabase database, String table) {
2568 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2569 queryBuilder.setTables(table);
2570
2571 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2572 null, null, null, null, null);
2573
2574 if (cursor == null) {
2575 return;
2576 }
2577
2578 try {
2579 if (!cursor.moveToFirst()) {
2580 return;
2581 }
2582
2583 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2584 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2585
2586 settingsState.setVersionLocked(database.getVersion());
2587
2588 while (!cursor.isAfterLast()) {
2589 String name = cursor.getString(nameColumnIdx);
2590 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002591 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002592 SettingsState.SYSTEM_PACKAGE_NAME);
2593 cursor.moveToNext();
2594 }
2595 } finally {
2596 cursor.close();
2597 }
2598 }
2599
2600 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2601 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2602
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002603 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002604 return;
2605 }
2606
2607 final int userId = getUserIdFromKey(secureSettings.mKey);
2608
2609 final UserInfo user;
2610 final long identity = Binder.clearCallingIdentity();
2611 try {
2612 user = mUserManager.getUserInfo(userId);
2613 } finally {
2614 Binder.restoreCallingIdentity(identity);
2615 }
2616 if (user == null) {
2617 // Can happen due to races when deleting users - treat as benign.
2618 return;
2619 }
2620
2621 String androidId = Long.toHexString(new SecureRandom().nextLong());
2622 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002623 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002624
2625 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2626 + "] for user " + userId);
2627
2628 // Write a drop box entry if it's a restricted profile
2629 if (user.isRestricted()) {
2630 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2631 Context.DROPBOX_SERVICE);
2632 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2633 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2634 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2635 }
2636 }
2637 }
2638
2639 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002640 final int userId = getUserIdFromKey(key);
2641 Uri uri = getNotificationUriFor(key, name);
2642
Phil Weaver83fec002016-05-11 10:55:29 -07002643 mGenerationRegistry.incrementGeneration(key);
2644
Svetoslav7e0683b2015-08-03 16:02:52 -07002645 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2646 userId, 0, uri).sendToTarget();
2647
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002648 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002649 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2650 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002651 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2652 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002653 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002654 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2655 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002656 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002657
Svet Ganov53a441c2016-04-19 19:38:00 -07002658 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002659 }
2660
Svet Ganov53a441c2016-04-19 19:38:00 -07002661 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002662 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002663 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002664 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002665 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002666 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002667 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002668 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002669 final int key = makeKey(type, profileId);
2670 mGenerationRegistry.incrementGeneration(key);
2671
2672 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002673 }
2674 }
2675 }
Svetoslav683914b2015-01-15 14:22:26 -08002676 }
2677
Svetoslav683914b2015-01-15 14:22:26 -08002678 private boolean isGlobalSettingsKey(int key) {
2679 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2680 }
2681
2682 private boolean isSystemSettingsKey(int key) {
2683 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2684 }
2685
2686 private boolean isSecureSettingsKey(int key) {
2687 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2688 }
2689
Mark Rathjend891f012017-01-19 04:10:37 +00002690 private boolean isSsaidSettingsKey(int key) {
2691 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2692 }
2693
Svetoslav683914b2015-01-15 14:22:26 -08002694 private File getSettingsFile(int key) {
2695 if (isGlobalSettingsKey(key)) {
2696 final int userId = getUserIdFromKey(key);
2697 return new File(Environment.getUserSystemDirectory(userId),
2698 SETTINGS_FILE_GLOBAL);
2699 } else if (isSystemSettingsKey(key)) {
2700 final int userId = getUserIdFromKey(key);
2701 return new File(Environment.getUserSystemDirectory(userId),
2702 SETTINGS_FILE_SYSTEM);
2703 } else if (isSecureSettingsKey(key)) {
2704 final int userId = getUserIdFromKey(key);
2705 return new File(Environment.getUserSystemDirectory(userId),
2706 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002707 } else if (isSsaidSettingsKey(key)) {
2708 final int userId = getUserIdFromKey(key);
2709 return new File(Environment.getUserSystemDirectory(userId),
2710 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002711 } else {
2712 throw new IllegalArgumentException("Invalid settings key:" + key);
2713 }
2714 }
2715
2716 private Uri getNotificationUriFor(int key, String name) {
2717 if (isGlobalSettingsKey(key)) {
2718 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2719 : Settings.Global.CONTENT_URI;
2720 } else if (isSecureSettingsKey(key)) {
2721 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2722 : Settings.Secure.CONTENT_URI;
2723 } else if (isSystemSettingsKey(key)) {
2724 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2725 : Settings.System.CONTENT_URI;
2726 } else {
2727 throw new IllegalArgumentException("Invalid settings key:" + key);
2728 }
2729 }
2730
2731 private int getMaxBytesPerPackageForType(int type) {
2732 switch (type) {
2733 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002734 case SETTINGS_TYPE_SECURE:
2735 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002736 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2737 }
2738
2739 default: {
2740 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2741 }
2742 }
2743 }
2744
Svetoslav7e0683b2015-08-03 16:02:52 -07002745 private final class MyHandler extends Handler {
2746 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2747 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2748
2749 public MyHandler(Looper looper) {
2750 super(looper);
2751 }
2752
2753 @Override
2754 public void handleMessage(Message msg) {
2755 switch (msg.what) {
2756 case MSG_NOTIFY_URI_CHANGED: {
2757 final int userId = msg.arg1;
2758 Uri uri = (Uri) msg.obj;
2759 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2760 if (DEBUG) {
2761 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2762 }
2763 } break;
2764
2765 case MSG_NOTIFY_DATA_CHANGED: {
2766 mBackupManager.dataChanged();
2767 } break;
2768 }
2769 }
2770 }
2771
Svetoslav683914b2015-01-15 14:22:26 -08002772 private final class UpgradeController {
Svet Ganov13701552017-02-23 12:45:17 -08002773 private static final int SETTINGS_VERSION = 142;
Svetoslav683914b2015-01-15 14:22:26 -08002774
2775 private final int mUserId;
2776
2777 public UpgradeController(int userId) {
2778 mUserId = userId;
2779 }
2780
2781 public void upgradeIfNeededLocked() {
2782 // The version of all settings for a user is the same (all users have secure).
2783 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002784 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002785
2786 // Try an update from the current state.
2787 final int oldVersion = secureSettings.getVersionLocked();
2788 final int newVersion = SETTINGS_VERSION;
2789
Svet Ganovc9755bc2015-03-28 13:21:22 -07002790 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002791 if (oldVersion == newVersion) {
2792 return;
2793 }
2794
2795 // Try to upgrade.
2796 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2797
2798 // If upgrade failed start from scratch and upgrade.
2799 if (curVersion != newVersion) {
2800 // Drop state we have for this user.
2801 removeUserStateLocked(mUserId, true);
2802
2803 // Recreate the database.
2804 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2805 SQLiteDatabase database = dbHelper.getWritableDatabase();
2806 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2807
2808 // Migrate the settings for this user.
2809 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2810
2811 // Now upgrade should work fine.
2812 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002813
2814 // Make a note what happened, so we don't wonder why data was lost
2815 String reason = "Settings rebuilt! Current version: "
2816 + curVersion + " while expected: " + newVersion;
2817 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002818 Settings.Global.DATABASE_DOWNGRADE_REASON,
2819 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002820 }
2821
2822 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002823 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002824 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002825 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002826 globalSettings.setVersionLocked(newVersion);
2827 }
2828
2829 // Set the secure settings version.
2830 secureSettings.setVersionLocked(newVersion);
2831
2832 // Set the system settings version.
2833 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002834 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002835 systemSettings.setVersionLocked(newVersion);
2836 }
2837
2838 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002839 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002840 }
2841
2842 private SettingsState getSecureSettingsLocked(int userId) {
2843 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2844 }
2845
Mark Rathjend891f012017-01-19 04:10:37 +00002846 private SettingsState getSsaidSettingsLocked(int userId) {
2847 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2848 }
2849
Svetoslav683914b2015-01-15 14:22:26 -08002850 private SettingsState getSystemSettingsLocked(int userId) {
2851 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2852 }
2853
Jeff Brown503cffc2015-03-26 18:08:51 -07002854 /**
2855 * You must perform all necessary mutations to bring the settings
2856 * for this user from the old to the new version. When you add a new
2857 * upgrade step you *must* update SETTINGS_VERSION.
2858 *
2859 * This is an example of moving a setting from secure to global.
2860 *
2861 * // v119: Example settings changes.
2862 * if (currentVersion == 118) {
2863 * if (userId == UserHandle.USER_OWNER) {
2864 * // Remove from the secure settings.
2865 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2866 * String name = "example_setting_to_move";
2867 * String value = secureSettings.getSetting(name);
2868 * secureSettings.deleteSetting(name);
2869 *
2870 * // Add to the global settings.
2871 * SettingsState globalSettings = getGlobalSettingsLocked();
2872 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2873 * }
2874 *
2875 * // Update the current version.
2876 * currentVersion = 119;
2877 * }
2878 */
Svetoslav683914b2015-01-15 14:22:26 -08002879 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2880 if (DEBUG) {
2881 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2882 + oldVersion + " to version: " + newVersion);
2883 }
2884
Jeff Brown503cffc2015-03-26 18:08:51 -07002885 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002886
John Spurlocke11ae112015-05-11 16:09:03 -04002887 // v119: Reset zen + ringer mode.
2888 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002889 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002890 final SettingsState globalSettings = getGlobalSettingsLocked();
2891 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002892 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2893 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002894 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002895 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2896 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002897 }
2898 currentVersion = 119;
2899 }
2900
Jason Monk27bbb2d2015-03-31 16:46:39 -04002901 // v120: Add double tap to wake setting.
2902 if (currentVersion == 119) {
2903 SettingsState secureSettings = getSecureSettingsLocked(userId);
2904 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2905 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002906 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002907 SettingsState.SYSTEM_PACKAGE_NAME);
2908
2909 currentVersion = 120;
2910 }
2911
Svetoslav7e0683b2015-08-03 16:02:52 -07002912 if (currentVersion == 120) {
2913 // Before 121, we used a different string encoding logic. We just bump the
2914 // version here; SettingsState knows how to handle pre-version 120 files.
2915 currentVersion = 121;
2916 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002917
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002918 if (currentVersion == 121) {
2919 // Version 122: allow OEMs to set a default payment component in resources.
2920 // Note that we only write the default if no default has been set;
2921 // if there is, we just leave the default at whatever it currently is.
2922 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2923 String defaultComponent = (getContext().getResources().getString(
2924 R.string.def_nfc_payment_component));
2925 Setting currentSetting = secureSettings.getSettingLocked(
2926 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2927 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002928 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002929 secureSettings.insertSettingLocked(
2930 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002931 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002932 }
2933 currentVersion = 122;
2934 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002935
2936 if (currentVersion == 122) {
2937 // Version 123: Adding a default value for the ability to add a user from
2938 // the lock screen.
2939 if (userId == UserHandle.USER_SYSTEM) {
2940 final SettingsState globalSettings = getGlobalSettingsLocked();
2941 Setting currentSetting = globalSettings.getSettingLocked(
2942 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002943 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002944 globalSettings.insertSettingLocked(
2945 Settings.Global.ADD_USERS_WHEN_LOCKED,
2946 getContext().getResources().getBoolean(
2947 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002948 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002949 }
2950 }
2951 currentVersion = 123;
2952 }
Bryce Leebd179282015-12-17 19:01:37 -08002953
2954 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002955 final SettingsState globalSettings = getGlobalSettingsLocked();
2956 String defaultDisabledProfiles = (getContext().getResources().getString(
2957 R.string.def_bluetooth_disabled_profiles));
2958 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002959 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002960 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002961 }
2962
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002963 if (currentVersion == 124) {
2964 // Version 124: allow OEMs to set a default value for whether IME should be
2965 // shown when a physical keyboard is connected.
2966 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2967 Setting currentSetting = secureSettings.getSettingLocked(
2968 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002969 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002970 secureSettings.insertSettingLocked(
2971 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2972 getContext().getResources().getBoolean(
2973 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002974 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002975 }
2976 currentVersion = 125;
2977 }
2978
Ruben Brunk98576cf2016-03-07 18:54:28 -08002979 if (currentVersion == 125) {
2980 // Version 125: Allow OEMs to set the default VR service.
2981 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2982
2983 Setting currentSetting = secureSettings.getSettingLocked(
2984 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002985 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002986 ArraySet<ComponentName> l =
2987 SystemConfig.getInstance().getDefaultVrComponents();
2988
2989 if (l != null && !l.isEmpty()) {
2990 StringBuilder b = new StringBuilder();
2991 boolean start = true;
2992 for (ComponentName c : l) {
2993 if (!start) {
2994 b.append(':');
2995 }
2996 b.append(c.flattenToString());
2997 start = false;
2998 }
2999 secureSettings.insertSettingLocked(
3000 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003001 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003002 }
3003
3004 }
3005 currentVersion = 126;
3006 }
3007
Daniel U02ba6122016-04-01 18:41:42 +01003008 if (currentVersion == 126) {
3009 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3010 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3011 if (mUserManager.isManagedProfile(userId)) {
3012 final SettingsState systemSecureSettings =
3013 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3014
3015 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3016 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003017 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003018 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3019 secureSettings.insertSettingLocked(
3020 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003021 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003022 SettingsState.SYSTEM_PACKAGE_NAME);
3023 }
3024
3025 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3026 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003027 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003028 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3029 secureSettings.insertSettingLocked(
3030 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003031 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003032 SettingsState.SYSTEM_PACKAGE_NAME);
3033 }
3034 }
3035 currentVersion = 127;
3036 }
3037
Steven Ngdc20ba62016-04-26 18:19:04 +01003038 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003039 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003040 currentVersion = 128;
3041 }
3042
Julia Reynolds1f721e12016-07-11 08:50:58 -04003043 if (currentVersion == 128) {
3044 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3045 // the new apps are appended to the list of already approved apps.
3046 final SettingsState systemSecureSettings =
3047 getSecureSettingsLocked(userId);
3048
3049 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3050 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3051 String defaultPolicyAccess = getContext().getResources().getString(
3052 com.android.internal.R.string.config_defaultDndAccessPackages);
3053 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3054 if (policyAccess.isNull()) {
3055 systemSecureSettings.insertSettingLocked(
3056 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003057 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003058 SettingsState.SYSTEM_PACKAGE_NAME);
3059 } else {
3060 StringBuilder currentSetting =
3061 new StringBuilder(policyAccess.getValue());
3062 currentSetting.append(":");
3063 currentSetting.append(defaultPolicyAccess);
3064 systemSecureSettings.updateSettingLocked(
3065 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003066 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003067 SettingsState.SYSTEM_PACKAGE_NAME);
3068 }
3069 }
3070
3071 currentVersion = 129;
3072 }
3073
Dan Sandler71f85e92016-07-20 13:46:05 -04003074 if (currentVersion == 129) {
3075 // default longpress timeout changed from 500 to 400. If unchanged from the old
3076 // default, update to the new default.
3077 final SettingsState systemSecureSettings =
3078 getSecureSettingsLocked(userId);
3079 final String oldValue = systemSecureSettings.getSettingLocked(
3080 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3081 if (TextUtils.equals("500", oldValue)) {
3082 systemSecureSettings.insertSettingLocked(
3083 Settings.Secure.LONG_PRESS_TIMEOUT,
3084 String.valueOf(getContext().getResources().getInteger(
3085 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003086 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003087 }
3088 currentVersion = 130;
3089 }
3090
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003091 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003092 // Split Ambient settings
3093 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3094 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3095 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3096
3097 if (dozeExplicitlyDisabled) {
3098 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003099 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003100 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003101 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003102 }
3103 currentVersion = 131;
3104 }
3105
3106 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003107 // Initialize new multi-press timeout to default value
3108 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3109 final String oldValue = systemSecureSettings.getSettingLocked(
3110 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3111 if (TextUtils.equals(null, oldValue)) {
3112 systemSecureSettings.insertSettingLocked(
3113 Settings.Secure.MULTI_PRESS_TIMEOUT,
3114 String.valueOf(getContext().getResources().getInteger(
3115 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003116 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003117 }
3118
Adrian Roos69741a22016-10-21 14:49:17 -07003119 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003120 }
3121
Adrian Roos69741a22016-10-21 14:49:17 -07003122 if (currentVersion == 132) {
3123 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003124 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3125 String defaultSyncParentSounds = (getContext().getResources()
3126 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3127 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003128 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3129 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003130 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003131 }
3132
Adrian Roos69741a22016-10-21 14:49:17 -07003133 if (currentVersion == 133) {
3134 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003135 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3136 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3137 null) {
3138 String defaultEndButtonBehavior = Integer.toString(getContext()
3139 .getResources().getInteger(R.integer.def_end_button_behavior));
3140 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003141 defaultEndButtonBehavior, null, true,
3142 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003143 }
Adrian Roos69741a22016-10-21 14:49:17 -07003144 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003145 }
3146
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003147 if (currentVersion == 134) {
3148 // Remove setting that specifies if magnification values should be preserved.
3149 // This setting defaulted to true and never has a UI.
3150 getSecureSettingsLocked(userId).deleteSettingLocked(
3151 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3152 currentVersion = 135;
3153 }
3154
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003155 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003156 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003157 currentVersion = 136;
3158 }
3159
Mark Rathjend891f012017-01-19 04:10:37 +00003160 if (currentVersion == 136) {
3161 // Version 136: Store legacy SSAID for all apps currently installed on the
3162 // device as first step in migrating SSAID to be unique per application.
3163
3164 final boolean isUpgrade;
3165 try {
3166 isUpgrade = mPackageManager.isUpgrade();
3167 } catch (RemoteException e) {
3168 throw new IllegalStateException("Package manager not available");
3169 }
3170 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3171 // user data or first boot on a new device should use new ssaid generation.
3172 if (isUpgrade) {
3173 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003174 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3175 userId, Settings.Secure.ANDROID_ID);
3176 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3177 || legacySsaidSetting.getValue() == null) {
3178 throw new IllegalStateException("Legacy ssaid not accessible");
3179 }
3180 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003181
3182 // Fill each uid with the legacy ssaid to be backwards compatible.
3183 final List<PackageInfo> packages;
3184 try {
3185 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3186 } catch (RemoteException e) {
3187 throw new IllegalStateException("Package manager not available");
3188 }
3189
3190 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3191 for (PackageInfo info : packages) {
3192 // Check if the UID already has an entry in the table.
3193 final String uid = Integer.toString(info.applicationInfo.uid);
3194 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3195
3196 if (ssaid.isNull() || ssaid.getValue() == null) {
3197 // Android Id doesn't exist for this package so create it.
3198 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3199 info.packageName);
3200 }
3201 }
3202 }
3203
3204 currentVersion = 137;
3205 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003206 if (currentVersion == 137) {
3207 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3208 // default value set to 1. The user can no longer change the value of this
3209 // setting through the UI.
3210 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3211 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003212 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3213 && secureSetting.getSettingLocked(
3214 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3215
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003216 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3217 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003218 // For managed profiles with profile owners, DevicePolicyManagerService
3219 // may want to set the user restriction in this case
3220 secureSetting.insertSettingLocked(
3221 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3222 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003223 }
3224 currentVersion = 138;
3225 }
Mark Rathjend891f012017-01-19 04:10:37 +00003226
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003227 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003228 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003229 currentVersion = 139;
3230 }
3231
Phil Weaver385912e2017-02-10 10:06:56 -08003232 if (currentVersion == 139) {
3233 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3234 // the user can no longer change the value of this setting through the UI.
3235 // Force to true.
3236 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3237 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3238 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3239 currentVersion = 140;
3240 }
3241
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003242 if (currentVersion == 140) {
3243 // Version 141: One-time grant of notification listener privileges
3244 // to packages specified in overlay.
3245 String defaultListenerAccess = getContext().getResources().getString(
3246 com.android.internal.R.string.config_defaultListenerAccessPackages);
3247 if (defaultListenerAccess != null) {
3248 StringBuffer newListeners = new StringBuffer();
3249 for (String whitelistPkg : defaultListenerAccess.split(":")) {
3250 // Gather all notification listener components for candidate pkgs.
3251 Intent serviceIntent =
3252 new Intent(NotificationListenerService.SERVICE_INTERFACE)
3253 .setPackage(whitelistPkg);
3254 List<ResolveInfo> installedServices =
3255 getContext().getPackageManager().queryIntentServicesAsUser(
3256 serviceIntent,
3257 PackageManager.GET_SERVICES
3258 | PackageManager.GET_META_DATA
3259 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3260 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
3261 userId);
3262
3263 for (int i = 0, count = installedServices.size(); i < count; i++) {
3264 ResolveInfo resolveInfo = installedServices.get(i);
3265 ServiceInfo info = resolveInfo.serviceInfo;
3266 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
3267 .equals(info.permission)) {
3268 continue;
3269 }
3270 newListeners.append(":")
3271 .append(info.getComponentName().flattenToString());
3272 }
3273 }
3274
3275 if (newListeners.length() > 0) {
3276 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3277 final Setting existingSetting = secureSetting.getSettingLocked(
3278 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
3279 if (existingSetting.isNull()) {
3280 secureSetting.insertSettingLocked(
3281 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3282 newListeners.toString(), null, true,
3283 SettingsState.SYSTEM_PACKAGE_NAME);
3284 } else {
3285 StringBuilder currentSetting =
3286 new StringBuilder(existingSetting.getValue());
3287 currentSetting.append(newListeners.toString());
3288 secureSetting.updateSettingLocked(
3289 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3290 currentSetting.toString(), null, true,
3291 SettingsState.SYSTEM_PACKAGE_NAME);
3292 }
3293 }
3294 }
3295 currentVersion = 141;
3296 }
3297
Svet Ganov13701552017-02-23 12:45:17 -08003298 if (currentVersion == 141) {
3299 // Version 141: We added the notion of a default and whether the system set
3300 // the setting. This is used for resetting the internal state and we need
3301 // to make sure this value is updated for the existing settings, otherwise
3302 // we would delete system set settings while they should stay unmodified.
3303 SettingsState globalSettings = getGlobalSettingsLocked();
3304 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3305 globalSettings.persistSyncLocked();
3306
3307 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3308 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3309 secureSettings.persistSyncLocked();
3310
3311 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3312 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3313 systemSettings.persistSyncLocked();
3314
3315 currentVersion = 142;
3316 }
3317
Dan Sandler71f85e92016-07-20 13:46:05 -04003318 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003319 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003320 + newVersion + " left it at "
3321 + currentVersion + " instead; this is probably a bug", new Throwable());
3322 if (DEBUG) {
3323 throw new RuntimeException("db upgrade error");
3324 }
3325 }
3326
Jeff Brown503cffc2015-03-26 18:08:51 -07003327 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003328
Jeff Brown503cffc2015-03-26 18:08:51 -07003329 // Return the current version.
3330 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003331 }
3332 }
Svet Ganov13701552017-02-23 12:45:17 -08003333
3334 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3335 List<String> names = settings.getSettingNamesLocked();
3336 final int nameCount = names.size();
3337 for (int i = 0; i < nameCount; i++) {
3338 String name = names.get(i);
3339 Setting setting = settings.getSettingLocked(name);
3340 if (setting.getDefaultValue() == null) {
3341 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3342 setting.getPackageName());
3343 if (systemSet) {
3344 settings.insertSettingLocked(name, setting.getValue(),
3345 setting.getTag(), true, setting.getPackageName());
3346 }
3347 }
3348 }
3349 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003350 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003351}