blob: 1a752f924425ecd1ae661ba959aefeccd14feff8 [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
Makoto Onuki73360ab2017-03-17 11:50:13 -0700251 @GuardedBy("mLock")
252 private Handler mHandler;
253
Svetoslav7ec28e82015-05-20 17:01:10 -0700254 // We have to call in the user manager with no lock held,
255 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800256
Svetoslav7ec28e82015-05-20 17:01:10 -0700257 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700258 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700259
Svet Ganov53a441c2016-04-19 19:38:00 -0700260 public static int makeKey(int type, int userId) {
261 return (type << SETTINGS_TYPE_SHIFT) | userId;
262 }
263
264 public static int getTypeFromKey(int key) {
265 return key >>> SETTINGS_TYPE_SHIFT;
266 }
267
268 public static int getUserIdFromKey(int key) {
269 return key & ~SETTINGS_TYPE_MASK;
270 }
271
272 public static String settingTypeToString(int type) {
273 switch (type) {
274 case SETTINGS_TYPE_GLOBAL: {
275 return "SETTINGS_GLOBAL";
276 }
277 case SETTINGS_TYPE_SECURE: {
278 return "SETTINGS_SECURE";
279 }
280 case SETTINGS_TYPE_SYSTEM: {
281 return "SETTINGS_SYSTEM";
282 }
Mark Rathjend891f012017-01-19 04:10:37 +0000283 case SETTINGS_TYPE_SSAID: {
284 return "SETTINGS_SSAID";
285 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700286 default: {
287 return "UNKNOWN";
288 }
289 }
290 }
291
292 public static String keyToString(int key) {
293 return "Key[user=" + getUserIdFromKey(key) + ";type="
294 + settingTypeToString(getTypeFromKey(key)) + "]";
295 }
296
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700297 @Override
298 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800299 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800300 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700301 mUserManager = UserManager.get(getContext());
302 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700303 mHandlerThread = new HandlerThread(LOG_TAG,
304 Process.THREAD_PRIORITY_BACKGROUND);
305 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700306 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800307 mSettingsRegistry = new SettingsRegistry();
308 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700309 mHandler.post(() -> {
310 registerBroadcastReceivers();
311 startWatchingUserRestrictionChanges();
312 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700313 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 return true;
315 }
316
Svetoslav683914b2015-01-15 14:22:26 -0800317 @Override
318 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700319 final int requestingUserId = getRequestingUserId(args);
320 switch (method) {
321 case Settings.CALL_METHOD_GET_GLOBAL: {
322 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700323 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800324 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700325
326 case Settings.CALL_METHOD_GET_SECURE: {
327 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700328 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700329 }
330
331 case Settings.CALL_METHOD_GET_SYSTEM: {
332 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700333 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700334 }
335
336 case Settings.CALL_METHOD_PUT_GLOBAL: {
337 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800338 String tag = getSettingTag(args);
339 final boolean makeDefault = getSettingMakeDefault(args);
340 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 break;
342 }
343
344 case Settings.CALL_METHOD_PUT_SECURE: {
345 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800346 String tag = getSettingTag(args);
347 final boolean makeDefault = getSettingMakeDefault(args);
348 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700349 break;
350 }
351
352 case Settings.CALL_METHOD_PUT_SYSTEM: {
353 String value = getSettingValue(args);
354 insertSystemSetting(name, value, requestingUserId);
355 break;
356 }
357
Svetoslav Ganove080da92016-12-21 17:10:35 -0800358 case Settings.CALL_METHOD_RESET_GLOBAL: {
359 final int mode = getResetModeEnforcingPermission(args);
360 String tag = getSettingTag(args);
361 resetGlobalSetting(requestingUserId, mode, tag);
362 break;
363 }
364
365 case Settings.CALL_METHOD_RESET_SECURE: {
366 final int mode = getResetModeEnforcingPermission(args);
367 String tag = getSettingTag(args);
368 resetSecureSetting(requestingUserId, mode, tag);
369 break;
370 }
371
Svetoslav7ec28e82015-05-20 17:01:10 -0700372 default: {
373 Slog.w(LOG_TAG, "call() with invalid method: " + method);
374 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700375 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700376
Christopher Tate06efb532012-08-24 15:29:27 -0700377 return null;
378 }
379
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800380 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800381 public String getType(Uri uri) {
382 Arguments args = new Arguments(uri, null, null, true);
383 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384 return "vnd.android.cursor.dir/" + args.table;
385 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700386 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700387 }
388 }
389
390 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800391 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
392 String order) {
393 if (DEBUG) {
394 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 }
396
Svetoslav683914b2015-01-15 14:22:26 -0800397 Arguments args = new Arguments(uri, where, whereArgs, true);
398 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700399
Svetoslav683914b2015-01-15 14:22:26 -0800400 // If a legacy table that is gone, done.
401 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
402 return new MatrixCursor(normalizedProjection, 0);
403 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700404
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 switch (args.table) {
406 case TABLE_GLOBAL: {
407 if (args.name != null) {
408 Setting setting = getGlobalSetting(args.name);
409 return packageSettingForQuery(setting, normalizedProjection);
410 } else {
411 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700412 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700413 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700414
Svetoslav7ec28e82015-05-20 17:01:10 -0700415 case TABLE_SECURE: {
416 final int userId = UserHandle.getCallingUserId();
417 if (args.name != null) {
418 Setting setting = getSecureSetting(args.name, userId);
419 return packageSettingForQuery(setting, normalizedProjection);
420 } else {
421 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800422 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700423 }
Svetoslav683914b2015-01-15 14:22:26 -0800424
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 case TABLE_SYSTEM: {
426 final int userId = UserHandle.getCallingUserId();
427 if (args.name != null) {
428 Setting setting = getSystemSetting(args.name, userId);
429 return packageSettingForQuery(setting, normalizedProjection);
430 } else {
431 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800432 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700433 }
Svetoslav683914b2015-01-15 14:22:26 -0800434
Svetoslav7ec28e82015-05-20 17:01:10 -0700435 default: {
436 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700437 }
438 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700439 }
440
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700441 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800442 public Uri insert(Uri uri, ContentValues values) {
443 if (DEBUG) {
444 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700445 }
446
Svetoslav683914b2015-01-15 14:22:26 -0800447 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700448
Svetoslav683914b2015-01-15 14:22:26 -0800449 // If a legacy table that is gone, done.
450 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 return null;
452 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700453
Svetoslav683914b2015-01-15 14:22:26 -0800454 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700455 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800456 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700457 }
458
Svetoslav683914b2015-01-15 14:22:26 -0800459 String value = values.getAsString(Settings.Secure.VALUE);
460
Svetoslav7ec28e82015-05-20 17:01:10 -0700461 switch (table) {
462 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800463 if (insertGlobalSetting(name, value, null, false,
464 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700465 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700466 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700467 } break;
468
469 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800470 if (insertSecureSetting(name, value, null, false,
471 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700472 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
473 }
474 } break;
475
476 case TABLE_SYSTEM: {
477 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
478 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
479 }
480 } break;
481
482 default: {
483 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700484 }
485 }
486
Svetoslav683914b2015-01-15 14:22:26 -0800487 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700488 }
489
490 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800491 public int bulkInsert(Uri uri, ContentValues[] allValues) {
492 if (DEBUG) {
493 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700495
Svetoslav683914b2015-01-15 14:22:26 -0800496 int insertionCount = 0;
497 final int valuesCount = allValues.length;
498 for (int i = 0; i < valuesCount; i++) {
499 ContentValues values = allValues[i];
500 if (insert(uri, values) != null) {
501 insertionCount++;
502 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700503 }
Svetoslav683914b2015-01-15 14:22:26 -0800504
505 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700506 }
507
508 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800509 public int delete(Uri uri, String where, String[] whereArgs) {
510 if (DEBUG) {
511 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700513
Svetoslav683914b2015-01-15 14:22:26 -0800514 Arguments args = new Arguments(uri, where, whereArgs, false);
515
516 // If a legacy table that is gone, done.
517 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
518 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700519 }
Svetoslav683914b2015-01-15 14:22:26 -0800520
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700521 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800522 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700523 }
Svetoslav683914b2015-01-15 14:22:26 -0800524
Svetoslav7ec28e82015-05-20 17:01:10 -0700525 switch (args.table) {
526 case TABLE_GLOBAL: {
527 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700528 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700529 }
Svetoslav683914b2015-01-15 14:22:26 -0800530
Svetoslav7ec28e82015-05-20 17:01:10 -0700531 case TABLE_SECURE: {
532 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700533 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700534 }
Svetoslav683914b2015-01-15 14:22:26 -0800535
Svetoslav7ec28e82015-05-20 17:01:10 -0700536 case TABLE_SYSTEM: {
537 final int userId = UserHandle.getCallingUserId();
538 return deleteSystemSetting(args.name, userId) ? 1 : 0;
539 }
540
541 default: {
542 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800543 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700544 }
Svetoslav683914b2015-01-15 14:22:26 -0800545 }
546
547 @Override
548 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
549 if (DEBUG) {
550 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700551 }
Svetoslav683914b2015-01-15 14:22:26 -0800552
553 Arguments args = new Arguments(uri, where, whereArgs, false);
554
555 // If a legacy table that is gone, done.
556 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
557 return 0;
558 }
559
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700560 String name = values.getAsString(Settings.Secure.NAME);
561 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800562 return 0;
563 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700564 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800565
Svetoslav7ec28e82015-05-20 17:01:10 -0700566 switch (args.table) {
567 case TABLE_GLOBAL: {
568 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800569 return updateGlobalSetting(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_SECURE: {
574 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800575 return updateSecureSetting(args.name, value, null, false,
576 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700577 }
Svetoslav683914b2015-01-15 14:22:26 -0800578
Svetoslav7ec28e82015-05-20 17:01:10 -0700579 case TABLE_SYSTEM: {
580 final int userId = UserHandle.getCallingUserId();
581 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
582 }
Svetoslav683914b2015-01-15 14:22:26 -0800583
Svetoslav7ec28e82015-05-20 17:01:10 -0700584 default: {
585 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800586 }
587 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700588 }
589
590 @Override
591 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100592 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
593 if (userId != UserHandle.getCallingUserId()) {
594 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
595 "Access files from the settings of another user");
596 }
597 uri = ContentProvider.getUriWithoutUserId(uri);
598
Andre Lago3fa139c2016-08-04 13:53:44 +0100599 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700600 final String cacheName;
601 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100602 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700603 cacheName = Settings.System.RINGTONE_CACHE;
604 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100605 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700606 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
607 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100608 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700609 cacheName = Settings.System.ALARM_ALERT_CACHE;
610 } else {
611 throw new FileNotFoundException("Direct file access no longer supported; "
612 + "ringtone playback is available through android.media.Ringtone");
613 }
614
Andre Lago3fa139c2016-08-04 13:53:44 +0100615 int actualCacheOwner;
616 // Redirect cache to parent if ringtone setting is owned by profile parent
617 synchronized (mLock) {
618 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
619 cacheRingtoneSetting);
620 }
621 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700622 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
623 }
624
625 private File getRingtoneCacheDir(int userId) {
626 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
627 cacheDir.mkdir();
628 SELinux.restorecon(cacheDir);
629 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700630 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800631
Eugene Suslad72c3972016-12-27 15:49:30 -0800632 /**
633 * Dump all settings as a proto buf.
634 *
635 * @param fd The file to dump to
636 */
637 void dumpProto(@NonNull FileDescriptor fd) {
638 ProtoOutputStream proto = new ProtoOutputStream(fd);
639
640 synchronized (mLock) {
641 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
642
643 }
644
645 proto.flush();
646 }
647
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700648 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800649 synchronized (mLock) {
650 final long identity = Binder.clearCallingIdentity();
651 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700652 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800653 final int userCount = users.size();
654 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700655 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800656 }
657 } finally {
658 Binder.restoreCallingIdentity(identity);
659 }
660 }
661 }
662
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700663 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700664 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800665 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700666 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
667 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700668 if (globalSettings != null) {
669 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800670 pw.println();
671 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700672 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800673 }
674
675 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700676 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
677 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700678 if (secureSettings != null) {
679 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800680 pw.println();
681 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700682 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700683
Svetoslavb505ccc2015-02-17 12:41:04 -0800684 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700685 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
686 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700687 if (systemSettings != null) {
688 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800689 pw.println();
690 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700691 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800692 }
693
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700694 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
695 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800696
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700697 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800698
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700699 for (int i = 0; i < nameCount; i++) {
700 String name = names.get(i);
701 Setting setting = settingsState.getSettingLocked(name);
702 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
703 pw.print(" name:"); pw.print(toDumpString(name));
704 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800705 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700706 }
707 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800708 if (setting.getDefaultValue() != null) {
709 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800710 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800711 }
712 if (setting.getTag() != null) {
713 pw.print(" tag:"); pw.print(setting.getTag());
714 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800715 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700716 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800717 }
718
Svetoslav7e0683b2015-08-03 16:02:52 -0700719 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700720 if (s != null) {
721 return s;
722 }
723 return "{null}";
724 }
725
Svetoslav683914b2015-01-15 14:22:26 -0800726 private void registerBroadcastReceivers() {
727 IntentFilter userFilter = new IntentFilter();
728 userFilter.addAction(Intent.ACTION_USER_REMOVED);
729 userFilter.addAction(Intent.ACTION_USER_STOPPED);
730
731 getContext().registerReceiver(new BroadcastReceiver() {
732 @Override
733 public void onReceive(Context context, Intent intent) {
734 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700735 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800736
737 switch (intent.getAction()) {
738 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700739 synchronized (mLock) {
740 mSettingsRegistry.removeUserStateLocked(userId, true);
741 }
Svetoslav683914b2015-01-15 14:22:26 -0800742 } break;
743
744 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700745 synchronized (mLock) {
746 mSettingsRegistry.removeUserStateLocked(userId, false);
747 }
Svetoslav683914b2015-01-15 14:22:26 -0800748 } break;
749 }
750 }
751 }, userFilter);
752
753 PackageMonitor monitor = new PackageMonitor() {
754 @Override
755 public void onPackageRemoved(String packageName, int uid) {
756 synchronized (mLock) {
757 mSettingsRegistry.onPackageRemovedLocked(packageName,
758 UserHandle.getUserId(uid));
759 }
760 }
Mark Rathjend891f012017-01-19 04:10:37 +0000761
762 @Override
763 public void onUidRemoved(int uid) {
764 synchronized (mLock) {
765 mSettingsRegistry.onUidRemovedLocked(uid);
766 }
767 }
Svetoslav683914b2015-01-15 14:22:26 -0800768 };
769
770 // package changes
771 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
772 UserHandle.ALL, true);
773 }
774
Svet Ganov53a441c2016-04-19 19:38:00 -0700775 private void startWatchingUserRestrictionChanges() {
776 // TODO: The current design of settings looking different based on user restrictions
777 // should be reworked to keep them separate and system code should check the setting
778 // first followed by checking the user restriction before performing an operation.
779 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
780 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
781 Bundle prevRestrictions) -> {
782 // We are changing the settings affected by restrictions to their current
783 // value with a forced update to ensure that all cross profile dependencies
784 // are taken into account. Also make sure the settings update to.. the same
785 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800786 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
787 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700788 final long identity = Binder.clearCallingIdentity();
789 try {
790 synchronized (mLock) {
791 Setting setting = getSecureSetting(
792 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
793 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800794 setting != null ? setting.getValue() : null, null,
795 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700796 }
797 } finally {
798 Binder.restoreCallingIdentity(identity);
799 }
800 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800801 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
802 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 final long identity = Binder.clearCallingIdentity();
804 try {
805 synchronized (mLock) {
806 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800807 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700808 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800809 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700810 }
811 } finally {
812 Binder.restoreCallingIdentity(identity);
813 }
814 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
816 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 final long identity = Binder.clearCallingIdentity();
818 try {
819 synchronized (mLock) {
820 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800821 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700822 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800823 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700824 }
825 } finally {
826 Binder.restoreCallingIdentity(identity);
827 }
828 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800829 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
830 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 final long identity = Binder.clearCallingIdentity();
832 try {
833 synchronized (mLock) {
834 Setting enable = getGlobalSetting(
835 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800836 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700837 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800838 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700839 Setting include = getGlobalSetting(
840 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800841 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700842 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800843 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700844 }
845 } finally {
846 Binder.restoreCallingIdentity(identity);
847 }
848 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800849 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
850 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700851 final long identity = Binder.clearCallingIdentity();
852 try {
853 synchronized (mLock) {
854 Setting setting = getGlobalSetting(
855 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700857 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800858 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700859 }
860 } finally {
861 Binder.restoreCallingIdentity(identity);
862 }
863 }
864 });
865 }
866
Svetoslav7ec28e82015-05-20 17:01:10 -0700867 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800868 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700869 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800870 }
871
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 synchronized (mLock) {
873 // Get the settings.
874 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700875 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800876
Chad Brubaker97bccee2017-01-05 15:51:41 -0800877 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
878 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800879
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800881
Svetoslav7ec28e82015-05-20 17:01:10 -0700882 String[] normalizedProjection = normalizeProjection(projection);
883 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 // Anyone can get the global settings, so no security checks.
886 for (int i = 0; i < nameCount; i++) {
887 String name = names.get(i);
888 Setting setting = settingsState.getSettingLocked(name);
889 appendSettingToCursor(result, setting);
890 }
891
892 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800893 }
Svetoslav683914b2015-01-15 14:22:26 -0800894 }
895
Svetoslav7ec28e82015-05-20 17:01:10 -0700896 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800897 if (DEBUG) {
898 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
899 }
900
Chad Brubaker97bccee2017-01-05 15:51:41 -0800901 // Ensure the caller can access the setting.
902 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
903
Svetoslav683914b2015-01-15 14:22:26 -0800904 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700905 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700906 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700907 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800908 }
Svetoslav683914b2015-01-15 14:22:26 -0800909 }
910
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 private boolean updateGlobalSetting(String name, String value, String tag,
912 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800913 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800914 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
915 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
916 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800917 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
919 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800920 }
921
Svetoslav Ganove080da92016-12-21 17:10:35 -0800922 private boolean insertGlobalSetting(String name, String value, String tag,
923 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800925 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
926 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
927 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700928 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
930 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700931 }
932
Svet Ganov53a441c2016-04-19 19:38:00 -0700933 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800934 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800935 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
936 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800937 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800938 return mutateGlobalSetting(name, null, null, false, requestingUserId,
939 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800940 }
941
Svetoslav Ganove080da92016-12-21 17:10:35 -0800942 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
943 if (DEBUG) {
944 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
945 + mode + ", " + tag + ")");
946 }
947 mutateGlobalSetting(null, null, tag, false, requestingUserId,
948 MUTATION_OPERATION_RESET, false, mode);
949 }
950
951 private boolean mutateGlobalSetting(String name, String value, String tag,
952 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
953 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800954 // Make sure the caller can change the settings - treated as secure.
955 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
956
Svetoslav683914b2015-01-15 14:22:26 -0800957 // Resolve the userId on whose behalf the call is made.
958 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
959
Makoto Onuki28da2e32015-11-20 11:30:44 -0800960 // If this is a setting that is currently restricted for this user, do not allow
961 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800962 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100963 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800964 return false;
965 }
966
967 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700968 synchronized (mLock) {
969 switch (operation) {
970 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800971 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
972 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800973 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700974 }
Svetoslav683914b2015-01-15 14:22:26 -0800975
Svetoslav7ec28e82015-05-20 17:01:10 -0700976 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700977 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800978 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700979 }
Svetoslav683914b2015-01-15 14:22:26 -0800980
Svetoslav7ec28e82015-05-20 17:01:10 -0700981 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800982 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
983 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800984 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800986
987 case MUTATION_OPERATION_RESET: {
988 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
989 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
990 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800991 }
992 }
993
994 return false;
995 }
996
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800998 if (DEBUG) {
999 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1000 }
1001
1002 // Resolve the userId on whose behalf the call is made.
1003 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1004
Svetoslav7ec28e82015-05-20 17:01:10 -07001005 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001006 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001007
Svetoslav7ec28e82015-05-20 17:01:10 -07001008 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001009
Svetoslav7ec28e82015-05-20 17:01:10 -07001010 String[] normalizedProjection = normalizeProjection(projection);
1011 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001012
Svetoslav7ec28e82015-05-20 17:01:10 -07001013 for (int i = 0; i < nameCount; i++) {
1014 String name = names.get(i);
1015 // Determine the owning user as some profile settings are cloned from the parent.
1016 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1017 name);
Svetoslav683914b2015-01-15 14:22:26 -08001018
Alex Klyubin1991f572017-03-03 14:08:36 -08001019 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1020 // This caller is not permitted to access this setting. Pretend the setting
1021 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001022 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001023 }
Svetoslav683914b2015-01-15 14:22:26 -08001024
Mark Rathjen7599f132017-01-23 14:15:54 -08001025 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001026 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1027 final Setting setting;
1028 if (isNewSsaidSetting(name)) {
1029 setting = getSsaidSettingLocked(owningUserId);
1030 } else {
1031 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1032 name);
1033 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001034 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001035 }
1036
Svetoslav7ec28e82015-05-20 17:01:10 -07001037 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001038 }
Svetoslav683914b2015-01-15 14:22:26 -08001039 }
1040
Svetoslav7ec28e82015-05-20 17:01:10 -07001041 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001042 if (DEBUG) {
1043 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1044 }
1045
1046 // Resolve the userId on whose behalf the call is made.
1047 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1048
Chad Brubaker97bccee2017-01-05 15:51:41 -08001049 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001050 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001051
Svetoslav683914b2015-01-15 14:22:26 -08001052 // Determine the owning user as some profile settings are cloned from the parent.
1053 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1054
Alex Klyubin1991f572017-03-03 14:08:36 -08001055 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1056 // This caller is not permitted to access this setting. Pretend the setting doesn't
1057 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001058 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1059 owningUserId);
1060 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001061 }
1062
1063 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001064 synchronized (mLock) {
Mark Rathjen7599f132017-01-23 14:15:54 -08001065 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001066 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1067 if (isNewSsaidSetting(name)) {
1068 return getSsaidSettingLocked(owningUserId);
1069 }
1070
Svet Ganov53a441c2016-04-19 19:38:00 -07001071 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001072 owningUserId, name);
1073 }
Svetoslav683914b2015-01-15 14:22:26 -08001074 }
1075
Mark Rathjend891f012017-01-19 04:10:37 +00001076 private boolean isNewSsaidSetting(String name) {
1077 return Settings.Secure.ANDROID_ID.equals(name)
1078 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1079 }
1080
1081 private Setting getSsaidSettingLocked(int owningUserId) {
1082 // Get uid of caller (key) used to store ssaid value
1083 String name = Integer.toString(
1084 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1085
1086 if (DEBUG) {
1087 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1088 }
1089
1090 // Retrieve the ssaid from the table if present.
1091 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1092 name);
1093
1094 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001095 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001096 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1097 }
1098
1099 return ssaid;
1100 }
1101
Svetoslav Ganove080da92016-12-21 17:10:35 -08001102 private boolean insertSecureSetting(String name, String value, String tag,
1103 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001104 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001105 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001106 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1107 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001108 }
1109
Svetoslav Ganove080da92016-12-21 17:10:35 -08001110 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1111 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001112 }
1113
Svet Ganov53a441c2016-04-19 19:38:00 -07001114 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001115 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001116 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1117 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001118 }
1119
Svetoslav Ganove080da92016-12-21 17:10:35 -08001120 return mutateSecureSetting(name, null, null, false, requestingUserId,
1121 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001122 }
1123
Svetoslav Ganove080da92016-12-21 17:10:35 -08001124 private boolean updateSecureSetting(String name, String value, String tag,
1125 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001126 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001127 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001128 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1129 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001130 }
1131
Svetoslav Ganove080da92016-12-21 17:10:35 -08001132 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1133 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001134 }
1135
Svetoslav Ganove080da92016-12-21 17:10:35 -08001136 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1137 if (DEBUG) {
1138 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1139 + mode + ", " + tag + ")");
1140 }
1141
1142 mutateSecureSetting(null, null, tag, false, requestingUserId,
1143 MUTATION_OPERATION_RESET, false, mode);
1144 }
1145
1146 private boolean mutateSecureSetting(String name, String value, String tag,
1147 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1148 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001149 // Make sure the caller can change the settings.
1150 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1151
Svetoslav683914b2015-01-15 14:22:26 -08001152 // Resolve the userId on whose behalf the call is made.
1153 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1154
Makoto Onuki28da2e32015-11-20 11:30:44 -08001155 // If this is a setting that is currently restricted for this user, do not allow
1156 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001157 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001158 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001159 return false;
1160 }
1161
1162 // Determine the owning user as some profile settings are cloned from the parent.
1163 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1164
1165 // Only the owning user can change the setting.
1166 if (owningUserId != callingUserId) {
1167 return false;
1168 }
1169
1170 // Special cases for location providers (sigh).
1171 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001172 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1173 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001174 }
1175
1176 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001177 synchronized (mLock) {
1178 switch (operation) {
1179 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001180 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001181 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001182 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001183 }
Svetoslav683914b2015-01-15 14:22:26 -08001184
Svetoslav7ec28e82015-05-20 17:01:10 -07001185 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001186 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001187 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001188 }
Svetoslav683914b2015-01-15 14:22:26 -08001189
Svetoslav7ec28e82015-05-20 17:01:10 -07001190 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001191 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001192 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001193 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001194 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001195
1196 case MUTATION_OPERATION_RESET: {
1197 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1198 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1199 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001200 }
1201 }
1202
1203 return false;
1204 }
1205
Svetoslav7ec28e82015-05-20 17:01:10 -07001206 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001207 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001208 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001209 }
1210
1211 // Resolve the userId on whose behalf the call is made.
1212 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1213
Svetoslav7ec28e82015-05-20 17:01:10 -07001214 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001215 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001216
Svetoslav7ec28e82015-05-20 17:01:10 -07001217 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001218
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 String[] normalizedProjection = normalizeProjection(projection);
1220 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001221
Svetoslav7ec28e82015-05-20 17:01:10 -07001222 for (int i = 0; i < nameCount; i++) {
1223 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001224
Svetoslav7ec28e82015-05-20 17:01:10 -07001225 // Determine the owning user as some profile settings are cloned from the parent.
1226 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1227 name);
Svetoslav683914b2015-01-15 14:22:26 -08001228
Svetoslav7ec28e82015-05-20 17:01:10 -07001229 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001230 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001231 appendSettingToCursor(result, setting);
1232 }
1233
1234 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001235 }
Svetoslav683914b2015-01-15 14:22:26 -08001236 }
1237
Svetoslav7ec28e82015-05-20 17:01:10 -07001238 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001239 if (DEBUG) {
1240 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1241 }
1242
1243 // Resolve the userId on whose behalf the call is made.
1244 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1245
Chad Brubaker97bccee2017-01-05 15:51:41 -08001246 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001247 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001248
Svetoslav683914b2015-01-15 14:22:26 -08001249 // Determine the owning user as some profile settings are cloned from the parent.
1250 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1251
1252 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001253 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001254 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 }
Svetoslav683914b2015-01-15 14:22:26 -08001256 }
1257
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001259 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001260 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001261 + requestingUserId + ")");
1262 }
1263
Svetoslav7ec28e82015-05-20 17:01:10 -07001264 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001265 }
1266
Svetoslav7ec28e82015-05-20 17:01:10 -07001267 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001268 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001269 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001270 }
1271
Svetoslav7ec28e82015-05-20 17:01:10 -07001272 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001273 }
1274
Svetoslav7ec28e82015-05-20 17:01:10 -07001275 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001276 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001277 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001278 + requestingUserId + ")");
1279 }
1280
Svetoslav7ec28e82015-05-20 17:01:10 -07001281 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001282 }
1283
Svetoslav7ec28e82015-05-20 17:01:10 -07001284 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001285 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001286 if (!hasWriteSecureSettingsPermission()) {
1287 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1288 // operation is allowed for the calling package through appops.
1289 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1290 Binder.getCallingUid(), getCallingPackage(), true)) {
1291 return false;
1292 }
Svetoslav683914b2015-01-15 14:22:26 -08001293 }
1294
Svetoslav683914b2015-01-15 14:22:26 -08001295 // Resolve the userId on whose behalf the call is made.
1296 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1297
Svetoslavd8d25e02015-11-20 13:09:26 -08001298 // Enforce what the calling package can mutate the system settings.
1299 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1300
Svetoslav683914b2015-01-15 14:22:26 -08001301 // Determine the owning user as some profile settings are cloned from the parent.
1302 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1303
1304 // Only the owning user id can change the setting.
1305 if (owningUserId != callingUserId) {
1306 return false;
1307 }
1308
Jeff Sharkey413573a2016-02-22 17:52:45 -07001309 // Invalidate any relevant cache files
1310 String cacheName = null;
1311 if (Settings.System.RINGTONE.equals(name)) {
1312 cacheName = Settings.System.RINGTONE_CACHE;
1313 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1314 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1315 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1316 cacheName = Settings.System.ALARM_ALERT_CACHE;
1317 }
1318 if (cacheName != null) {
1319 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001320 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001321 cacheFile.delete();
1322 }
1323
Svetoslav683914b2015-01-15 14:22:26 -08001324 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001325 synchronized (mLock) {
1326 switch (operation) {
1327 case MUTATION_OPERATION_INSERT: {
1328 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001329 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001330 owningUserId, name, value, null, false, getCallingPackage(),
1331 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001332 }
1333
1334 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001335 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001336 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001337 }
1338
1339 case MUTATION_OPERATION_UPDATE: {
1340 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001341 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001342 owningUserId, name, value, null, false, getCallingPackage(),
1343 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001344 }
Svetoslav683914b2015-01-15 14:22:26 -08001345 }
1346
Svetoslav7ec28e82015-05-20 17:01:10 -07001347 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001348 }
Svetoslav683914b2015-01-15 14:22:26 -08001349 }
1350
Billy Lau6ad2d662015-07-18 00:26:58 +01001351 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001352 // Write secure settings is a more protected permission. If caller has it we are good.
1353 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1354 == PackageManager.PERMISSION_GRANTED) {
1355 return true;
1356 }
1357
Svetoslavf41334b2015-06-23 12:06:03 -07001358 return false;
1359 }
1360
Svetoslav683914b2015-01-15 14:22:26 -08001361 private void validateSystemSettingValue(String name, String value) {
1362 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1363 if (validator != null && !validator.validate(value)) {
1364 throw new IllegalArgumentException("Invalid value: " + value
1365 + " for setting: " + name);
1366 }
1367 }
1368
Alex Klyubin1991f572017-03-03 14:08:36 -08001369 /**
1370 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1371 */
1372 private boolean isSecureSettingAccessible(String name, int callingUserId,
1373 int owningUserId) {
1374 // Special case for location (sigh).
1375 // This check is not inside the name-based checks below because this method performs checks
1376 // only if the calling user ID is not the same as the owning user ID.
1377 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1378 return false;
1379 }
1380
1381 switch (name) {
1382 case "bluetooth_address":
1383 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1384 // address in this secure setting. Secure settings can normally be read by any app,
1385 // which thus enables them to bypass the recently introduced restrictions on access
1386 // to device identifiers.
1387 // To mitigate this we make this setting available only to callers privileged to see
1388 // this device's MAC addresses, same as through public API
1389 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1390 return getContext().checkCallingOrSelfPermission(
1391 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1392 default:
1393 return true;
1394 }
1395 }
1396
Svetoslav683914b2015-01-15 14:22:26 -08001397 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1398 int owningUserId) {
1399 // Optimization - location providers are restricted only for managed profiles.
1400 if (callingUserId == owningUserId) {
1401 return false;
1402 }
1403 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1404 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1405 new UserHandle(callingUserId))) {
1406 return true;
1407 }
1408 return false;
1409 }
1410
Makoto Onuki28da2e32015-11-20 11:30:44 -08001411 /**
1412 * Checks whether changing a setting to a value is prohibited by the corresponding user
1413 * restriction.
1414 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001415 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1416 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001417 *
1418 * @return true if the change is prohibited, false if the change is allowed.
1419 */
1420 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001421 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001422 String restriction;
1423 switch (setting) {
1424 case Settings.Secure.LOCATION_MODE:
1425 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1426 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1427 // here normally, but we still protect it here from a direct provider write.
1428 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1429 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1430 break;
1431
1432 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1433 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1434 // a provider, which should be allowed even if the user restriction is set.
1435 if (value != null && value.startsWith("-")) return false;
1436 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1437 break;
1438
1439 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1440 if ("0".equals(value)) return false;
1441 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1442 break;
1443
1444 case Settings.Global.ADB_ENABLED:
1445 if ("0".equals(value)) return false;
1446 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1447 break;
1448
1449 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1450 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1451 if ("1".equals(value)) return false;
1452 restriction = UserManager.ENSURE_VERIFY_APPS;
1453 break;
1454
1455 case Settings.Global.PREFERRED_NETWORK_MODE:
1456 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1457 break;
1458
Victor Chang9c7b7062016-07-12 23:47:29 +01001459 case Settings.Secure.ALWAYS_ON_VPN_APP:
1460 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1461 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001462 final int appId = UserHandle.getAppId(callingUid);
1463 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001464 return false;
1465 }
1466 restriction = UserManager.DISALLOW_CONFIG_VPN;
1467 break;
1468
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001469 case Settings.Global.SAFE_BOOT_DISALLOWED:
1470 if ("1".equals(value)) return false;
1471 restriction = UserManager.DISALLOW_SAFE_BOOT;
1472 break;
1473
Makoto Onuki28da2e32015-11-20 11:30:44 -08001474 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001475 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001476 if ("0".equals(value)) return false;
1477 restriction = UserManager.DISALLOW_DATA_ROAMING;
1478 break;
1479 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001480 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001481 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001482
1483 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001484 }
1485
1486 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1487 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1488 }
1489
1490 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001491 final int parentId;
1492 // Resolves dependency if setting has a dependency and the calling user has a parent
1493 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1494 && (parentId = getGroupParentLocked(userId)) != userId) {
1495 // The setting has a dependency and the profile has a parent
1496 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001497 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1498 final long token = Binder.clearCallingIdentity();
1499 try {
1500 Setting settingObj = getSecureSetting(dependency, userId);
1501 if (settingObj != null && settingObj.getValue().equals("1")) {
1502 return parentId;
1503 }
1504 } finally {
1505 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001506 }
1507 }
Svetoslav683914b2015-01-15 14:22:26 -08001508 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1509 }
1510
1511 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1512 final int parentId = getGroupParentLocked(userId);
1513 if (parentId != userId && keys.contains(name)) {
1514 return parentId;
1515 }
1516 return userId;
1517 }
1518
Svetoslavf41334b2015-06-23 12:06:03 -07001519 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001520 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001521 // System/root/shell can mutate whatever secure settings they want.
1522 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001523 final int appId = UserHandle.getAppId(callingUid);
1524 if (appId == android.os.Process.SYSTEM_UID
1525 || appId == Process.SHELL_UID
1526 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001527 return;
1528 }
1529
1530 switch (operation) {
1531 case MUTATION_OPERATION_INSERT:
1532 // Insert updates.
1533 case MUTATION_OPERATION_UPDATE: {
1534 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1535 return;
1536 }
1537
1538 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001539 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001540
1541 // Privileged apps can do whatever they want.
1542 if ((packageInfo.applicationInfo.privateFlags
1543 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1544 return;
1545 }
1546
1547 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1548 packageInfo.applicationInfo.targetSdkVersion, name);
1549 } break;
1550
1551 case MUTATION_OPERATION_DELETE: {
1552 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1553 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1554 throw new IllegalArgumentException("You cannot delete system defined"
1555 + " secure settings.");
1556 }
1557
1558 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001559 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001560
1561 // Privileged apps can do whatever they want.
1562 if ((packageInfo.applicationInfo.privateFlags &
1563 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1564 return;
1565 }
1566
1567 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1568 packageInfo.applicationInfo.targetSdkVersion, name);
1569 } break;
1570 }
1571 }
1572
Todd Kennedybe0b8892017-02-15 14:13:52 -08001573 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001574 switch (settingsType) {
1575 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001576 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001577 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001578 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001579 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001580 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001581 default:
1582 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1583 }
1584 }
1585
1586 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001587 boolean instantApp;
1588 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1589 instantApp = false;
1590 } else {
1591 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1592 instantApp = ai.isInstantApp();
1593 }
1594 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001595 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001596 } else {
1597 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1598 }
1599 }
1600
1601 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1602 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1603 return;
1604 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001605 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001606 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001607 return;
1608 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08001609 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001610 throw new SecurityException("Setting " + settingName + " is not accessible from"
1611 + " ephemeral package " + getCallingPackage());
1612 }
1613 }
1614
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001615 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1616 // We always use the callingUid for this lookup. This means that if hypothetically an
1617 // app was installed in user A with cross user and in user B as an Instant App
1618 // the app in A would be able to see all the settings in user B. However since cross
1619 // user is a system permission and the app must be uninstalled in B and then installed as
1620 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001621 ApplicationInfo ai = null;
1622 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001623 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1624 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001625 } catch (RemoteException ignored) {
1626 }
1627 if (ai == null) {
1628 throw new IllegalStateException("Failed to lookup info for package "
1629 + getCallingPackage());
1630 }
1631 return ai;
1632 }
1633
Xiaohui Chen43765b72015-08-31 10:57:33 -07001634 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001635 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001636 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1637 getCallingPackage(), 0, userId);
1638 if (packageInfo != null) {
1639 return packageInfo;
1640 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001641 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001642 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001643 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001644 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001645 }
1646
1647 private int getGroupParentLocked(int userId) {
1648 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001649 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001650 return userId;
1651 }
1652 // We are in the same process with the user manager and the returned
1653 // user info is a cached instance, so just look up instead of cache.
1654 final long identity = Binder.clearCallingIdentity();
1655 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001656 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001657 UserInfo userInfo = mUserManager.getProfileParent(userId);
1658 return (userInfo != null) ? userInfo.id : userId;
1659 } finally {
1660 Binder.restoreCallingIdentity(identity);
1661 }
1662 }
1663
Svetoslav683914b2015-01-15 14:22:26 -08001664 private void enforceWritePermission(String permission) {
1665 if (getContext().checkCallingOrSelfPermission(permission)
1666 != PackageManager.PERMISSION_GRANTED) {
1667 throw new SecurityException("Permission denial: writing to settings requires:"
1668 + permission);
1669 }
1670 }
1671
1672 /*
1673 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1674 * This setting contains a list of the currently enabled location providers.
1675 * But helper functions in android.providers.Settings can enable or disable
1676 * a single provider by using a "+" or "-" prefix before the provider name.
1677 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001678 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1679 * is set, the said method will only allow values with the "-" prefix.
1680 *
Svetoslav683914b2015-01-15 14:22:26 -08001681 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001682 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001683 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1684 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001685 if (TextUtils.isEmpty(value)) {
1686 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001687 }
1688
Svetoslav683914b2015-01-15 14:22:26 -08001689 final char prefix = value.charAt(0);
1690 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001691 if (forceNotify) {
1692 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1693 mSettingsRegistry.notifyForSettingsChange(key,
1694 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1695 }
Svetoslav683914b2015-01-15 14:22:26 -08001696 return false;
1697 }
1698
1699 // skip prefix
1700 value = value.substring(1);
1701
Svetoslav7ec28e82015-05-20 17:01:10 -07001702 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001703 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001704 if (settingValue == null) {
1705 return false;
1706 }
Svetoslav683914b2015-01-15 14:22:26 -08001707
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001708 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001709
1710 int index = oldProviders.indexOf(value);
1711 int end = index + value.length();
1712
1713 // check for commas to avoid matching on partial string
1714 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1715 index = -1;
1716 }
1717
1718 // check for commas to avoid matching on partial string
1719 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1720 index = -1;
1721 }
1722
1723 String newProviders;
1724
1725 if (prefix == '+' && index < 0) {
1726 // append the provider to the list if not present
1727 if (oldProviders.length() == 0) {
1728 newProviders = value;
1729 } else {
1730 newProviders = oldProviders + ',' + value;
1731 }
1732 } else if (prefix == '-' && index >= 0) {
1733 // remove the provider from the list if present
1734 // remove leading or trailing comma
1735 if (index > 0) {
1736 index--;
1737 } else if (end < oldProviders.length()) {
1738 end++;
1739 }
1740
1741 newProviders = oldProviders.substring(0, index);
1742 if (end < oldProviders.length()) {
1743 newProviders += oldProviders.substring(end);
1744 }
1745 } else {
1746 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001747 if (forceNotify) {
1748 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1749 mSettingsRegistry.notifyForSettingsChange(key,
1750 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1751 }
Svetoslav683914b2015-01-15 14:22:26 -08001752 return false;
1753 }
1754
Svet Ganov53a441c2016-04-19 19:38:00 -07001755 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001756 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001757 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001758 }
1759
Svetoslav683914b2015-01-15 14:22:26 -08001760 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1761 int targetSdkVersion, String name) {
1762 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1763 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1764 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1765 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1766 + " This will soon become an error.");
1767 } else {
1768 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1769 + " This will soon become an error.");
1770 }
1771 } else {
1772 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1773 throw new IllegalArgumentException("You cannot change private secure settings.");
1774 } else {
1775 throw new IllegalArgumentException("You cannot keep your settings in"
1776 + " the secure settings.");
1777 }
1778 }
1779 }
1780
1781 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1782 if (requestingUserId == UserHandle.getCallingUserId()) {
1783 return requestingUserId;
1784 }
1785 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1786 Binder.getCallingUid(), requestingUserId, false, true,
1787 "get/set setting for user", null);
1788 }
1789
Svet Ganov53a441c2016-04-19 19:38:00 -07001790 private Bundle packageValueForCallResult(Setting setting,
1791 boolean trackingGeneration) {
1792 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001793 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001794 return NULL_SETTING_BUNDLE;
1795 }
1796 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001797 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001798 Bundle result = new Bundle();
1799 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001800 !setting.isNull() ? setting.getValue() : null);
1801 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001802 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001803 }
1804
1805 private static int getRequestingUserId(Bundle args) {
1806 final int callingUserId = UserHandle.getCallingUserId();
1807 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1808 : callingUserId;
1809 }
1810
Svet Ganov53a441c2016-04-19 19:38:00 -07001811 private boolean isTrackingGeneration(Bundle args) {
1812 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1813 }
1814
Svetoslav683914b2015-01-15 14:22:26 -08001815 private static String getSettingValue(Bundle args) {
1816 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1817 }
1818
Svetoslav Ganove080da92016-12-21 17:10:35 -08001819 private static String getSettingTag(Bundle args) {
1820 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1821 }
1822
1823 private static boolean getSettingMakeDefault(Bundle args) {
1824 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1825 }
1826
1827 private static int getResetModeEnforcingPermission(Bundle args) {
1828 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1829 switch (mode) {
1830 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1831 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1832 throw new SecurityException("Only system, shell/root on a "
1833 + "debuggable build can reset to untrusted defaults");
1834 }
1835 return mode;
1836 }
1837 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1838 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1839 throw new SecurityException("Only system, shell/root on a "
1840 + "debuggable build can reset untrusted changes");
1841 }
1842 return mode;
1843 }
1844 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1845 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1846 throw new SecurityException("Only system, shell/root on a "
1847 + "debuggable build can reset to trusted defaults");
1848 }
1849 return mode;
1850 }
1851 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1852 return mode;
1853 }
1854 }
1855 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1856 }
1857
1858 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1859 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1860 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1861 && (appId == SHELL_UID || appId == ROOT_UID));
1862 }
1863
Svetoslav683914b2015-01-15 14:22:26 -08001864 private static String getValidTableOrThrow(Uri uri) {
1865 if (uri.getPathSegments().size() > 0) {
1866 String table = uri.getPathSegments().get(0);
1867 if (DatabaseHelper.isValidTable(table)) {
1868 return table;
1869 }
1870 throw new IllegalArgumentException("Bad root path: " + table);
1871 }
1872 throw new IllegalArgumentException("Invalid URI:" + uri);
1873 }
1874
1875 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001876 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001877 return new MatrixCursor(projection, 0);
1878 }
1879 MatrixCursor cursor = new MatrixCursor(projection, 1);
1880 appendSettingToCursor(cursor, setting);
1881 return cursor;
1882 }
1883
1884 private static String[] normalizeProjection(String[] projection) {
1885 if (projection == null) {
1886 return ALL_COLUMNS;
1887 }
1888
1889 final int columnCount = projection.length;
1890 for (int i = 0; i < columnCount; i++) {
1891 String column = projection[i];
1892 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1893 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001894 }
1895 }
1896
Svetoslav683914b2015-01-15 14:22:26 -08001897 return projection;
1898 }
1899
1900 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001901 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001902 return;
1903 }
Svetoslav683914b2015-01-15 14:22:26 -08001904 final int columnCount = cursor.getColumnCount();
1905
1906 String[] values = new String[columnCount];
1907
1908 for (int i = 0; i < columnCount; i++) {
1909 String column = cursor.getColumnName(i);
1910
1911 switch (column) {
1912 case Settings.NameValueTable._ID: {
1913 values[i] = setting.getId();
1914 } break;
1915
1916 case Settings.NameValueTable.NAME: {
1917 values[i] = setting.getName();
1918 } break;
1919
1920 case Settings.NameValueTable.VALUE: {
1921 values[i] = setting.getValue();
1922 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001923 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001924 }
1925
Svetoslav683914b2015-01-15 14:22:26 -08001926 cursor.addRow(values);
1927 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001928
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001929 private static boolean isKeyValid(String key) {
1930 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1931 }
1932
Svetoslav683914b2015-01-15 14:22:26 -08001933 private static final class Arguments {
1934 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1935 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1936
1937 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1938 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1939
1940 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1941 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1942
1943 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1944 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1945
1946 public final String table;
1947 public final String name;
1948
1949 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1950 final int segmentSize = uri.getPathSegments().size();
1951 switch (segmentSize) {
1952 case 1: {
1953 if (where != null
1954 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1955 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1956 && whereArgs.length == 1) {
1957 name = whereArgs[0];
1958 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001959 return;
Svetoslav683914b2015-01-15 14:22:26 -08001960 } else if (where != null
1961 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1962 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1963 final int startIndex = Math.max(where.indexOf("'"),
1964 where.indexOf("\"")) + 1;
1965 final int endIndex = Math.max(where.lastIndexOf("'"),
1966 where.lastIndexOf("\""));
1967 name = where.substring(startIndex, endIndex);
1968 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001969 return;
Svetoslav683914b2015-01-15 14:22:26 -08001970 } else if (supportAll && where == null && whereArgs == null) {
1971 name = null;
1972 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001973 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001974 }
Svetoslav683914b2015-01-15 14:22:26 -08001975 } break;
1976
Svetoslav28494652015-02-12 14:11:42 -08001977 case 2: {
1978 if (where == null && whereArgs == null) {
1979 name = uri.getPathSegments().get(1);
1980 table = computeTableForSetting(uri, name);
1981 return;
1982 }
1983 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001984 }
Svetoslav28494652015-02-12 14:11:42 -08001985
1986 EventLogTags.writeUnsupportedSettingsQuery(
1987 uri.toSafeString(), where, Arrays.toString(whereArgs));
1988 String message = String.format( "Supported SQL:\n"
1989 + " uri content://some_table/some_property with null where and where args\n"
1990 + " uri content://some_table with query name=? and single name as arg\n"
1991 + " uri content://some_table with query name=some_name and null args\n"
1992 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1993 Arrays.toString(whereArgs));
1994 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001995 }
1996
Svetoslav28494652015-02-12 14:11:42 -08001997 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001998 String table = getValidTableOrThrow(uri);
1999
2000 if (name != null) {
2001 if (sSystemMovedToSecureSettings.contains(name)) {
2002 table = TABLE_SECURE;
2003 }
2004
2005 if (sSystemMovedToGlobalSettings.contains(name)) {
2006 table = TABLE_GLOBAL;
2007 }
2008
2009 if (sSecureMovedToGlobalSettings.contains(name)) {
2010 table = TABLE_GLOBAL;
2011 }
2012
2013 if (sGlobalMovedToSecureSettings.contains(name)) {
2014 table = TABLE_SECURE;
2015 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002016 }
Svetoslav683914b2015-01-15 14:22:26 -08002017
2018 return table;
2019 }
2020 }
2021
2022 final class SettingsRegistry {
2023 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2024
Svetoslav683914b2015-01-15 14:22:26 -08002025 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2026 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2027 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002028 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2029
2030 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002031
2032 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2033
Svet Ganov53a441c2016-04-19 19:38:00 -07002034 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002035
Svetoslav7e0683b2015-08-03 16:02:52 -07002036 private final Handler mHandler;
2037
Svet Ganov53a441c2016-04-19 19:38:00 -07002038 private final BackupManager mBackupManager;
2039
Amith Yamasani39452022017-03-21 15:23:47 -07002040 private String mSettingsCreationBuildId;
2041
Svetoslav683914b2015-01-15 14:22:26 -08002042 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002043 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002044 mGenerationRegistry = new GenerationRegistry(mLock);
2045 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002046 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002047 syncSsaidTableOnStart();
2048 }
2049
2050 private void generateUserKeyLocked(int userId) {
2051 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002052 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002053 final SecureRandom rand = new SecureRandom();
2054 rand.nextBytes(keyBytes);
2055
2056 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002057 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002058
2059 // Store the key in the ssaid table.
2060 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2061 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2062 true, SettingsState.SYSTEM_PACKAGE_NAME);
2063
2064 if (!success) {
2065 throw new IllegalStateException("Ssaid settings not accessible");
2066 }
2067 }
2068
Mark Rathjen7599f132017-01-23 14:15:54 -08002069 private byte[] getLengthPrefix(byte[] data) {
2070 return ByteBuffer.allocate(4).putInt(data.length).array();
2071 }
2072
Mark Rathjend891f012017-01-19 04:10:37 +00002073 public Setting generateSsaidLocked(String packageName, int userId) {
2074 final PackageInfo packageInfo;
2075 try {
2076 packageInfo = mPackageManager.getPackageInfo(packageName,
2077 PackageManager.GET_SIGNATURES, userId);
2078 } catch (RemoteException e) {
2079 throw new IllegalStateException("Package info doesn't exist");
2080 }
2081
2082 // Read the user's key from the ssaid table.
2083 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002084 if (userKeySetting == null || userKeySetting.isNull()
2085 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002086 // Lazy initialize and store the user key.
2087 generateUserKeyLocked(userId);
2088 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002089 if (userKeySetting == null || userKeySetting.isNull()
2090 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002091 throw new IllegalStateException("User key not accessible");
2092 }
2093 }
2094 final String userKey = userKeySetting.getValue();
2095
2096 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002097 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2098
2099 // Validate that the key is of expected length.
2100 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2101 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002102 throw new IllegalStateException("User key invalid");
2103 }
2104
Mark Rathjen7599f132017-01-23 14:15:54 -08002105 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002106 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002107 m = Mac.getInstance("HmacSHA256");
2108 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002109 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002110 throw new IllegalStateException("HmacSHA256 is not available", e);
2111 } catch (InvalidKeyException e) {
2112 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002113 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002114
2115 // Mac the package name and each of the signatures.
2116 byte[] packageNameBytes = packageInfo.packageName.getBytes(StandardCharsets.UTF_8);
2117 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2118 m.update(packageNameBytes);
2119 for (int i = 0; i < packageInfo.signatures.length; i++) {
2120 byte[] sig = packageInfo.signatures[i].toByteArray();
2121 m.update(getLengthPrefix(sig), 0, 4);
2122 m.update(sig);
2123 }
Mark Rathjend891f012017-01-19 04:10:37 +00002124
2125 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002126 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2127 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002128
2129 // Save the ssaid in the ssaid table.
2130 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2131 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2132 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2133 packageName);
2134
2135 if (!success) {
2136 throw new IllegalStateException("Ssaid settings not accessible");
2137 }
2138
2139 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2140 }
2141
2142 public void syncSsaidTableOnStart() {
2143 synchronized (mLock) {
2144 // Verify that each user's packages and ssaid's are in sync.
2145 for (UserInfo user : mUserManager.getUsers(true)) {
2146 // Get all uids for the user's packages.
2147 final List<PackageInfo> packages;
2148 try {
2149 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2150 } catch (RemoteException e) {
2151 throw new IllegalStateException("Package manager not available");
2152 }
2153 final Set<String> appUids = new HashSet<>();
2154 for (PackageInfo info : packages) {
2155 appUids.add(Integer.toString(info.applicationInfo.uid));
2156 }
2157
2158 // Get all uids currently stored in the user's ssaid table.
2159 final Set<String> ssaidUids = new HashSet<>(
2160 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2161 ssaidUids.remove(SSAID_USER_KEY);
2162
2163 // Perform a set difference for the appUids and ssaidUids.
2164 ssaidUids.removeAll(appUids);
2165
2166 // If there are ssaidUids left over they need to be removed from the table.
2167 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2168 user.id);
2169 for (String uid : ssaidUids) {
2170 ssaidSettings.deleteSettingLocked(uid);
2171 }
2172 }
2173 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002174 }
2175
Svetoslav683914b2015-01-15 14:22:26 -08002176 public List<String> getSettingsNamesLocked(int type, int userId) {
2177 final int key = makeKey(type, userId);
2178 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002179 if (settingsState == null) {
2180 return new ArrayList<String>();
2181 }
Svetoslav683914b2015-01-15 14:22:26 -08002182 return settingsState.getSettingNamesLocked();
2183 }
2184
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002185 public SparseBooleanArray getKnownUsersLocked() {
2186 SparseBooleanArray users = new SparseBooleanArray();
2187 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2188 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2189 }
2190 return users;
2191 }
2192
Svetoslav683914b2015-01-15 14:22:26 -08002193 public SettingsState getSettingsLocked(int type, int userId) {
2194 final int key = makeKey(type, userId);
2195 return peekSettingsStateLocked(key);
2196 }
2197
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002198 public boolean ensureSettingsForUserLocked(int userId) {
2199 // First make sure this user actually exists.
2200 if (mUserManager.getUserInfo(userId) == null) {
2201 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2202 return false;
2203 }
2204
Svetoslav683914b2015-01-15 14:22:26 -08002205 // Migrate the setting for this user if needed.
2206 migrateLegacySettingsForUserIfNeededLocked(userId);
2207
2208 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002209 if (userId == UserHandle.USER_SYSTEM) {
2210 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002211 ensureSettingsStateLocked(globalKey);
2212 }
2213
2214 // Ensure secure settings loaded.
2215 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2216 ensureSettingsStateLocked(secureKey);
2217
2218 // Make sure the secure settings have an Android id set.
2219 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2220 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2221
2222 // Ensure system settings loaded.
2223 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2224 ensureSettingsStateLocked(systemKey);
2225
Mark Rathjend891f012017-01-19 04:10:37 +00002226 // Ensure secure settings loaded.
2227 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2228 ensureSettingsStateLocked(ssaidKey);
2229
Svetoslav683914b2015-01-15 14:22:26 -08002230 // Upgrade the settings to the latest version.
2231 UpgradeController upgrader = new UpgradeController(userId);
2232 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002233 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002234 }
2235
2236 private void ensureSettingsStateLocked(int key) {
2237 if (mSettingsStates.get(key) == null) {
2238 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002239 SettingsState settingsState = new SettingsState(getContext(), mLock,
2240 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002241 mSettingsStates.put(key, settingsState);
2242 }
2243 }
2244
2245 public void removeUserStateLocked(int userId, boolean permanently) {
2246 // We always keep the global settings in memory.
2247
2248 // Nuke system settings.
2249 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2250 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2251 if (systemSettingsState != null) {
2252 if (permanently) {
2253 mSettingsStates.remove(systemKey);
2254 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002255 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002256 systemSettingsState.destroyLocked(new Runnable() {
2257 @Override
2258 public void run() {
2259 mSettingsStates.remove(systemKey);
2260 }
2261 });
2262 }
2263 }
2264
2265 // Nuke secure settings.
2266 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2267 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2268 if (secureSettingsState != null) {
2269 if (permanently) {
2270 mSettingsStates.remove(secureKey);
2271 secureSettingsState.destroyLocked(null);
2272 } else {
2273 secureSettingsState.destroyLocked(new Runnable() {
2274 @Override
2275 public void run() {
2276 mSettingsStates.remove(secureKey);
2277 }
2278 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002279 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002280 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002281
Mark Rathjend891f012017-01-19 04:10:37 +00002282 // Nuke ssaid settings.
2283 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2284 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2285 if (ssaidSettingsState != null) {
2286 if (permanently) {
2287 mSettingsStates.remove(ssaidKey);
2288 ssaidSettingsState.destroyLocked(null);
2289 } else {
2290 ssaidSettingsState.destroyLocked(new Runnable() {
2291 @Override
2292 public void run() {
2293 mSettingsStates.remove(ssaidKey);
2294 }
2295 });
2296 }
2297 }
2298
Svet Ganov53a441c2016-04-19 19:38:00 -07002299 // Nuke generation tracking data
2300 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002301 }
2302
Svetoslav683914b2015-01-15 14:22:26 -08002303 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002304 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2305 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002306 final int key = makeKey(type, userId);
2307
Svetoslav Ganove080da92016-12-21 17:10:35 -08002308 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002309 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002310 if (settingsState != null) {
2311 success = settingsState.insertSettingLocked(name, value,
2312 tag, makeDefault, packageName);
2313 }
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 deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2326 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002327 final int key = makeKey(type, userId);
2328
Svetoslav Ganove080da92016-12-21 17:10:35 -08002329 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002330 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002331 if (settingsState != null) {
2332 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002333 }
Svetoslav683914b2015-01-15 14:22:26 -08002334
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002335 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2336 settingsState.persistSyncLocked();
2337 }
2338
Svet Ganov53a441c2016-04-19 19:38:00 -07002339 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002340 notifyForSettingsChange(key, name);
2341 }
2342 return success;
2343 }
2344
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002345 public boolean updateSettingLocked(int type, int userId, String name, String value,
2346 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2347 Set<String> criticalSettings) {
2348 final int key = makeKey(type, userId);
2349
2350 boolean success = false;
2351 SettingsState settingsState = peekSettingsStateLocked(key);
2352 if (settingsState != null) {
2353 success = settingsState.updateSettingLocked(name, value, tag,
2354 makeDefault, packageName);
2355 }
2356
2357 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2358 settingsState.persistSyncLocked();
2359 }
2360
2361 if (forceNotify || success) {
2362 notifyForSettingsChange(key, name);
2363 }
2364
2365 return success;
2366 }
2367
Svetoslav683914b2015-01-15 14:22:26 -08002368 public Setting getSettingLocked(int type, int userId, String name) {
2369 final int key = makeKey(type, userId);
2370
2371 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002372 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002373 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002374 }
Mark Rathjend891f012017-01-19 04:10:37 +00002375
2376 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002377 return settingsState.getSettingLocked(name);
2378 }
2379
Svetoslav Ganove080da92016-12-21 17:10:35 -08002380 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2381 String tag) {
2382 final int key = makeKey(type, userId);
2383 SettingsState settingsState = peekSettingsStateLocked(key);
2384 if (settingsState == null) {
2385 return;
2386 }
2387
2388 switch (mode) {
2389 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2390 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002391 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002392 Setting setting = settingsState.getSettingLocked(name);
2393 if (packageName.equals(setting.getPackageName())) {
2394 if (tag != null && !tag.equals(setting.getTag())) {
2395 continue;
2396 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002397 if (settingsState.resetSettingLocked(name)) {
2398 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002399 notifyForSettingsChange(key, name);
2400 }
2401 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002402 if (someSettingChanged) {
2403 settingsState.persistSyncLocked();
2404 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002405 }
2406 } break;
2407
2408 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2409 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002410 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002411 Setting setting = settingsState.getSettingLocked(name);
2412 if (!SettingsState.isSystemPackage(getContext(),
2413 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002414 if (settingsState.resetSettingLocked(name)) {
2415 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002416 notifyForSettingsChange(key, name);
2417 }
2418 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002419 if (someSettingChanged) {
2420 settingsState.persistSyncLocked();
2421 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002422 }
2423 } break;
2424
2425 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2426 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002427 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002428 Setting setting = settingsState.getSettingLocked(name);
2429 if (!SettingsState.isSystemPackage(getContext(),
2430 setting.getPackageName())) {
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 }
2440 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002441 if (someSettingChanged) {
2442 settingsState.persistSyncLocked();
2443 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002444 }
2445 } break;
2446
2447 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2448 for (String name : settingsState.getSettingNamesLocked()) {
2449 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002450 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002451 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002452 if (settingsState.resetSettingLocked(name)) {
2453 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002454 notifyForSettingsChange(key, name);
2455 }
2456 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002457 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002458 notifyForSettingsChange(key, name);
2459 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002460 if (someSettingChanged) {
2461 settingsState.persistSyncLocked();
2462 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002463 }
2464 } break;
2465 }
2466 }
2467
Svetoslav683914b2015-01-15 14:22:26 -08002468 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002469 // Global and secure settings are signature protected. Apps signed
2470 // by the platform certificate are generally not uninstalled and
2471 // the main exception is tests. We trust components signed
2472 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002473
2474 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2475 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002476 if (systemSettings != null) {
2477 systemSettings.onPackageRemovedLocked(packageName);
2478 }
Svetoslav683914b2015-01-15 14:22:26 -08002479 }
2480
Mark Rathjend891f012017-01-19 04:10:37 +00002481 public void onUidRemovedLocked(int uid) {
2482 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2483 UserHandle.getUserId(uid));
2484 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2485 }
2486
Svetoslav683914b2015-01-15 14:22:26 -08002487 private SettingsState peekSettingsStateLocked(int key) {
2488 SettingsState settingsState = mSettingsStates.get(key);
2489 if (settingsState != null) {
2490 return settingsState;
2491 }
2492
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002493 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2494 return null;
2495 }
Svetoslav683914b2015-01-15 14:22:26 -08002496 return mSettingsStates.get(key);
2497 }
2498
2499 private void migrateAllLegacySettingsIfNeeded() {
2500 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002501 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002502 File globalFile = getSettingsFile(key);
2503 if (globalFile.exists()) {
2504 return;
2505 }
2506
Amith Yamasani39452022017-03-21 15:23:47 -07002507 mSettingsCreationBuildId = Build.ID;
2508
Svetoslav683914b2015-01-15 14:22:26 -08002509 final long identity = Binder.clearCallingIdentity();
2510 try {
2511 List<UserInfo> users = mUserManager.getUsers(true);
2512
2513 final int userCount = users.size();
2514 for (int i = 0; i < userCount; i++) {
2515 final int userId = users.get(i).id;
2516
2517 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2518 SQLiteDatabase database = dbHelper.getWritableDatabase();
2519 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2520
2521 // Upgrade to the latest version.
2522 UpgradeController upgrader = new UpgradeController(userId);
2523 upgrader.upgradeIfNeededLocked();
2524
2525 // Drop from memory if not a running user.
2526 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2527 removeUserStateLocked(userId, false);
2528 }
2529 }
2530 } finally {
2531 Binder.restoreCallingIdentity(identity);
2532 }
2533 }
2534 }
2535
2536 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2537 // Every user has secure settings and if no file we need to migrate.
2538 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2539 File secureFile = getSettingsFile(secureKey);
2540 if (secureFile.exists()) {
2541 return;
2542 }
2543
2544 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2545 SQLiteDatabase database = dbHelper.getWritableDatabase();
2546
2547 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2548 }
2549
2550 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2551 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002552 // Move over the system settings.
2553 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2554 ensureSettingsStateLocked(systemKey);
2555 SettingsState systemSettings = mSettingsStates.get(systemKey);
2556 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2557 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002558
2559 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002560 // Do this after System settings, since this is the first thing we check when deciding
2561 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002562 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2563 ensureSettingsStateLocked(secureKey);
2564 SettingsState secureSettings = mSettingsStates.get(secureKey);
2565 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2566 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2567 secureSettings.persistSyncLocked();
2568
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002569 // Move over the global settings if owner.
2570 // Do this last, since this is the first thing we check when deciding
2571 // to skip over migration from db to xml for owner user.
2572 if (userId == UserHandle.USER_SYSTEM) {
2573 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2574 ensureSettingsStateLocked(globalKey);
2575 SettingsState globalSettings = mSettingsStates.get(globalKey);
2576 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002577 // If this was just created
2578 if (mSettingsCreationBuildId != null) {
2579 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2580 mSettingsCreationBuildId, null, true,
2581 SettingsState.SYSTEM_PACKAGE_NAME);
2582 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002583 globalSettings.persistSyncLocked();
2584 }
Svetoslav683914b2015-01-15 14:22:26 -08002585
2586 // Drop the database as now all is moved and persisted.
2587 if (DROP_DATABASE_ON_MIGRATION) {
2588 dbHelper.dropDatabase();
2589 } else {
2590 dbHelper.backupDatabase();
2591 }
2592 }
2593
2594 private void migrateLegacySettingsLocked(SettingsState settingsState,
2595 SQLiteDatabase database, String table) {
2596 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2597 queryBuilder.setTables(table);
2598
2599 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2600 null, null, null, null, null);
2601
2602 if (cursor == null) {
2603 return;
2604 }
2605
2606 try {
2607 if (!cursor.moveToFirst()) {
2608 return;
2609 }
2610
2611 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2612 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2613
2614 settingsState.setVersionLocked(database.getVersion());
2615
2616 while (!cursor.isAfterLast()) {
2617 String name = cursor.getString(nameColumnIdx);
2618 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002619 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002620 SettingsState.SYSTEM_PACKAGE_NAME);
2621 cursor.moveToNext();
2622 }
2623 } finally {
2624 cursor.close();
2625 }
2626 }
2627
2628 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2629 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2630
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002631 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002632 return;
2633 }
2634
2635 final int userId = getUserIdFromKey(secureSettings.mKey);
2636
2637 final UserInfo user;
2638 final long identity = Binder.clearCallingIdentity();
2639 try {
2640 user = mUserManager.getUserInfo(userId);
2641 } finally {
2642 Binder.restoreCallingIdentity(identity);
2643 }
2644 if (user == null) {
2645 // Can happen due to races when deleting users - treat as benign.
2646 return;
2647 }
2648
2649 String androidId = Long.toHexString(new SecureRandom().nextLong());
2650 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002651 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002652
2653 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2654 + "] for user " + userId);
2655
2656 // Write a drop box entry if it's a restricted profile
2657 if (user.isRestricted()) {
2658 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2659 Context.DROPBOX_SERVICE);
2660 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2661 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2662 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2663 }
2664 }
2665 }
2666
2667 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002668 final int userId = getUserIdFromKey(key);
2669 Uri uri = getNotificationUriFor(key, name);
2670
Phil Weaver83fec002016-05-11 10:55:29 -07002671 mGenerationRegistry.incrementGeneration(key);
2672
Svetoslav7e0683b2015-08-03 16:02:52 -07002673 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2674 userId, 0, uri).sendToTarget();
2675
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002676 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002677 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2678 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002679 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2680 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002681 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002682 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2683 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002684 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002685
Svet Ganov53a441c2016-04-19 19:38:00 -07002686 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002687 }
2688
Svet Ganov53a441c2016-04-19 19:38:00 -07002689 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002690 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002691 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002692 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002693 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002694 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002695 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002696 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002697 final int key = makeKey(type, profileId);
2698 mGenerationRegistry.incrementGeneration(key);
2699
2700 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002701 }
2702 }
2703 }
Svetoslav683914b2015-01-15 14:22:26 -08002704 }
2705
Svetoslav683914b2015-01-15 14:22:26 -08002706 private boolean isGlobalSettingsKey(int key) {
2707 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2708 }
2709
2710 private boolean isSystemSettingsKey(int key) {
2711 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2712 }
2713
2714 private boolean isSecureSettingsKey(int key) {
2715 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2716 }
2717
Mark Rathjend891f012017-01-19 04:10:37 +00002718 private boolean isSsaidSettingsKey(int key) {
2719 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2720 }
2721
Svetoslav683914b2015-01-15 14:22:26 -08002722 private File getSettingsFile(int key) {
2723 if (isGlobalSettingsKey(key)) {
2724 final int userId = getUserIdFromKey(key);
2725 return new File(Environment.getUserSystemDirectory(userId),
2726 SETTINGS_FILE_GLOBAL);
2727 } else if (isSystemSettingsKey(key)) {
2728 final int userId = getUserIdFromKey(key);
2729 return new File(Environment.getUserSystemDirectory(userId),
2730 SETTINGS_FILE_SYSTEM);
2731 } else if (isSecureSettingsKey(key)) {
2732 final int userId = getUserIdFromKey(key);
2733 return new File(Environment.getUserSystemDirectory(userId),
2734 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002735 } else if (isSsaidSettingsKey(key)) {
2736 final int userId = getUserIdFromKey(key);
2737 return new File(Environment.getUserSystemDirectory(userId),
2738 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002739 } else {
2740 throw new IllegalArgumentException("Invalid settings key:" + key);
2741 }
2742 }
2743
2744 private Uri getNotificationUriFor(int key, String name) {
2745 if (isGlobalSettingsKey(key)) {
2746 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2747 : Settings.Global.CONTENT_URI;
2748 } else if (isSecureSettingsKey(key)) {
2749 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2750 : Settings.Secure.CONTENT_URI;
2751 } else if (isSystemSettingsKey(key)) {
2752 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2753 : Settings.System.CONTENT_URI;
2754 } else {
2755 throw new IllegalArgumentException("Invalid settings key:" + key);
2756 }
2757 }
2758
2759 private int getMaxBytesPerPackageForType(int type) {
2760 switch (type) {
2761 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002762 case SETTINGS_TYPE_SECURE:
2763 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002764 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2765 }
2766
2767 default: {
2768 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2769 }
2770 }
2771 }
2772
Svetoslav7e0683b2015-08-03 16:02:52 -07002773 private final class MyHandler extends Handler {
2774 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2775 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2776
2777 public MyHandler(Looper looper) {
2778 super(looper);
2779 }
2780
2781 @Override
2782 public void handleMessage(Message msg) {
2783 switch (msg.what) {
2784 case MSG_NOTIFY_URI_CHANGED: {
2785 final int userId = msg.arg1;
2786 Uri uri = (Uri) msg.obj;
2787 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2788 if (DEBUG) {
2789 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2790 }
2791 } break;
2792
2793 case MSG_NOTIFY_DATA_CHANGED: {
2794 mBackupManager.dataChanged();
2795 } break;
2796 }
2797 }
2798 }
2799
Svetoslav683914b2015-01-15 14:22:26 -08002800 private final class UpgradeController {
Svet Ganov13701552017-02-23 12:45:17 -08002801 private static final int SETTINGS_VERSION = 142;
Svetoslav683914b2015-01-15 14:22:26 -08002802
2803 private final int mUserId;
2804
2805 public UpgradeController(int userId) {
2806 mUserId = userId;
2807 }
2808
2809 public void upgradeIfNeededLocked() {
2810 // The version of all settings for a user is the same (all users have secure).
2811 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002812 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002813
2814 // Try an update from the current state.
2815 final int oldVersion = secureSettings.getVersionLocked();
2816 final int newVersion = SETTINGS_VERSION;
2817
Svet Ganovc9755bc2015-03-28 13:21:22 -07002818 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002819 if (oldVersion == newVersion) {
2820 return;
2821 }
2822
2823 // Try to upgrade.
2824 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2825
2826 // If upgrade failed start from scratch and upgrade.
2827 if (curVersion != newVersion) {
2828 // Drop state we have for this user.
2829 removeUserStateLocked(mUserId, true);
2830
2831 // Recreate the database.
2832 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2833 SQLiteDatabase database = dbHelper.getWritableDatabase();
2834 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2835
2836 // Migrate the settings for this user.
2837 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2838
2839 // Now upgrade should work fine.
2840 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002841
2842 // Make a note what happened, so we don't wonder why data was lost
2843 String reason = "Settings rebuilt! Current version: "
2844 + curVersion + " while expected: " + newVersion;
2845 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002846 Settings.Global.DATABASE_DOWNGRADE_REASON,
2847 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002848 }
2849
2850 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002851 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002852 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002853 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002854 globalSettings.setVersionLocked(newVersion);
2855 }
2856
2857 // Set the secure settings version.
2858 secureSettings.setVersionLocked(newVersion);
2859
2860 // Set the system settings version.
2861 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002862 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002863 systemSettings.setVersionLocked(newVersion);
2864 }
2865
2866 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002867 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002868 }
2869
2870 private SettingsState getSecureSettingsLocked(int userId) {
2871 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2872 }
2873
Mark Rathjend891f012017-01-19 04:10:37 +00002874 private SettingsState getSsaidSettingsLocked(int userId) {
2875 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2876 }
2877
Svetoslav683914b2015-01-15 14:22:26 -08002878 private SettingsState getSystemSettingsLocked(int userId) {
2879 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2880 }
2881
Jeff Brown503cffc2015-03-26 18:08:51 -07002882 /**
2883 * You must perform all necessary mutations to bring the settings
2884 * for this user from the old to the new version. When you add a new
2885 * upgrade step you *must* update SETTINGS_VERSION.
2886 *
2887 * This is an example of moving a setting from secure to global.
2888 *
2889 * // v119: Example settings changes.
2890 * if (currentVersion == 118) {
2891 * if (userId == UserHandle.USER_OWNER) {
2892 * // Remove from the secure settings.
2893 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2894 * String name = "example_setting_to_move";
2895 * String value = secureSettings.getSetting(name);
2896 * secureSettings.deleteSetting(name);
2897 *
2898 * // Add to the global settings.
2899 * SettingsState globalSettings = getGlobalSettingsLocked();
2900 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2901 * }
2902 *
2903 * // Update the current version.
2904 * currentVersion = 119;
2905 * }
2906 */
Svetoslav683914b2015-01-15 14:22:26 -08002907 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2908 if (DEBUG) {
2909 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2910 + oldVersion + " to version: " + newVersion);
2911 }
2912
Jeff Brown503cffc2015-03-26 18:08:51 -07002913 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002914
John Spurlocke11ae112015-05-11 16:09:03 -04002915 // v119: Reset zen + ringer mode.
2916 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002917 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002918 final SettingsState globalSettings = getGlobalSettingsLocked();
2919 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002920 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2921 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002922 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002923 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2924 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002925 }
2926 currentVersion = 119;
2927 }
2928
Jason Monk27bbb2d2015-03-31 16:46:39 -04002929 // v120: Add double tap to wake setting.
2930 if (currentVersion == 119) {
2931 SettingsState secureSettings = getSecureSettingsLocked(userId);
2932 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2933 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002934 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002935 SettingsState.SYSTEM_PACKAGE_NAME);
2936
2937 currentVersion = 120;
2938 }
2939
Svetoslav7e0683b2015-08-03 16:02:52 -07002940 if (currentVersion == 120) {
2941 // Before 121, we used a different string encoding logic. We just bump the
2942 // version here; SettingsState knows how to handle pre-version 120 files.
2943 currentVersion = 121;
2944 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002945
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002946 if (currentVersion == 121) {
2947 // Version 122: allow OEMs to set a default payment component in resources.
2948 // Note that we only write the default if no default has been set;
2949 // if there is, we just leave the default at whatever it currently is.
2950 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2951 String defaultComponent = (getContext().getResources().getString(
2952 R.string.def_nfc_payment_component));
2953 Setting currentSetting = secureSettings.getSettingLocked(
2954 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2955 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002956 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002957 secureSettings.insertSettingLocked(
2958 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002959 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002960 }
2961 currentVersion = 122;
2962 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002963
2964 if (currentVersion == 122) {
2965 // Version 123: Adding a default value for the ability to add a user from
2966 // the lock screen.
2967 if (userId == UserHandle.USER_SYSTEM) {
2968 final SettingsState globalSettings = getGlobalSettingsLocked();
2969 Setting currentSetting = globalSettings.getSettingLocked(
2970 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002971 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002972 globalSettings.insertSettingLocked(
2973 Settings.Global.ADD_USERS_WHEN_LOCKED,
2974 getContext().getResources().getBoolean(
2975 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002976 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002977 }
2978 }
2979 currentVersion = 123;
2980 }
Bryce Leebd179282015-12-17 19:01:37 -08002981
2982 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002983 final SettingsState globalSettings = getGlobalSettingsLocked();
2984 String defaultDisabledProfiles = (getContext().getResources().getString(
2985 R.string.def_bluetooth_disabled_profiles));
2986 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002987 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002988 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002989 }
2990
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002991 if (currentVersion == 124) {
2992 // Version 124: allow OEMs to set a default value for whether IME should be
2993 // shown when a physical keyboard is connected.
2994 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2995 Setting currentSetting = secureSettings.getSettingLocked(
2996 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002997 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002998 secureSettings.insertSettingLocked(
2999 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3000 getContext().getResources().getBoolean(
3001 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003002 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003003 }
3004 currentVersion = 125;
3005 }
3006
Ruben Brunk98576cf2016-03-07 18:54:28 -08003007 if (currentVersion == 125) {
3008 // Version 125: Allow OEMs to set the default VR service.
3009 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3010
3011 Setting currentSetting = secureSettings.getSettingLocked(
3012 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003013 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003014 ArraySet<ComponentName> l =
3015 SystemConfig.getInstance().getDefaultVrComponents();
3016
3017 if (l != null && !l.isEmpty()) {
3018 StringBuilder b = new StringBuilder();
3019 boolean start = true;
3020 for (ComponentName c : l) {
3021 if (!start) {
3022 b.append(':');
3023 }
3024 b.append(c.flattenToString());
3025 start = false;
3026 }
3027 secureSettings.insertSettingLocked(
3028 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003029 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003030 }
3031
3032 }
3033 currentVersion = 126;
3034 }
3035
Daniel U02ba6122016-04-01 18:41:42 +01003036 if (currentVersion == 126) {
3037 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3038 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3039 if (mUserManager.isManagedProfile(userId)) {
3040 final SettingsState systemSecureSettings =
3041 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3042
3043 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3044 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003045 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003046 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3047 secureSettings.insertSettingLocked(
3048 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003049 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003050 SettingsState.SYSTEM_PACKAGE_NAME);
3051 }
3052
3053 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3054 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003055 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003056 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3057 secureSettings.insertSettingLocked(
3058 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003059 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003060 SettingsState.SYSTEM_PACKAGE_NAME);
3061 }
3062 }
3063 currentVersion = 127;
3064 }
3065
Steven Ngdc20ba62016-04-26 18:19:04 +01003066 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003067 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003068 currentVersion = 128;
3069 }
3070
Julia Reynolds1f721e12016-07-11 08:50:58 -04003071 if (currentVersion == 128) {
3072 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3073 // the new apps are appended to the list of already approved apps.
3074 final SettingsState systemSecureSettings =
3075 getSecureSettingsLocked(userId);
3076
3077 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3078 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3079 String defaultPolicyAccess = getContext().getResources().getString(
3080 com.android.internal.R.string.config_defaultDndAccessPackages);
3081 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3082 if (policyAccess.isNull()) {
3083 systemSecureSettings.insertSettingLocked(
3084 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003085 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003086 SettingsState.SYSTEM_PACKAGE_NAME);
3087 } else {
3088 StringBuilder currentSetting =
3089 new StringBuilder(policyAccess.getValue());
3090 currentSetting.append(":");
3091 currentSetting.append(defaultPolicyAccess);
3092 systemSecureSettings.updateSettingLocked(
3093 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003094 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003095 SettingsState.SYSTEM_PACKAGE_NAME);
3096 }
3097 }
3098
3099 currentVersion = 129;
3100 }
3101
Dan Sandler71f85e92016-07-20 13:46:05 -04003102 if (currentVersion == 129) {
3103 // default longpress timeout changed from 500 to 400. If unchanged from the old
3104 // default, update to the new default.
3105 final SettingsState systemSecureSettings =
3106 getSecureSettingsLocked(userId);
3107 final String oldValue = systemSecureSettings.getSettingLocked(
3108 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3109 if (TextUtils.equals("500", oldValue)) {
3110 systemSecureSettings.insertSettingLocked(
3111 Settings.Secure.LONG_PRESS_TIMEOUT,
3112 String.valueOf(getContext().getResources().getInteger(
3113 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003114 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003115 }
3116 currentVersion = 130;
3117 }
3118
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003119 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003120 // Split Ambient settings
3121 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3122 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3123 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3124
3125 if (dozeExplicitlyDisabled) {
3126 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003127 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003128 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003129 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003130 }
3131 currentVersion = 131;
3132 }
3133
3134 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003135 // Initialize new multi-press timeout to default value
3136 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3137 final String oldValue = systemSecureSettings.getSettingLocked(
3138 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3139 if (TextUtils.equals(null, oldValue)) {
3140 systemSecureSettings.insertSettingLocked(
3141 Settings.Secure.MULTI_PRESS_TIMEOUT,
3142 String.valueOf(getContext().getResources().getInteger(
3143 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003144 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003145 }
3146
Adrian Roos69741a22016-10-21 14:49:17 -07003147 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003148 }
3149
Adrian Roos69741a22016-10-21 14:49:17 -07003150 if (currentVersion == 132) {
3151 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003152 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3153 String defaultSyncParentSounds = (getContext().getResources()
3154 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3155 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003156 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3157 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003158 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003159 }
3160
Adrian Roos69741a22016-10-21 14:49:17 -07003161 if (currentVersion == 133) {
3162 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003163 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3164 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3165 null) {
3166 String defaultEndButtonBehavior = Integer.toString(getContext()
3167 .getResources().getInteger(R.integer.def_end_button_behavior));
3168 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003169 defaultEndButtonBehavior, null, true,
3170 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003171 }
Adrian Roos69741a22016-10-21 14:49:17 -07003172 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003173 }
3174
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003175 if (currentVersion == 134) {
3176 // Remove setting that specifies if magnification values should be preserved.
3177 // This setting defaulted to true and never has a UI.
3178 getSecureSettingsLocked(userId).deleteSettingLocked(
3179 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3180 currentVersion = 135;
3181 }
3182
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003183 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003184 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003185 currentVersion = 136;
3186 }
3187
Mark Rathjend891f012017-01-19 04:10:37 +00003188 if (currentVersion == 136) {
3189 // Version 136: Store legacy SSAID for all apps currently installed on the
3190 // device as first step in migrating SSAID to be unique per application.
3191
3192 final boolean isUpgrade;
3193 try {
3194 isUpgrade = mPackageManager.isUpgrade();
3195 } catch (RemoteException e) {
3196 throw new IllegalStateException("Package manager not available");
3197 }
3198 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3199 // user data or first boot on a new device should use new ssaid generation.
3200 if (isUpgrade) {
3201 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003202 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3203 userId, Settings.Secure.ANDROID_ID);
3204 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3205 || legacySsaidSetting.getValue() == null) {
3206 throw new IllegalStateException("Legacy ssaid not accessible");
3207 }
3208 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003209
3210 // Fill each uid with the legacy ssaid to be backwards compatible.
3211 final List<PackageInfo> packages;
3212 try {
3213 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3214 } catch (RemoteException e) {
3215 throw new IllegalStateException("Package manager not available");
3216 }
3217
3218 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3219 for (PackageInfo info : packages) {
3220 // Check if the UID already has an entry in the table.
3221 final String uid = Integer.toString(info.applicationInfo.uid);
3222 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3223
3224 if (ssaid.isNull() || ssaid.getValue() == null) {
3225 // Android Id doesn't exist for this package so create it.
3226 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3227 info.packageName);
3228 }
3229 }
3230 }
3231
3232 currentVersion = 137;
3233 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003234 if (currentVersion == 137) {
3235 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3236 // default value set to 1. The user can no longer change the value of this
3237 // setting through the UI.
3238 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3239 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003240 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3241 && secureSetting.getSettingLocked(
3242 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3243
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003244 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3245 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003246 // For managed profiles with profile owners, DevicePolicyManagerService
3247 // may want to set the user restriction in this case
3248 secureSetting.insertSettingLocked(
3249 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3250 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003251 }
3252 currentVersion = 138;
3253 }
Mark Rathjend891f012017-01-19 04:10:37 +00003254
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003255 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003256 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003257 currentVersion = 139;
3258 }
3259
Phil Weaver385912e2017-02-10 10:06:56 -08003260 if (currentVersion == 139) {
3261 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3262 // the user can no longer change the value of this setting through the UI.
3263 // Force to true.
3264 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3265 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3266 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3267 currentVersion = 140;
3268 }
3269
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003270 if (currentVersion == 140) {
3271 // Version 141: One-time grant of notification listener privileges
3272 // to packages specified in overlay.
3273 String defaultListenerAccess = getContext().getResources().getString(
3274 com.android.internal.R.string.config_defaultListenerAccessPackages);
3275 if (defaultListenerAccess != null) {
3276 StringBuffer newListeners = new StringBuffer();
3277 for (String whitelistPkg : defaultListenerAccess.split(":")) {
3278 // Gather all notification listener components for candidate pkgs.
3279 Intent serviceIntent =
3280 new Intent(NotificationListenerService.SERVICE_INTERFACE)
3281 .setPackage(whitelistPkg);
3282 List<ResolveInfo> installedServices =
3283 getContext().getPackageManager().queryIntentServicesAsUser(
3284 serviceIntent,
3285 PackageManager.GET_SERVICES
3286 | PackageManager.GET_META_DATA
3287 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3288 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
3289 userId);
3290
3291 for (int i = 0, count = installedServices.size(); i < count; i++) {
3292 ResolveInfo resolveInfo = installedServices.get(i);
3293 ServiceInfo info = resolveInfo.serviceInfo;
3294 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
3295 .equals(info.permission)) {
3296 continue;
3297 }
3298 newListeners.append(":")
3299 .append(info.getComponentName().flattenToString());
3300 }
3301 }
3302
3303 if (newListeners.length() > 0) {
3304 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3305 final Setting existingSetting = secureSetting.getSettingLocked(
3306 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
3307 if (existingSetting.isNull()) {
3308 secureSetting.insertSettingLocked(
3309 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3310 newListeners.toString(), null, true,
3311 SettingsState.SYSTEM_PACKAGE_NAME);
3312 } else {
3313 StringBuilder currentSetting =
3314 new StringBuilder(existingSetting.getValue());
3315 currentSetting.append(newListeners.toString());
3316 secureSetting.updateSettingLocked(
3317 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
3318 currentSetting.toString(), null, true,
3319 SettingsState.SYSTEM_PACKAGE_NAME);
3320 }
3321 }
3322 }
3323 currentVersion = 141;
3324 }
3325
Svet Ganov13701552017-02-23 12:45:17 -08003326 if (currentVersion == 141) {
3327 // Version 141: We added the notion of a default and whether the system set
3328 // the setting. This is used for resetting the internal state and we need
3329 // to make sure this value is updated for the existing settings, otherwise
3330 // we would delete system set settings while they should stay unmodified.
3331 SettingsState globalSettings = getGlobalSettingsLocked();
3332 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings);
3333 globalSettings.persistSyncLocked();
3334
3335 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3336 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings);
3337 secureSettings.persistSyncLocked();
3338
3339 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3340 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings);
3341 systemSettings.persistSyncLocked();
3342
3343 currentVersion = 142;
3344 }
3345
Dan Sandler71f85e92016-07-20 13:46:05 -04003346 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003347 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003348 + newVersion + " left it at "
3349 + currentVersion + " instead; this is probably a bug", new Throwable());
3350 if (DEBUG) {
3351 throw new RuntimeException("db upgrade error");
3352 }
3353 }
3354
Jeff Brown503cffc2015-03-26 18:08:51 -07003355 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003356
Jeff Brown503cffc2015-03-26 18:08:51 -07003357 // Return the current version.
3358 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003359 }
3360 }
Svet Ganov13701552017-02-23 12:45:17 -08003361
3362 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings) {
3363 List<String> names = settings.getSettingNamesLocked();
3364 final int nameCount = names.size();
3365 for (int i = 0; i < nameCount; i++) {
3366 String name = names.get(i);
3367 Setting setting = settings.getSettingLocked(name);
3368 if (setting.getDefaultValue() == null) {
3369 boolean systemSet = SettingsState.isSystemPackage(getContext(),
3370 setting.getPackageName());
3371 if (systemSet) {
3372 settings.insertSettingLocked(name, setting.getValue(),
3373 setting.getTag(), true, setting.getPackageName());
3374 }
3375 }
3376 }
3377 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003378 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003379}