blob: 225b955958cdc440d89f9ec85c46a640616df13e [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;
Christopher Tate38e7a602013-09-03 16:57:34 -070035import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080037import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.sqlite.SQLiteDatabase;
39import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080040import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040041import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070043import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080044import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070046import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080047import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070048import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070049import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Looper;
51import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070053import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070054import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070055import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070056import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070057import android.os.UserHandle;
58import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070059import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060import android.provider.Settings;
Jeremy Joslin8bdad342016-12-14 11:46:47 -080061import android.provider.Settings.Global;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010063import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080064import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000065import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070066import android.util.Slog;
67import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070068import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080069import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040070
Svetoslav683914b2015-01-15 14:22:26 -080071import com.android.internal.annotations.GuardedBy;
72import com.android.internal.content.PackageMonitor;
73import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080074import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070075import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080076import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040077
Svetoslav683914b2015-01-15 14:22:26 -080078import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080079import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080080import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080081import java.io.PrintWriter;
Mark Rathjend891f012017-01-19 04:10:37 +000082import java.nio.charset.StandardCharsets;
Mark Rathjen7599f132017-01-23 14:15:54 -080083import java.nio.ByteBuffer;
84import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000085import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080086import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070087import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000089import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000090import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080091import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080092import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010093import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080094import java.util.Set;
95import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080096import javax.crypto.Mac;
97import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070098
Svetoslav Ganove080da92016-12-21 17:10:35 -080099import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800100import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800101import static android.os.Process.SYSTEM_UID;
102
Svetoslav Ganove080da92016-12-21 17:10:35 -0800103
Svetoslav683914b2015-01-15 14:22:26 -0800104/**
105 * <p>
106 * This class is a content provider that publishes the system settings.
107 * It can be accessed via the content provider APIs or via custom call
108 * commands. The latter is a bit faster and is the preferred way to access
109 * the platform settings.
110 * </p>
111 * <p>
112 * There are three settings types, global (with signature level protection
113 * and shared across users), secure (with signature permission level
114 * protection and per user), and system (with dangerous permission level
115 * protection and per user). Global settings are stored under the device owner.
116 * Each of these settings is represented by a {@link
117 * com.android.providers.settings.SettingsState} object mapped to an integer
118 * key derived from the setting type in the most significant bits and user
119 * id in the least significant bits. Settings are synchronously loaded on
120 * instantiation of a SettingsState and asynchronously persisted on mutation.
121 * Settings are stored in the user specific system directory.
122 * </p>
123 * <p>
124 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
125 * and get a warning. Targeting higher API version prohibits this as the
126 * system settings are not a place for apps to save their state. When a package
127 * is removed the settings it added are deleted. Apps cannot delete system
128 * settings added by the platform. System settings values are validated to
129 * ensure the clients do not put bad values. Global and secure settings are
130 * changed only by trusted parties, therefore no validation is performed. Also
131 * there is a limit on the amount of app specific settings that can be added
132 * to prevent unlimited growth of the system process memory footprint.
133 * </p>
134 */
135@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700137 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700139 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800140
141 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700142
Christopher Tate06efb532012-08-24 15:29:27 -0700143 private static final String TABLE_SYSTEM = "system";
144 private static final String TABLE_SECURE = "secure";
145 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800146
147 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final String TABLE_FAVORITES = "favorites";
149 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800150 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
151 private static final String TABLE_BOOKMARKS = "bookmarks";
152 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Svetoslav683914b2015-01-15 14:22:26 -0800154 // The set of removed legacy tables.
155 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700156 static {
Svetoslav683914b2015-01-15 14:22:26 -0800157 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
158 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
159 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
160 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
161 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
162 }
Christopher Tate06efb532012-08-24 15:29:27 -0700163
Svetoslav683914b2015-01-15 14:22:26 -0800164 private static final int MUTATION_OPERATION_INSERT = 1;
165 private static final int MUTATION_OPERATION_DELETE = 2;
166 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800167 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400168
Svetoslav683914b2015-01-15 14:22:26 -0800169 private static final String[] ALL_COLUMNS = new String[] {
170 Settings.NameValueTable._ID,
171 Settings.NameValueTable.NAME,
172 Settings.NameValueTable.VALUE
173 };
174
Svet Ganov53a441c2016-04-19 19:38:00 -0700175 public static final int SETTINGS_TYPE_GLOBAL = 0;
176 public static final int SETTINGS_TYPE_SYSTEM = 1;
177 public static final int SETTINGS_TYPE_SECURE = 2;
Mark Rathjend891f012017-01-19 04:10:37 +0000178 public static final int SETTINGS_TYPE_SSAID = 3;
Svetoslav683914b2015-01-15 14:22:26 -0800179
Svet Ganov53a441c2016-04-19 19:38:00 -0700180 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
181 public static final int SETTINGS_TYPE_SHIFT = 28;
182
183 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
184 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700185
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800186 // Changes to these global settings are synchronously persisted
187 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
188 static {
189 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
190 }
191
192 // Changes to these secure settings are synchronously persisted
193 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
194 static {
195 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
196 }
197
Svetoslav683914b2015-01-15 14:22:26 -0800198 // Per user secure settings that moved to the for all users global settings.
199 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
200 static {
201 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700202 }
203
Svetoslav683914b2015-01-15 14:22:26 -0800204 // Per user system settings that moved to the for all users global settings.
205 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
206 static {
207 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700208 }
209
Svetoslav683914b2015-01-15 14:22:26 -0800210 // Per user system settings that moved to the per user secure settings.
211 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
212 static {
213 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700214 }
215
Svetoslav683914b2015-01-15 14:22:26 -0800216 // Per all users global settings that moved to the per user secure settings.
217 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
218 static {
219 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 }
221
Svetoslav683914b2015-01-15 14:22:26 -0800222 // Per user secure settings that are cloned for the managed profiles of the user.
223 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
224 static {
225 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700226 }
227
Svetoslav683914b2015-01-15 14:22:26 -0800228 // Per user system settings that are cloned for the managed profiles of the user.
229 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
230 static {
231 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400232 }
233
Andre Lago3fa139c2016-08-04 13:53:44 +0100234 // Per user system settings that are cloned from the profile's parent when a dependency
235 // in {@link Settings.Secure} is set to "1".
236 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
237 static {
238 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
239 }
240
Svetoslav683914b2015-01-15 14:22:26 -0800241 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700242
Svetoslav683914b2015-01-15 14:22:26 -0800243 @GuardedBy("mLock")
244 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700245
Svet Ganova8f90262016-05-10 08:44:48 -0700246 @GuardedBy("mLock")
247 private HandlerThread mHandlerThread;
248
Svetoslav7ec28e82015-05-20 17:01:10 -0700249 // We have to call in the user manager with no lock held,
250 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800251
Svetoslav7ec28e82015-05-20 17:01:10 -0700252 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700253 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700254
Svet Ganov53a441c2016-04-19 19:38:00 -0700255 public static int makeKey(int type, int userId) {
256 return (type << SETTINGS_TYPE_SHIFT) | userId;
257 }
258
259 public static int getTypeFromKey(int key) {
260 return key >>> SETTINGS_TYPE_SHIFT;
261 }
262
263 public static int getUserIdFromKey(int key) {
264 return key & ~SETTINGS_TYPE_MASK;
265 }
266
267 public static String settingTypeToString(int type) {
268 switch (type) {
269 case SETTINGS_TYPE_GLOBAL: {
270 return "SETTINGS_GLOBAL";
271 }
272 case SETTINGS_TYPE_SECURE: {
273 return "SETTINGS_SECURE";
274 }
275 case SETTINGS_TYPE_SYSTEM: {
276 return "SETTINGS_SYSTEM";
277 }
Mark Rathjend891f012017-01-19 04:10:37 +0000278 case SETTINGS_TYPE_SSAID: {
279 return "SETTINGS_SSAID";
280 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 default: {
282 return "UNKNOWN";
283 }
284 }
285 }
286
287 public static String keyToString(int key) {
288 return "Key[user=" + getUserIdFromKey(key) + ";type="
289 + settingTypeToString(getTypeFromKey(key)) + "]";
290 }
291
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700292 @Override
293 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800294 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800295 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700296 mUserManager = UserManager.get(getContext());
297 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700298 mHandlerThread = new HandlerThread(LOG_TAG,
299 Process.THREAD_PRIORITY_BACKGROUND);
300 mHandlerThread.start();
Svetoslav683914b2015-01-15 14:22:26 -0800301 mSettingsRegistry = new SettingsRegistry();
302 }
303 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700304 startWatchingUserRestrictionChanges();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700305 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700306 return true;
307 }
308
Svetoslav683914b2015-01-15 14:22:26 -0800309 @Override
310 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700311 final int requestingUserId = getRequestingUserId(args);
312 switch (method) {
313 case Settings.CALL_METHOD_GET_GLOBAL: {
314 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700315 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800316 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700317
318 case Settings.CALL_METHOD_GET_SECURE: {
319 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700320 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700321 }
322
323 case Settings.CALL_METHOD_GET_SYSTEM: {
324 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700325 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700326 }
327
328 case Settings.CALL_METHOD_PUT_GLOBAL: {
329 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800330 String tag = getSettingTag(args);
331 final boolean makeDefault = getSettingMakeDefault(args);
332 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700333 break;
334 }
335
336 case Settings.CALL_METHOD_PUT_SECURE: {
337 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800338 String tag = getSettingTag(args);
339 final boolean makeDefault = getSettingMakeDefault(args);
340 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700341 break;
342 }
343
344 case Settings.CALL_METHOD_PUT_SYSTEM: {
345 String value = getSettingValue(args);
346 insertSystemSetting(name, value, requestingUserId);
347 break;
348 }
349
Svetoslav Ganove080da92016-12-21 17:10:35 -0800350 case Settings.CALL_METHOD_RESET_GLOBAL: {
351 final int mode = getResetModeEnforcingPermission(args);
352 String tag = getSettingTag(args);
353 resetGlobalSetting(requestingUserId, mode, tag);
354 break;
355 }
356
357 case Settings.CALL_METHOD_RESET_SECURE: {
358 final int mode = getResetModeEnforcingPermission(args);
359 String tag = getSettingTag(args);
360 resetSecureSetting(requestingUserId, mode, tag);
361 break;
362 }
363
Svetoslav7ec28e82015-05-20 17:01:10 -0700364 default: {
365 Slog.w(LOG_TAG, "call() with invalid method: " + method);
366 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700367 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700368
Christopher Tate06efb532012-08-24 15:29:27 -0700369 return null;
370 }
371
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800372 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800373 public String getType(Uri uri) {
374 Arguments args = new Arguments(uri, null, null, true);
375 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376 return "vnd.android.cursor.dir/" + args.table;
377 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700378 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700379 }
380 }
381
382 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800383 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
384 String order) {
385 if (DEBUG) {
386 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700387 }
388
Svetoslav683914b2015-01-15 14:22:26 -0800389 Arguments args = new Arguments(uri, where, whereArgs, true);
390 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700391
Svetoslav683914b2015-01-15 14:22:26 -0800392 // If a legacy table that is gone, done.
393 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
394 return new MatrixCursor(normalizedProjection, 0);
395 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700396
Svetoslav7ec28e82015-05-20 17:01:10 -0700397 switch (args.table) {
398 case TABLE_GLOBAL: {
399 if (args.name != null) {
400 Setting setting = getGlobalSetting(args.name);
401 return packageSettingForQuery(setting, normalizedProjection);
402 } else {
403 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700404 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700405 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700406
Svetoslav7ec28e82015-05-20 17:01:10 -0700407 case TABLE_SECURE: {
408 final int userId = UserHandle.getCallingUserId();
409 if (args.name != null) {
410 Setting setting = getSecureSetting(args.name, userId);
411 return packageSettingForQuery(setting, normalizedProjection);
412 } else {
413 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800414 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700415 }
Svetoslav683914b2015-01-15 14:22:26 -0800416
Svetoslav7ec28e82015-05-20 17:01:10 -0700417 case TABLE_SYSTEM: {
418 final int userId = UserHandle.getCallingUserId();
419 if (args.name != null) {
420 Setting setting = getSystemSetting(args.name, userId);
421 return packageSettingForQuery(setting, normalizedProjection);
422 } else {
423 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800424 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 }
Svetoslav683914b2015-01-15 14:22:26 -0800426
Svetoslav7ec28e82015-05-20 17:01:10 -0700427 default: {
428 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700429 }
430 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700431 }
432
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700433 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800434 public Uri insert(Uri uri, ContentValues values) {
435 if (DEBUG) {
436 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700437 }
438
Svetoslav683914b2015-01-15 14:22:26 -0800439 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700440
Svetoslav683914b2015-01-15 14:22:26 -0800441 // If a legacy table that is gone, done.
442 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 return null;
444 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700445
Svetoslav683914b2015-01-15 14:22:26 -0800446 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700447 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800448 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700449 }
450
Svetoslav683914b2015-01-15 14:22:26 -0800451 String value = values.getAsString(Settings.Secure.VALUE);
452
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 switch (table) {
454 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800455 if (insertGlobalSetting(name, value, null, false,
456 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700457 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700458 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700459 } break;
460
461 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800462 if (insertSecureSetting(name, value, null, false,
463 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700464 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
465 }
466 } break;
467
468 case TABLE_SYSTEM: {
469 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
470 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
471 }
472 } break;
473
474 default: {
475 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700476 }
477 }
478
Svetoslav683914b2015-01-15 14:22:26 -0800479 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700480 }
481
482 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800483 public int bulkInsert(Uri uri, ContentValues[] allValues) {
484 if (DEBUG) {
485 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700487
Svetoslav683914b2015-01-15 14:22:26 -0800488 int insertionCount = 0;
489 final int valuesCount = allValues.length;
490 for (int i = 0; i < valuesCount; i++) {
491 ContentValues values = allValues[i];
492 if (insert(uri, values) != null) {
493 insertionCount++;
494 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700495 }
Svetoslav683914b2015-01-15 14:22:26 -0800496
497 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700498 }
499
500 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800501 public int delete(Uri uri, String where, String[] whereArgs) {
502 if (DEBUG) {
503 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700505
Svetoslav683914b2015-01-15 14:22:26 -0800506 Arguments args = new Arguments(uri, where, whereArgs, false);
507
508 // If a legacy table that is gone, done.
509 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
510 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700511 }
Svetoslav683914b2015-01-15 14:22:26 -0800512
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700513 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800514 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700515 }
Svetoslav683914b2015-01-15 14:22:26 -0800516
Svetoslav7ec28e82015-05-20 17:01:10 -0700517 switch (args.table) {
518 case TABLE_GLOBAL: {
519 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700520 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700521 }
Svetoslav683914b2015-01-15 14:22:26 -0800522
Svetoslav7ec28e82015-05-20 17:01:10 -0700523 case TABLE_SECURE: {
524 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700525 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700526 }
Svetoslav683914b2015-01-15 14:22:26 -0800527
Svetoslav7ec28e82015-05-20 17:01:10 -0700528 case TABLE_SYSTEM: {
529 final int userId = UserHandle.getCallingUserId();
530 return deleteSystemSetting(args.name, userId) ? 1 : 0;
531 }
532
533 default: {
534 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800535 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700536 }
Svetoslav683914b2015-01-15 14:22:26 -0800537 }
538
539 @Override
540 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
541 if (DEBUG) {
542 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700543 }
Svetoslav683914b2015-01-15 14:22:26 -0800544
545 Arguments args = new Arguments(uri, where, whereArgs, false);
546
547 // If a legacy table that is gone, done.
548 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
549 return 0;
550 }
551
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700552 String name = values.getAsString(Settings.Secure.NAME);
553 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800554 return 0;
555 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700556 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800557
Svetoslav7ec28e82015-05-20 17:01:10 -0700558 switch (args.table) {
559 case TABLE_GLOBAL: {
560 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800561 return updateGlobalSetting(args.name, value, null, false,
562 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700563 }
Svetoslav683914b2015-01-15 14:22:26 -0800564
Svetoslav7ec28e82015-05-20 17:01:10 -0700565 case TABLE_SECURE: {
566 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800567 return updateSecureSetting(args.name, value, null, false,
568 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700569 }
Svetoslav683914b2015-01-15 14:22:26 -0800570
Svetoslav7ec28e82015-05-20 17:01:10 -0700571 case TABLE_SYSTEM: {
572 final int userId = UserHandle.getCallingUserId();
573 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
574 }
Svetoslav683914b2015-01-15 14:22:26 -0800575
Svetoslav7ec28e82015-05-20 17:01:10 -0700576 default: {
577 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800578 }
579 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700580 }
581
582 @Override
583 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100584 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
585 if (userId != UserHandle.getCallingUserId()) {
586 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
587 "Access files from the settings of another user");
588 }
589 uri = ContentProvider.getUriWithoutUserId(uri);
590
Andre Lago3fa139c2016-08-04 13:53:44 +0100591 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700592 final String cacheName;
593 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100594 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700595 cacheName = Settings.System.RINGTONE_CACHE;
596 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100597 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700598 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
599 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100600 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700601 cacheName = Settings.System.ALARM_ALERT_CACHE;
602 } else {
603 throw new FileNotFoundException("Direct file access no longer supported; "
604 + "ringtone playback is available through android.media.Ringtone");
605 }
606
Andre Lago3fa139c2016-08-04 13:53:44 +0100607 int actualCacheOwner;
608 // Redirect cache to parent if ringtone setting is owned by profile parent
609 synchronized (mLock) {
610 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
611 cacheRingtoneSetting);
612 }
613 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700614 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
615 }
616
617 private File getRingtoneCacheDir(int userId) {
618 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
619 cacheDir.mkdir();
620 SELinux.restorecon(cacheDir);
621 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700622 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800623
Eugene Suslad72c3972016-12-27 15:49:30 -0800624 /**
625 * Dump all settings as a proto buf.
626 *
627 * @param fd The file to dump to
628 */
629 void dumpProto(@NonNull FileDescriptor fd) {
630 ProtoOutputStream proto = new ProtoOutputStream(fd);
631
632 synchronized (mLock) {
633 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
634
635 }
636
637 proto.flush();
638 }
639
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700640 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800641 synchronized (mLock) {
642 final long identity = Binder.clearCallingIdentity();
643 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700644 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800645 final int userCount = users.size();
646 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700647 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800648 }
649 } finally {
650 Binder.restoreCallingIdentity(identity);
651 }
652 }
653 }
654
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700655 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700656 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800657 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700658 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
659 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700660 if (globalSettings != null) {
661 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800662 pw.println();
663 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700664 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800665 }
666
667 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700668 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
669 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700670 if (secureSettings != null) {
671 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800672 pw.println();
673 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700674 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700675
Svetoslavb505ccc2015-02-17 12:41:04 -0800676 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700677 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
678 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700679 if (systemSettings != null) {
680 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800681 pw.println();
682 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700683 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800684 }
685
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700686 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
687 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800688
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700689 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800690
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700691 for (int i = 0; i < nameCount; i++) {
692 String name = names.get(i);
693 Setting setting = settingsState.getSettingLocked(name);
694 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
695 pw.print(" name:"); pw.print(toDumpString(name));
696 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800697 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700698 }
699 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800700 if (setting.getDefaultValue() != null) {
701 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800702 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800703 }
704 if (setting.getTag() != null) {
705 pw.print(" tag:"); pw.print(setting.getTag());
706 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800707 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700708 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800709 }
710
Svetoslav7e0683b2015-08-03 16:02:52 -0700711 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700712 if (s != null) {
713 return s;
714 }
715 return "{null}";
716 }
717
Svetoslav683914b2015-01-15 14:22:26 -0800718 private void registerBroadcastReceivers() {
719 IntentFilter userFilter = new IntentFilter();
720 userFilter.addAction(Intent.ACTION_USER_REMOVED);
721 userFilter.addAction(Intent.ACTION_USER_STOPPED);
722
723 getContext().registerReceiver(new BroadcastReceiver() {
724 @Override
725 public void onReceive(Context context, Intent intent) {
726 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700727 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800728
729 switch (intent.getAction()) {
730 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700731 synchronized (mLock) {
732 mSettingsRegistry.removeUserStateLocked(userId, true);
733 }
Svetoslav683914b2015-01-15 14:22:26 -0800734 } break;
735
736 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700737 synchronized (mLock) {
738 mSettingsRegistry.removeUserStateLocked(userId, false);
739 }
Svetoslav683914b2015-01-15 14:22:26 -0800740 } break;
741 }
742 }
743 }, userFilter);
744
745 PackageMonitor monitor = new PackageMonitor() {
746 @Override
747 public void onPackageRemoved(String packageName, int uid) {
748 synchronized (mLock) {
749 mSettingsRegistry.onPackageRemovedLocked(packageName,
750 UserHandle.getUserId(uid));
751 }
752 }
Mark Rathjend891f012017-01-19 04:10:37 +0000753
754 @Override
755 public void onUidRemoved(int uid) {
756 synchronized (mLock) {
757 mSettingsRegistry.onUidRemovedLocked(uid);
758 }
759 }
Svetoslav683914b2015-01-15 14:22:26 -0800760 };
761
762 // package changes
763 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
764 UserHandle.ALL, true);
765 }
766
Svet Ganov53a441c2016-04-19 19:38:00 -0700767 private void startWatchingUserRestrictionChanges() {
768 // TODO: The current design of settings looking different based on user restrictions
769 // should be reworked to keep them separate and system code should check the setting
770 // first followed by checking the user restriction before performing an operation.
771 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
772 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
773 Bundle prevRestrictions) -> {
774 // We are changing the settings affected by restrictions to their current
775 // value with a forced update to ensure that all cross profile dependencies
776 // are taken into account. Also make sure the settings update to.. the same
777 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800778 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
779 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700780 final long identity = Binder.clearCallingIdentity();
781 try {
782 synchronized (mLock) {
783 Setting setting = getSecureSetting(
784 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
785 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800786 setting != null ? setting.getValue() : null, null,
787 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700788 }
789 } finally {
790 Binder.restoreCallingIdentity(identity);
791 }
792 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800793 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
794 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700795 final long identity = Binder.clearCallingIdentity();
796 try {
797 synchronized (mLock) {
798 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800799 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700800 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800801 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700802 }
803 } finally {
804 Binder.restoreCallingIdentity(identity);
805 }
806 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800807 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
808 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700809 final long identity = Binder.clearCallingIdentity();
810 try {
811 synchronized (mLock) {
812 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800813 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700814 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700816 }
817 } finally {
818 Binder.restoreCallingIdentity(identity);
819 }
820 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800821 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
822 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700823 final long identity = Binder.clearCallingIdentity();
824 try {
825 synchronized (mLock) {
826 Setting enable = getGlobalSetting(
827 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800828 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700829 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800830 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 Setting include = getGlobalSetting(
832 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800833 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700834 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800835 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700836 }
837 } finally {
838 Binder.restoreCallingIdentity(identity);
839 }
840 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800841 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
842 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700843 final long identity = Binder.clearCallingIdentity();
844 try {
845 synchronized (mLock) {
846 Setting setting = getGlobalSetting(
847 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800848 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700849 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800850 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700851 }
852 } finally {
853 Binder.restoreCallingIdentity(identity);
854 }
855 }
856 });
857 }
858
Svetoslav7ec28e82015-05-20 17:01:10 -0700859 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800860 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700861 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800862 }
863
Svetoslav7ec28e82015-05-20 17:01:10 -0700864 synchronized (mLock) {
865 // Get the settings.
866 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700867 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800868
Chad Brubaker97bccee2017-01-05 15:51:41 -0800869 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
870 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800871
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800873
Svetoslav7ec28e82015-05-20 17:01:10 -0700874 String[] normalizedProjection = normalizeProjection(projection);
875 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800876
Svetoslav7ec28e82015-05-20 17:01:10 -0700877 // Anyone can get the global settings, so no security checks.
878 for (int i = 0; i < nameCount; i++) {
879 String name = names.get(i);
880 Setting setting = settingsState.getSettingLocked(name);
881 appendSettingToCursor(result, setting);
882 }
883
884 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800885 }
Svetoslav683914b2015-01-15 14:22:26 -0800886 }
887
Svetoslav7ec28e82015-05-20 17:01:10 -0700888 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800889 if (DEBUG) {
890 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
891 }
892
Chad Brubaker97bccee2017-01-05 15:51:41 -0800893 // Ensure the caller can access the setting.
894 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
895
Svetoslav683914b2015-01-15 14:22:26 -0800896 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700897 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700898 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700899 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800900 }
Svetoslav683914b2015-01-15 14:22:26 -0800901 }
902
Svetoslav Ganove080da92016-12-21 17:10:35 -0800903 private boolean updateGlobalSetting(String name, String value, String tag,
904 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800905 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800906 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
907 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
908 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800909 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800910 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
911 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800912 }
913
Svetoslav Ganove080da92016-12-21 17:10:35 -0800914 private boolean insertGlobalSetting(String name, String value, String tag,
915 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700916 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800917 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
918 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
919 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700920 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800921 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
922 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700923 }
924
Svet Ganov53a441c2016-04-19 19:38:00 -0700925 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800926 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800927 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
928 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800929 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800930 return mutateGlobalSetting(name, null, null, false, requestingUserId,
931 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800932 }
933
Svetoslav Ganove080da92016-12-21 17:10:35 -0800934 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
935 if (DEBUG) {
936 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
937 + mode + ", " + tag + ")");
938 }
939 mutateGlobalSetting(null, null, tag, false, requestingUserId,
940 MUTATION_OPERATION_RESET, false, mode);
941 }
942
943 private boolean mutateGlobalSetting(String name, String value, String tag,
944 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
945 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800946 // Make sure the caller can change the settings - treated as secure.
947 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
948
Svetoslav683914b2015-01-15 14:22:26 -0800949 // Resolve the userId on whose behalf the call is made.
950 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
951
Makoto Onuki28da2e32015-11-20 11:30:44 -0800952 // If this is a setting that is currently restricted for this user, do not allow
953 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800954 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100955 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800956 return false;
957 }
958
959 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 synchronized (mLock) {
961 switch (operation) {
962 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800963 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
964 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800965 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700966 }
Svetoslav683914b2015-01-15 14:22:26 -0800967
Svetoslav7ec28e82015-05-20 17:01:10 -0700968 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700969 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800970 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700971 }
Svetoslav683914b2015-01-15 14:22:26 -0800972
Svetoslav7ec28e82015-05-20 17:01:10 -0700973 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800974 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
975 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800976 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700977 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800978
979 case MUTATION_OPERATION_RESET: {
980 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
981 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
982 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800983 }
984 }
985
986 return false;
987 }
988
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800990 if (DEBUG) {
991 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
992 }
993
994 // Resolve the userId on whose behalf the call is made.
995 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
996
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800998 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800999
Svetoslav7ec28e82015-05-20 17:01:10 -07001000 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001001
Svetoslav7ec28e82015-05-20 17:01:10 -07001002 String[] normalizedProjection = normalizeProjection(projection);
1003 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001004
Svetoslav7ec28e82015-05-20 17:01:10 -07001005 for (int i = 0; i < nameCount; i++) {
1006 String name = names.get(i);
1007 // Determine the owning user as some profile settings are cloned from the parent.
1008 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1009 name);
Svetoslav683914b2015-01-15 14:22:26 -08001010
Svetoslav7ec28e82015-05-20 17:01:10 -07001011 // Special case for location (sigh).
1012 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001013 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001014 }
Svetoslav683914b2015-01-15 14:22:26 -08001015
Mark Rathjen7599f132017-01-23 14:15:54 -08001016 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001017 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1018 final Setting setting;
1019 if (isNewSsaidSetting(name)) {
1020 setting = getSsaidSettingLocked(owningUserId);
1021 } else {
1022 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1023 name);
1024 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001025 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001026 }
1027
Svetoslav7ec28e82015-05-20 17:01:10 -07001028 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001029 }
Svetoslav683914b2015-01-15 14:22:26 -08001030 }
1031
Svetoslav7ec28e82015-05-20 17:01:10 -07001032 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001033 if (DEBUG) {
1034 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1035 }
1036
1037 // Resolve the userId on whose behalf the call is made.
1038 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1039
Chad Brubaker97bccee2017-01-05 15:51:41 -08001040 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001041 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001042
Svetoslav683914b2015-01-15 14:22:26 -08001043 // Determine the owning user as some profile settings are cloned from the parent.
1044 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1045
1046 // Special case for location (sigh).
1047 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001048 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1049 owningUserId);
1050 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001051 }
1052
1053 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001054 synchronized (mLock) {
Mark Rathjen7599f132017-01-23 14:15:54 -08001055 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001056 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1057 if (isNewSsaidSetting(name)) {
1058 return getSsaidSettingLocked(owningUserId);
1059 }
1060
Svet Ganov53a441c2016-04-19 19:38:00 -07001061 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001062 owningUserId, name);
1063 }
Svetoslav683914b2015-01-15 14:22:26 -08001064 }
1065
Mark Rathjend891f012017-01-19 04:10:37 +00001066 private boolean isNewSsaidSetting(String name) {
1067 return Settings.Secure.ANDROID_ID.equals(name)
1068 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1069 }
1070
1071 private Setting getSsaidSettingLocked(int owningUserId) {
1072 // Get uid of caller (key) used to store ssaid value
1073 String name = Integer.toString(
1074 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1075
1076 if (DEBUG) {
1077 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1078 }
1079
1080 // Retrieve the ssaid from the table if present.
1081 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1082 name);
1083
1084 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001085 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00001086 return mSettingsRegistry.generateSsaidLocked(getCallingPackage(), owningUserId);
1087 }
1088
1089 return ssaid;
1090 }
1091
Svetoslav Ganove080da92016-12-21 17:10:35 -08001092 private boolean insertSecureSetting(String name, String value, String tag,
1093 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001094 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001095 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001096 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1097 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001098 }
1099
Svetoslav Ganove080da92016-12-21 17:10:35 -08001100 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1101 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001102 }
1103
Svet Ganov53a441c2016-04-19 19:38:00 -07001104 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001105 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001106 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1107 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001108 }
1109
Svetoslav Ganove080da92016-12-21 17:10:35 -08001110 return mutateSecureSetting(name, null, null, false, requestingUserId,
1111 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001112 }
1113
Svetoslav Ganove080da92016-12-21 17:10:35 -08001114 private boolean updateSecureSetting(String name, String value, String tag,
1115 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001116 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001117 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001118 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1119 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001120 }
1121
Svetoslav Ganove080da92016-12-21 17:10:35 -08001122 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1123 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001124 }
1125
Svetoslav Ganove080da92016-12-21 17:10:35 -08001126 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1127 if (DEBUG) {
1128 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1129 + mode + ", " + tag + ")");
1130 }
1131
1132 mutateSecureSetting(null, null, tag, false, requestingUserId,
1133 MUTATION_OPERATION_RESET, false, mode);
1134 }
1135
1136 private boolean mutateSecureSetting(String name, String value, String tag,
1137 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1138 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001139 // Make sure the caller can change the settings.
1140 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1141
Svetoslav683914b2015-01-15 14:22:26 -08001142 // Resolve the userId on whose behalf the call is made.
1143 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1144
Makoto Onuki28da2e32015-11-20 11:30:44 -08001145 // If this is a setting that is currently restricted for this user, do not allow
1146 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001147 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001148 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001149 return false;
1150 }
1151
1152 // Determine the owning user as some profile settings are cloned from the parent.
1153 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1154
1155 // Only the owning user can change the setting.
1156 if (owningUserId != callingUserId) {
1157 return false;
1158 }
1159
1160 // Special cases for location providers (sigh).
1161 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001162 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1163 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001164 }
1165
1166 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001167 synchronized (mLock) {
1168 switch (operation) {
1169 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001170 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001171 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001172 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001173 }
Svetoslav683914b2015-01-15 14:22:26 -08001174
Svetoslav7ec28e82015-05-20 17:01:10 -07001175 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001176 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001177 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001178 }
Svetoslav683914b2015-01-15 14:22:26 -08001179
Svetoslav7ec28e82015-05-20 17:01:10 -07001180 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001181 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001182 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001183 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001184 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001185
1186 case MUTATION_OPERATION_RESET: {
1187 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1188 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1189 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001190 }
1191 }
1192
1193 return false;
1194 }
1195
Svetoslav7ec28e82015-05-20 17:01:10 -07001196 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001197 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001198 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001199 }
1200
1201 // Resolve the userId on whose behalf the call is made.
1202 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1203
Svetoslav7ec28e82015-05-20 17:01:10 -07001204 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001205 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001206
Svetoslav7ec28e82015-05-20 17:01:10 -07001207 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001208
Svetoslav7ec28e82015-05-20 17:01:10 -07001209 String[] normalizedProjection = normalizeProjection(projection);
1210 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001211
Svetoslav7ec28e82015-05-20 17:01:10 -07001212 for (int i = 0; i < nameCount; i++) {
1213 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001214
Svetoslav7ec28e82015-05-20 17:01:10 -07001215 // Determine the owning user as some profile settings are cloned from the parent.
1216 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1217 name);
Svetoslav683914b2015-01-15 14:22:26 -08001218
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001220 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001221 appendSettingToCursor(result, setting);
1222 }
1223
1224 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001225 }
Svetoslav683914b2015-01-15 14:22:26 -08001226 }
1227
Svetoslav7ec28e82015-05-20 17:01:10 -07001228 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001229 if (DEBUG) {
1230 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1231 }
1232
1233 // Resolve the userId on whose behalf the call is made.
1234 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1235
Chad Brubaker97bccee2017-01-05 15:51:41 -08001236 // Ensure the caller can access the setting.
Chad Brubaker7fe0a5a2017-02-18 11:41:26 -08001237 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001238
Svetoslav683914b2015-01-15 14:22:26 -08001239 // Determine the owning user as some profile settings are cloned from the parent.
1240 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1241
1242 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001243 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001244 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001245 }
Svetoslav683914b2015-01-15 14:22:26 -08001246 }
1247
Svetoslav7ec28e82015-05-20 17:01:10 -07001248 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001249 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001250 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001251 + requestingUserId + ")");
1252 }
1253
Svetoslav7ec28e82015-05-20 17:01:10 -07001254 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001255 }
1256
Svetoslav7ec28e82015-05-20 17:01:10 -07001257 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001258 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001259 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001260 }
1261
Svetoslav7ec28e82015-05-20 17:01:10 -07001262 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001263 }
1264
Svetoslav7ec28e82015-05-20 17:01:10 -07001265 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001266 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001267 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001268 + requestingUserId + ")");
1269 }
1270
Svetoslav7ec28e82015-05-20 17:01:10 -07001271 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001272 }
1273
Svetoslav7ec28e82015-05-20 17:01:10 -07001274 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001275 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001276 if (!hasWriteSecureSettingsPermission()) {
1277 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1278 // operation is allowed for the calling package through appops.
1279 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1280 Binder.getCallingUid(), getCallingPackage(), true)) {
1281 return false;
1282 }
Svetoslav683914b2015-01-15 14:22:26 -08001283 }
1284
Svetoslav683914b2015-01-15 14:22:26 -08001285 // Resolve the userId on whose behalf the call is made.
1286 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1287
Svetoslavd8d25e02015-11-20 13:09:26 -08001288 // Enforce what the calling package can mutate the system settings.
1289 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1290
Svetoslav683914b2015-01-15 14:22:26 -08001291 // Determine the owning user as some profile settings are cloned from the parent.
1292 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1293
1294 // Only the owning user id can change the setting.
1295 if (owningUserId != callingUserId) {
1296 return false;
1297 }
1298
Jeff Sharkey413573a2016-02-22 17:52:45 -07001299 // Invalidate any relevant cache files
1300 String cacheName = null;
1301 if (Settings.System.RINGTONE.equals(name)) {
1302 cacheName = Settings.System.RINGTONE_CACHE;
1303 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1304 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1305 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1306 cacheName = Settings.System.ALARM_ALERT_CACHE;
1307 }
1308 if (cacheName != null) {
1309 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001310 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001311 cacheFile.delete();
1312 }
1313
Svetoslav683914b2015-01-15 14:22:26 -08001314 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001315 synchronized (mLock) {
1316 switch (operation) {
1317 case MUTATION_OPERATION_INSERT: {
1318 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001319 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001320 owningUserId, name, value, null, false, getCallingPackage(),
1321 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001322 }
1323
1324 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001325 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001326 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001327 }
1328
1329 case MUTATION_OPERATION_UPDATE: {
1330 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001331 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001332 owningUserId, name, value, null, false, getCallingPackage(),
1333 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001334 }
Svetoslav683914b2015-01-15 14:22:26 -08001335 }
1336
Svetoslav7ec28e82015-05-20 17:01:10 -07001337 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001338 }
Svetoslav683914b2015-01-15 14:22:26 -08001339 }
1340
Billy Lau6ad2d662015-07-18 00:26:58 +01001341 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001342 // Write secure settings is a more protected permission. If caller has it we are good.
1343 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1344 == PackageManager.PERMISSION_GRANTED) {
1345 return true;
1346 }
1347
Svetoslavf41334b2015-06-23 12:06:03 -07001348 return false;
1349 }
1350
Svetoslav683914b2015-01-15 14:22:26 -08001351 private void validateSystemSettingValue(String name, String value) {
1352 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1353 if (validator != null && !validator.validate(value)) {
1354 throw new IllegalArgumentException("Invalid value: " + value
1355 + " for setting: " + name);
1356 }
1357 }
1358
1359 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1360 int owningUserId) {
1361 // Optimization - location providers are restricted only for managed profiles.
1362 if (callingUserId == owningUserId) {
1363 return false;
1364 }
1365 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1366 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1367 new UserHandle(callingUserId))) {
1368 return true;
1369 }
1370 return false;
1371 }
1372
Makoto Onuki28da2e32015-11-20 11:30:44 -08001373 /**
1374 * Checks whether changing a setting to a value is prohibited by the corresponding user
1375 * restriction.
1376 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001377 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1378 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001379 *
1380 * @return true if the change is prohibited, false if the change is allowed.
1381 */
1382 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001383 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001384 String restriction;
1385 switch (setting) {
1386 case Settings.Secure.LOCATION_MODE:
1387 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1388 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1389 // here normally, but we still protect it here from a direct provider write.
1390 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1391 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1392 break;
1393
1394 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1395 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1396 // a provider, which should be allowed even if the user restriction is set.
1397 if (value != null && value.startsWith("-")) return false;
1398 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1399 break;
1400
1401 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1402 if ("0".equals(value)) return false;
1403 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1404 break;
1405
1406 case Settings.Global.ADB_ENABLED:
1407 if ("0".equals(value)) return false;
1408 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1409 break;
1410
1411 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1412 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1413 if ("1".equals(value)) return false;
1414 restriction = UserManager.ENSURE_VERIFY_APPS;
1415 break;
1416
1417 case Settings.Global.PREFERRED_NETWORK_MODE:
1418 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1419 break;
1420
Victor Chang9c7b7062016-07-12 23:47:29 +01001421 case Settings.Secure.ALWAYS_ON_VPN_APP:
1422 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1423 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001424 final int appId = UserHandle.getAppId(callingUid);
1425 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001426 return false;
1427 }
1428 restriction = UserManager.DISALLOW_CONFIG_VPN;
1429 break;
1430
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001431 case Settings.Global.SAFE_BOOT_DISALLOWED:
1432 if ("1".equals(value)) return false;
1433 restriction = UserManager.DISALLOW_SAFE_BOOT;
1434 break;
1435
Makoto Onuki28da2e32015-11-20 11:30:44 -08001436 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001437 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001438 if ("0".equals(value)) return false;
1439 restriction = UserManager.DISALLOW_DATA_ROAMING;
1440 break;
1441 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001442 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001443 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001444
1445 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001446 }
1447
1448 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1449 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1450 }
1451
1452 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001453 final int parentId;
1454 // Resolves dependency if setting has a dependency and the calling user has a parent
1455 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1456 && (parentId = getGroupParentLocked(userId)) != userId) {
1457 // The setting has a dependency and the profile has a parent
1458 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001459 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1460 final long token = Binder.clearCallingIdentity();
1461 try {
1462 Setting settingObj = getSecureSetting(dependency, userId);
1463 if (settingObj != null && settingObj.getValue().equals("1")) {
1464 return parentId;
1465 }
1466 } finally {
1467 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001468 }
1469 }
Svetoslav683914b2015-01-15 14:22:26 -08001470 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1471 }
1472
1473 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1474 final int parentId = getGroupParentLocked(userId);
1475 if (parentId != userId && keys.contains(name)) {
1476 return parentId;
1477 }
1478 return userId;
1479 }
1480
Svetoslavf41334b2015-06-23 12:06:03 -07001481 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001482 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001483 // System/root/shell can mutate whatever secure settings they want.
1484 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001485 final int appId = UserHandle.getAppId(callingUid);
1486 if (appId == android.os.Process.SYSTEM_UID
1487 || appId == Process.SHELL_UID
1488 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001489 return;
1490 }
1491
1492 switch (operation) {
1493 case MUTATION_OPERATION_INSERT:
1494 // Insert updates.
1495 case MUTATION_OPERATION_UPDATE: {
1496 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1497 return;
1498 }
1499
1500 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001501 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001502
1503 // Privileged apps can do whatever they want.
1504 if ((packageInfo.applicationInfo.privateFlags
1505 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1506 return;
1507 }
1508
1509 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1510 packageInfo.applicationInfo.targetSdkVersion, name);
1511 } break;
1512
1513 case MUTATION_OPERATION_DELETE: {
1514 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1515 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1516 throw new IllegalArgumentException("You cannot delete system defined"
1517 + " secure settings.");
1518 }
1519
1520 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001521 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001522
1523 // Privileged apps can do whatever they want.
1524 if ((packageInfo.applicationInfo.privateFlags &
1525 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1526 return;
1527 }
1528
1529 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1530 packageInfo.applicationInfo.targetSdkVersion, name);
1531 } break;
1532 }
1533 }
1534
Todd Kennedybe0b8892017-02-15 14:13:52 -08001535 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001536 switch (settingsType) {
1537 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001538 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001539 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001540 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001541 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001542 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001543 default:
1544 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1545 }
1546 }
1547
1548 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
1549 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001550 if (ai.isInstantApp()) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001551 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001552 } else {
1553 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1554 }
1555 }
1556
1557 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
1558 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1559 return;
1560 }
1561 ApplicationInfo ai = getCallingApplicationInfoOrThrow(userId);
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001562 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001563 return;
1564 }
Todd Kennedybe0b8892017-02-15 14:13:52 -08001565 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001566 throw new SecurityException("Setting " + settingName + " is not accessible from"
1567 + " ephemeral package " + getCallingPackage());
1568 }
1569 }
1570
1571 private ApplicationInfo getCallingApplicationInfoOrThrow(int userId) {
1572 ApplicationInfo ai = null;
1573 try {
1574 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0 , userId);
1575 } catch (RemoteException ignored) {
1576 }
1577 if (ai == null) {
1578 throw new IllegalStateException("Failed to lookup info for package "
1579 + getCallingPackage());
1580 }
1581 return ai;
1582 }
1583
Xiaohui Chen43765b72015-08-31 10:57:33 -07001584 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001585 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001586 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1587 getCallingPackage(), 0, userId);
1588 if (packageInfo != null) {
1589 return packageInfo;
1590 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001591 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001592 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001593 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001594 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001595 }
1596
1597 private int getGroupParentLocked(int userId) {
1598 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001599 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001600 return userId;
1601 }
1602 // We are in the same process with the user manager and the returned
1603 // user info is a cached instance, so just look up instead of cache.
1604 final long identity = Binder.clearCallingIdentity();
1605 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001606 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001607 UserInfo userInfo = mUserManager.getProfileParent(userId);
1608 return (userInfo != null) ? userInfo.id : userId;
1609 } finally {
1610 Binder.restoreCallingIdentity(identity);
1611 }
1612 }
1613
Svetoslav683914b2015-01-15 14:22:26 -08001614 private void enforceWritePermission(String permission) {
1615 if (getContext().checkCallingOrSelfPermission(permission)
1616 != PackageManager.PERMISSION_GRANTED) {
1617 throw new SecurityException("Permission denial: writing to settings requires:"
1618 + permission);
1619 }
1620 }
1621
1622 /*
1623 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1624 * This setting contains a list of the currently enabled location providers.
1625 * But helper functions in android.providers.Settings can enable or disable
1626 * a single provider by using a "+" or "-" prefix before the provider name.
1627 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001628 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1629 * is set, the said method will only allow values with the "-" prefix.
1630 *
Svetoslav683914b2015-01-15 14:22:26 -08001631 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001632 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001633 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1634 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001635 if (TextUtils.isEmpty(value)) {
1636 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001637 }
1638
Svetoslav683914b2015-01-15 14:22:26 -08001639 final char prefix = value.charAt(0);
1640 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001641 if (forceNotify) {
1642 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1643 mSettingsRegistry.notifyForSettingsChange(key,
1644 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1645 }
Svetoslav683914b2015-01-15 14:22:26 -08001646 return false;
1647 }
1648
1649 // skip prefix
1650 value = value.substring(1);
1651
Svetoslav7ec28e82015-05-20 17:01:10 -07001652 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001653 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001654 if (settingValue == null) {
1655 return false;
1656 }
Svetoslav683914b2015-01-15 14:22:26 -08001657
1658 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1659
1660 int index = oldProviders.indexOf(value);
1661 int end = index + value.length();
1662
1663 // check for commas to avoid matching on partial string
1664 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1665 index = -1;
1666 }
1667
1668 // check for commas to avoid matching on partial string
1669 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1670 index = -1;
1671 }
1672
1673 String newProviders;
1674
1675 if (prefix == '+' && index < 0) {
1676 // append the provider to the list if not present
1677 if (oldProviders.length() == 0) {
1678 newProviders = value;
1679 } else {
1680 newProviders = oldProviders + ',' + value;
1681 }
1682 } else if (prefix == '-' && index >= 0) {
1683 // remove the provider from the list if present
1684 // remove leading or trailing comma
1685 if (index > 0) {
1686 index--;
1687 } else if (end < oldProviders.length()) {
1688 end++;
1689 }
1690
1691 newProviders = oldProviders.substring(0, index);
1692 if (end < oldProviders.length()) {
1693 newProviders += oldProviders.substring(end);
1694 }
1695 } else {
1696 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001697 if (forceNotify) {
1698 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1699 mSettingsRegistry.notifyForSettingsChange(key,
1700 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1701 }
Svetoslav683914b2015-01-15 14:22:26 -08001702 return false;
1703 }
1704
Svet Ganov53a441c2016-04-19 19:38:00 -07001705 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001706 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001707 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001708 }
1709
Svetoslav683914b2015-01-15 14:22:26 -08001710 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1711 int targetSdkVersion, String name) {
1712 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1713 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1714 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1715 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1716 + " This will soon become an error.");
1717 } else {
1718 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1719 + " This will soon become an error.");
1720 }
1721 } else {
1722 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1723 throw new IllegalArgumentException("You cannot change private secure settings.");
1724 } else {
1725 throw new IllegalArgumentException("You cannot keep your settings in"
1726 + " the secure settings.");
1727 }
1728 }
1729 }
1730
1731 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1732 if (requestingUserId == UserHandle.getCallingUserId()) {
1733 return requestingUserId;
1734 }
1735 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1736 Binder.getCallingUid(), requestingUserId, false, true,
1737 "get/set setting for user", null);
1738 }
1739
Svet Ganov53a441c2016-04-19 19:38:00 -07001740 private Bundle packageValueForCallResult(Setting setting,
1741 boolean trackingGeneration) {
1742 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001743 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001744 return NULL_SETTING_BUNDLE;
1745 }
1746 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001747 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001748 Bundle result = new Bundle();
1749 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001750 !setting.isNull() ? setting.getValue() : null);
1751 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001752 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001753 }
1754
1755 private static int getRequestingUserId(Bundle args) {
1756 final int callingUserId = UserHandle.getCallingUserId();
1757 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1758 : callingUserId;
1759 }
1760
Svet Ganov53a441c2016-04-19 19:38:00 -07001761 private boolean isTrackingGeneration(Bundle args) {
1762 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1763 }
1764
Svetoslav683914b2015-01-15 14:22:26 -08001765 private static String getSettingValue(Bundle args) {
1766 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1767 }
1768
Svetoslav Ganove080da92016-12-21 17:10:35 -08001769 private static String getSettingTag(Bundle args) {
1770 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1771 }
1772
1773 private static boolean getSettingMakeDefault(Bundle args) {
1774 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1775 }
1776
1777 private static int getResetModeEnforcingPermission(Bundle args) {
1778 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1779 switch (mode) {
1780 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1781 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1782 throw new SecurityException("Only system, shell/root on a "
1783 + "debuggable build can reset to untrusted defaults");
1784 }
1785 return mode;
1786 }
1787 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1788 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1789 throw new SecurityException("Only system, shell/root on a "
1790 + "debuggable build can reset untrusted changes");
1791 }
1792 return mode;
1793 }
1794 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1795 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1796 throw new SecurityException("Only system, shell/root on a "
1797 + "debuggable build can reset to trusted defaults");
1798 }
1799 return mode;
1800 }
1801 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1802 return mode;
1803 }
1804 }
1805 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1806 }
1807
1808 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1809 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1810 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1811 && (appId == SHELL_UID || appId == ROOT_UID));
1812 }
1813
Svetoslav683914b2015-01-15 14:22:26 -08001814 private static String getValidTableOrThrow(Uri uri) {
1815 if (uri.getPathSegments().size() > 0) {
1816 String table = uri.getPathSegments().get(0);
1817 if (DatabaseHelper.isValidTable(table)) {
1818 return table;
1819 }
1820 throw new IllegalArgumentException("Bad root path: " + table);
1821 }
1822 throw new IllegalArgumentException("Invalid URI:" + uri);
1823 }
1824
1825 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001826 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001827 return new MatrixCursor(projection, 0);
1828 }
1829 MatrixCursor cursor = new MatrixCursor(projection, 1);
1830 appendSettingToCursor(cursor, setting);
1831 return cursor;
1832 }
1833
1834 private static String[] normalizeProjection(String[] projection) {
1835 if (projection == null) {
1836 return ALL_COLUMNS;
1837 }
1838
1839 final int columnCount = projection.length;
1840 for (int i = 0; i < columnCount; i++) {
1841 String column = projection[i];
1842 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1843 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001844 }
1845 }
1846
Svetoslav683914b2015-01-15 14:22:26 -08001847 return projection;
1848 }
1849
1850 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001851 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001852 return;
1853 }
Svetoslav683914b2015-01-15 14:22:26 -08001854 final int columnCount = cursor.getColumnCount();
1855
1856 String[] values = new String[columnCount];
1857
1858 for (int i = 0; i < columnCount; i++) {
1859 String column = cursor.getColumnName(i);
1860
1861 switch (column) {
1862 case Settings.NameValueTable._ID: {
1863 values[i] = setting.getId();
1864 } break;
1865
1866 case Settings.NameValueTable.NAME: {
1867 values[i] = setting.getName();
1868 } break;
1869
1870 case Settings.NameValueTable.VALUE: {
1871 values[i] = setting.getValue();
1872 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001873 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001874 }
1875
Svetoslav683914b2015-01-15 14:22:26 -08001876 cursor.addRow(values);
1877 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001878
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001879 private static boolean isKeyValid(String key) {
1880 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1881 }
1882
Svetoslav683914b2015-01-15 14:22:26 -08001883 private static final class Arguments {
1884 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1885 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1886
1887 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1888 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1889
1890 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1891 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1892
1893 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1894 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1895
1896 public final String table;
1897 public final String name;
1898
1899 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1900 final int segmentSize = uri.getPathSegments().size();
1901 switch (segmentSize) {
1902 case 1: {
1903 if (where != null
1904 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1905 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1906 && whereArgs.length == 1) {
1907 name = whereArgs[0];
1908 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001909 return;
Svetoslav683914b2015-01-15 14:22:26 -08001910 } else if (where != null
1911 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1912 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1913 final int startIndex = Math.max(where.indexOf("'"),
1914 where.indexOf("\"")) + 1;
1915 final int endIndex = Math.max(where.lastIndexOf("'"),
1916 where.lastIndexOf("\""));
1917 name = where.substring(startIndex, endIndex);
1918 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001919 return;
Svetoslav683914b2015-01-15 14:22:26 -08001920 } else if (supportAll && where == null && whereArgs == null) {
1921 name = null;
1922 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001923 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001924 }
Svetoslav683914b2015-01-15 14:22:26 -08001925 } break;
1926
Svetoslav28494652015-02-12 14:11:42 -08001927 case 2: {
1928 if (where == null && whereArgs == null) {
1929 name = uri.getPathSegments().get(1);
1930 table = computeTableForSetting(uri, name);
1931 return;
1932 }
1933 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001934 }
Svetoslav28494652015-02-12 14:11:42 -08001935
1936 EventLogTags.writeUnsupportedSettingsQuery(
1937 uri.toSafeString(), where, Arrays.toString(whereArgs));
1938 String message = String.format( "Supported SQL:\n"
1939 + " uri content://some_table/some_property with null where and where args\n"
1940 + " uri content://some_table with query name=? and single name as arg\n"
1941 + " uri content://some_table with query name=some_name and null args\n"
1942 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1943 Arrays.toString(whereArgs));
1944 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001945 }
1946
Svetoslav28494652015-02-12 14:11:42 -08001947 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001948 String table = getValidTableOrThrow(uri);
1949
1950 if (name != null) {
1951 if (sSystemMovedToSecureSettings.contains(name)) {
1952 table = TABLE_SECURE;
1953 }
1954
1955 if (sSystemMovedToGlobalSettings.contains(name)) {
1956 table = TABLE_GLOBAL;
1957 }
1958
1959 if (sSecureMovedToGlobalSettings.contains(name)) {
1960 table = TABLE_GLOBAL;
1961 }
1962
1963 if (sGlobalMovedToSecureSettings.contains(name)) {
1964 table = TABLE_SECURE;
1965 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001966 }
Svetoslav683914b2015-01-15 14:22:26 -08001967
1968 return table;
1969 }
1970 }
1971
1972 final class SettingsRegistry {
1973 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1974
Svetoslav683914b2015-01-15 14:22:26 -08001975 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1976 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1977 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00001978 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
1979
1980 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08001981
1982 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1983
Svet Ganov53a441c2016-04-19 19:38:00 -07001984 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001985
Svetoslav7e0683b2015-08-03 16:02:52 -07001986 private final Handler mHandler;
1987
Svet Ganov53a441c2016-04-19 19:38:00 -07001988 private final BackupManager mBackupManager;
1989
Svetoslav683914b2015-01-15 14:22:26 -08001990 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001991 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001992 mGenerationRegistry = new GenerationRegistry(mLock);
1993 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001994 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00001995 syncSsaidTableOnStart();
1996 }
1997
1998 private void generateUserKeyLocked(int userId) {
1999 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002000 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002001 final SecureRandom rand = new SecureRandom();
2002 rand.nextBytes(keyBytes);
2003
2004 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002005 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002006
2007 // Store the key in the ssaid table.
2008 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2009 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2010 true, SettingsState.SYSTEM_PACKAGE_NAME);
2011
2012 if (!success) {
2013 throw new IllegalStateException("Ssaid settings not accessible");
2014 }
2015 }
2016
Mark Rathjen7599f132017-01-23 14:15:54 -08002017 private byte[] getLengthPrefix(byte[] data) {
2018 return ByteBuffer.allocate(4).putInt(data.length).array();
2019 }
2020
Mark Rathjend891f012017-01-19 04:10:37 +00002021 public Setting generateSsaidLocked(String packageName, int userId) {
2022 final PackageInfo packageInfo;
2023 try {
2024 packageInfo = mPackageManager.getPackageInfo(packageName,
2025 PackageManager.GET_SIGNATURES, userId);
2026 } catch (RemoteException e) {
2027 throw new IllegalStateException("Package info doesn't exist");
2028 }
2029
2030 // Read the user's key from the ssaid table.
2031 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002032 if (userKeySetting == null || userKeySetting.isNull()
2033 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002034 // Lazy initialize and store the user key.
2035 generateUserKeyLocked(userId);
2036 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002037 if (userKeySetting == null || userKeySetting.isNull()
2038 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002039 throw new IllegalStateException("User key not accessible");
2040 }
2041 }
2042 final String userKey = userKeySetting.getValue();
2043
2044 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002045 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2046
2047 // Validate that the key is of expected length.
2048 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2049 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002050 throw new IllegalStateException("User key invalid");
2051 }
2052
Mark Rathjen7599f132017-01-23 14:15:54 -08002053 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002054 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002055 m = Mac.getInstance("HmacSHA256");
2056 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002057 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002058 throw new IllegalStateException("HmacSHA256 is not available", e);
2059 } catch (InvalidKeyException e) {
2060 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002061 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002062
2063 // Mac the package name and each of the signatures.
2064 byte[] packageNameBytes = packageInfo.packageName.getBytes(StandardCharsets.UTF_8);
2065 m.update(getLengthPrefix(packageNameBytes), 0, 4);
2066 m.update(packageNameBytes);
2067 for (int i = 0; i < packageInfo.signatures.length; i++) {
2068 byte[] sig = packageInfo.signatures[i].toByteArray();
2069 m.update(getLengthPrefix(sig), 0, 4);
2070 m.update(sig);
2071 }
Mark Rathjend891f012017-01-19 04:10:37 +00002072
2073 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002074 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2075 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002076
2077 // Save the ssaid in the ssaid table.
2078 final String uid = Integer.toString(packageInfo.applicationInfo.uid);
2079 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2080 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
2081 packageName);
2082
2083 if (!success) {
2084 throw new IllegalStateException("Ssaid settings not accessible");
2085 }
2086
2087 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2088 }
2089
2090 public void syncSsaidTableOnStart() {
2091 synchronized (mLock) {
2092 // Verify that each user's packages and ssaid's are in sync.
2093 for (UserInfo user : mUserManager.getUsers(true)) {
2094 // Get all uids for the user's packages.
2095 final List<PackageInfo> packages;
2096 try {
2097 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2098 } catch (RemoteException e) {
2099 throw new IllegalStateException("Package manager not available");
2100 }
2101 final Set<String> appUids = new HashSet<>();
2102 for (PackageInfo info : packages) {
2103 appUids.add(Integer.toString(info.applicationInfo.uid));
2104 }
2105
2106 // Get all uids currently stored in the user's ssaid table.
2107 final Set<String> ssaidUids = new HashSet<>(
2108 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2109 ssaidUids.remove(SSAID_USER_KEY);
2110
2111 // Perform a set difference for the appUids and ssaidUids.
2112 ssaidUids.removeAll(appUids);
2113
2114 // If there are ssaidUids left over they need to be removed from the table.
2115 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2116 user.id);
2117 for (String uid : ssaidUids) {
2118 ssaidSettings.deleteSettingLocked(uid);
2119 }
2120 }
2121 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002122 }
2123
Svetoslav683914b2015-01-15 14:22:26 -08002124 public List<String> getSettingsNamesLocked(int type, int userId) {
2125 final int key = makeKey(type, userId);
2126 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002127 if (settingsState == null) {
2128 return new ArrayList<String>();
2129 }
Svetoslav683914b2015-01-15 14:22:26 -08002130 return settingsState.getSettingNamesLocked();
2131 }
2132
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002133 public SparseBooleanArray getKnownUsersLocked() {
2134 SparseBooleanArray users = new SparseBooleanArray();
2135 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2136 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2137 }
2138 return users;
2139 }
2140
Svetoslav683914b2015-01-15 14:22:26 -08002141 public SettingsState getSettingsLocked(int type, int userId) {
2142 final int key = makeKey(type, userId);
2143 return peekSettingsStateLocked(key);
2144 }
2145
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002146 public boolean ensureSettingsForUserLocked(int userId) {
2147 // First make sure this user actually exists.
2148 if (mUserManager.getUserInfo(userId) == null) {
2149 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2150 return false;
2151 }
2152
Svetoslav683914b2015-01-15 14:22:26 -08002153 // Migrate the setting for this user if needed.
2154 migrateLegacySettingsForUserIfNeededLocked(userId);
2155
2156 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002157 if (userId == UserHandle.USER_SYSTEM) {
2158 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002159 ensureSettingsStateLocked(globalKey);
2160 }
2161
2162 // Ensure secure settings loaded.
2163 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2164 ensureSettingsStateLocked(secureKey);
2165
2166 // Make sure the secure settings have an Android id set.
2167 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2168 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2169
2170 // Ensure system settings loaded.
2171 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2172 ensureSettingsStateLocked(systemKey);
2173
Mark Rathjend891f012017-01-19 04:10:37 +00002174 // Ensure secure settings loaded.
2175 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2176 ensureSettingsStateLocked(ssaidKey);
2177
Svetoslav683914b2015-01-15 14:22:26 -08002178 // Upgrade the settings to the latest version.
2179 UpgradeController upgrader = new UpgradeController(userId);
2180 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002181 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002182 }
2183
2184 private void ensureSettingsStateLocked(int key) {
2185 if (mSettingsStates.get(key) == null) {
2186 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002187 SettingsState settingsState = new SettingsState(getContext(), mLock,
2188 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002189 mSettingsStates.put(key, settingsState);
2190 }
2191 }
2192
2193 public void removeUserStateLocked(int userId, boolean permanently) {
2194 // We always keep the global settings in memory.
2195
2196 // Nuke system settings.
2197 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2198 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2199 if (systemSettingsState != null) {
2200 if (permanently) {
2201 mSettingsStates.remove(systemKey);
2202 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002203 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002204 systemSettingsState.destroyLocked(new Runnable() {
2205 @Override
2206 public void run() {
2207 mSettingsStates.remove(systemKey);
2208 }
2209 });
2210 }
2211 }
2212
2213 // Nuke secure settings.
2214 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2215 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2216 if (secureSettingsState != null) {
2217 if (permanently) {
2218 mSettingsStates.remove(secureKey);
2219 secureSettingsState.destroyLocked(null);
2220 } else {
2221 secureSettingsState.destroyLocked(new Runnable() {
2222 @Override
2223 public void run() {
2224 mSettingsStates.remove(secureKey);
2225 }
2226 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002227 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002228 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002229
Mark Rathjend891f012017-01-19 04:10:37 +00002230 // Nuke ssaid settings.
2231 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2232 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2233 if (ssaidSettingsState != null) {
2234 if (permanently) {
2235 mSettingsStates.remove(ssaidKey);
2236 ssaidSettingsState.destroyLocked(null);
2237 } else {
2238 ssaidSettingsState.destroyLocked(new Runnable() {
2239 @Override
2240 public void run() {
2241 mSettingsStates.remove(ssaidKey);
2242 }
2243 });
2244 }
2245 }
2246
Svet Ganov53a441c2016-04-19 19:38:00 -07002247 // Nuke generation tracking data
2248 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002249 }
2250
Svetoslav683914b2015-01-15 14:22:26 -08002251 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002252 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2253 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002254 final int key = makeKey(type, userId);
2255
Svetoslav Ganove080da92016-12-21 17:10:35 -08002256 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002257 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002258 if (settingsState != null) {
2259 success = settingsState.insertSettingLocked(name, value,
2260 tag, makeDefault, packageName);
2261 }
Svetoslav683914b2015-01-15 14:22:26 -08002262
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002263 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2264 settingsState.persistSyncLocked();
2265 }
2266
Svet Ganov53a441c2016-04-19 19:38:00 -07002267 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002268 notifyForSettingsChange(key, name);
2269 }
2270 return success;
2271 }
2272
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002273 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2274 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002275 final int key = makeKey(type, userId);
2276
Svetoslav Ganove080da92016-12-21 17:10:35 -08002277 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002278 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002279 if (settingsState != null) {
2280 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002281 }
Svetoslav683914b2015-01-15 14:22:26 -08002282
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002283 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2284 settingsState.persistSyncLocked();
2285 }
2286
Svet Ganov53a441c2016-04-19 19:38:00 -07002287 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002288 notifyForSettingsChange(key, name);
2289 }
2290 return success;
2291 }
2292
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002293 public boolean updateSettingLocked(int type, int userId, String name, String value,
2294 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2295 Set<String> criticalSettings) {
2296 final int key = makeKey(type, userId);
2297
2298 boolean success = false;
2299 SettingsState settingsState = peekSettingsStateLocked(key);
2300 if (settingsState != null) {
2301 success = settingsState.updateSettingLocked(name, value, tag,
2302 makeDefault, packageName);
2303 }
2304
2305 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2306 settingsState.persistSyncLocked();
2307 }
2308
2309 if (forceNotify || success) {
2310 notifyForSettingsChange(key, name);
2311 }
2312
2313 return success;
2314 }
2315
Svetoslav683914b2015-01-15 14:22:26 -08002316 public Setting getSettingLocked(int type, int userId, String name) {
2317 final int key = makeKey(type, userId);
2318
2319 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002320 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002321 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002322 }
Mark Rathjend891f012017-01-19 04:10:37 +00002323
2324 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002325 return settingsState.getSettingLocked(name);
2326 }
2327
Svetoslav Ganove080da92016-12-21 17:10:35 -08002328 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2329 String tag) {
2330 final int key = makeKey(type, userId);
2331 SettingsState settingsState = peekSettingsStateLocked(key);
2332 if (settingsState == null) {
2333 return;
2334 }
2335
2336 switch (mode) {
2337 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2338 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002339 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002340 Setting setting = settingsState.getSettingLocked(name);
2341 if (packageName.equals(setting.getPackageName())) {
2342 if (tag != null && !tag.equals(setting.getTag())) {
2343 continue;
2344 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002345 if (settingsState.resetSettingLocked(name)) {
2346 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002347 notifyForSettingsChange(key, name);
2348 }
2349 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002350 if (someSettingChanged) {
2351 settingsState.persistSyncLocked();
2352 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002353 }
2354 } break;
2355
2356 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2357 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002358 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002359 Setting setting = settingsState.getSettingLocked(name);
2360 if (!SettingsState.isSystemPackage(getContext(),
2361 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002362 if (settingsState.resetSettingLocked(name)) {
2363 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002364 notifyForSettingsChange(key, name);
2365 }
2366 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002367 if (someSettingChanged) {
2368 settingsState.persistSyncLocked();
2369 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002370 }
2371 } break;
2372
2373 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2374 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002375 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002376 Setting setting = settingsState.getSettingLocked(name);
2377 if (!SettingsState.isSystemPackage(getContext(),
2378 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002379 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002380 if (settingsState.resetSettingLocked(name)) {
2381 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002382 notifyForSettingsChange(key, name);
2383 }
2384 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002385 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002386 notifyForSettingsChange(key, name);
2387 }
2388 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002389 if (someSettingChanged) {
2390 settingsState.persistSyncLocked();
2391 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002392 }
2393 } break;
2394
2395 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2396 for (String name : settingsState.getSettingNamesLocked()) {
2397 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002398 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002399 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002400 if (settingsState.resetSettingLocked(name)) {
2401 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002402 notifyForSettingsChange(key, name);
2403 }
2404 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002405 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002406 notifyForSettingsChange(key, name);
2407 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002408 if (someSettingChanged) {
2409 settingsState.persistSyncLocked();
2410 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002411 }
2412 } break;
2413 }
2414 }
2415
Svetoslav683914b2015-01-15 14:22:26 -08002416 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002417 // Global and secure settings are signature protected. Apps signed
2418 // by the platform certificate are generally not uninstalled and
2419 // the main exception is tests. We trust components signed
2420 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002421
2422 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2423 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002424 if (systemSettings != null) {
2425 systemSettings.onPackageRemovedLocked(packageName);
2426 }
Svetoslav683914b2015-01-15 14:22:26 -08002427 }
2428
Mark Rathjend891f012017-01-19 04:10:37 +00002429 public void onUidRemovedLocked(int uid) {
2430 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2431 UserHandle.getUserId(uid));
2432 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2433 }
2434
Svetoslav683914b2015-01-15 14:22:26 -08002435 private SettingsState peekSettingsStateLocked(int key) {
2436 SettingsState settingsState = mSettingsStates.get(key);
2437 if (settingsState != null) {
2438 return settingsState;
2439 }
2440
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002441 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2442 return null;
2443 }
Svetoslav683914b2015-01-15 14:22:26 -08002444 return mSettingsStates.get(key);
2445 }
2446
2447 private void migrateAllLegacySettingsIfNeeded() {
2448 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002449 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002450 File globalFile = getSettingsFile(key);
2451 if (globalFile.exists()) {
2452 return;
2453 }
2454
2455 final long identity = Binder.clearCallingIdentity();
2456 try {
2457 List<UserInfo> users = mUserManager.getUsers(true);
2458
2459 final int userCount = users.size();
2460 for (int i = 0; i < userCount; i++) {
2461 final int userId = users.get(i).id;
2462
2463 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2464 SQLiteDatabase database = dbHelper.getWritableDatabase();
2465 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2466
2467 // Upgrade to the latest version.
2468 UpgradeController upgrader = new UpgradeController(userId);
2469 upgrader.upgradeIfNeededLocked();
2470
2471 // Drop from memory if not a running user.
2472 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2473 removeUserStateLocked(userId, false);
2474 }
2475 }
2476 } finally {
2477 Binder.restoreCallingIdentity(identity);
2478 }
2479 }
2480 }
2481
2482 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2483 // Every user has secure settings and if no file we need to migrate.
2484 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2485 File secureFile = getSettingsFile(secureKey);
2486 if (secureFile.exists()) {
2487 return;
2488 }
2489
2490 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2491 SQLiteDatabase database = dbHelper.getWritableDatabase();
2492
2493 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2494 }
2495
2496 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2497 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002498 // Move over the system settings.
2499 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2500 ensureSettingsStateLocked(systemKey);
2501 SettingsState systemSettings = mSettingsStates.get(systemKey);
2502 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2503 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002504
2505 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002506 // Do this after System settings, since this is the first thing we check when deciding
2507 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002508 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2509 ensureSettingsStateLocked(secureKey);
2510 SettingsState secureSettings = mSettingsStates.get(secureKey);
2511 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2512 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2513 secureSettings.persistSyncLocked();
2514
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002515 // Move over the global settings if owner.
2516 // Do this last, since this is the first thing we check when deciding
2517 // to skip over migration from db to xml for owner user.
2518 if (userId == UserHandle.USER_SYSTEM) {
2519 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2520 ensureSettingsStateLocked(globalKey);
2521 SettingsState globalSettings = mSettingsStates.get(globalKey);
2522 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
2523 globalSettings.persistSyncLocked();
2524 }
Svetoslav683914b2015-01-15 14:22:26 -08002525
2526 // Drop the database as now all is moved and persisted.
2527 if (DROP_DATABASE_ON_MIGRATION) {
2528 dbHelper.dropDatabase();
2529 } else {
2530 dbHelper.backupDatabase();
2531 }
2532 }
2533
2534 private void migrateLegacySettingsLocked(SettingsState settingsState,
2535 SQLiteDatabase database, String table) {
2536 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2537 queryBuilder.setTables(table);
2538
2539 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2540 null, null, null, null, null);
2541
2542 if (cursor == null) {
2543 return;
2544 }
2545
2546 try {
2547 if (!cursor.moveToFirst()) {
2548 return;
2549 }
2550
2551 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2552 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2553
2554 settingsState.setVersionLocked(database.getVersion());
2555
2556 while (!cursor.isAfterLast()) {
2557 String name = cursor.getString(nameColumnIdx);
2558 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002559 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002560 SettingsState.SYSTEM_PACKAGE_NAME);
2561 cursor.moveToNext();
2562 }
2563 } finally {
2564 cursor.close();
2565 }
2566 }
2567
2568 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2569 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2570
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002571 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002572 return;
2573 }
2574
2575 final int userId = getUserIdFromKey(secureSettings.mKey);
2576
2577 final UserInfo user;
2578 final long identity = Binder.clearCallingIdentity();
2579 try {
2580 user = mUserManager.getUserInfo(userId);
2581 } finally {
2582 Binder.restoreCallingIdentity(identity);
2583 }
2584 if (user == null) {
2585 // Can happen due to races when deleting users - treat as benign.
2586 return;
2587 }
2588
2589 String androidId = Long.toHexString(new SecureRandom().nextLong());
2590 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002591 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002592
2593 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2594 + "] for user " + userId);
2595
2596 // Write a drop box entry if it's a restricted profile
2597 if (user.isRestricted()) {
2598 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2599 Context.DROPBOX_SERVICE);
2600 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2601 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2602 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2603 }
2604 }
2605 }
2606
2607 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002608 final int userId = getUserIdFromKey(key);
2609 Uri uri = getNotificationUriFor(key, name);
2610
Phil Weaver83fec002016-05-11 10:55:29 -07002611 mGenerationRegistry.incrementGeneration(key);
2612
Svetoslav7e0683b2015-08-03 16:02:52 -07002613 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2614 userId, 0, uri).sendToTarget();
2615
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002616 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002617 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2618 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002619 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2620 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002621 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002622 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2623 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002624 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002625
Svet Ganov53a441c2016-04-19 19:38:00 -07002626 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002627 }
2628
Svet Ganov53a441c2016-04-19 19:38:00 -07002629 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002630 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002631 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002632 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002633 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002634 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002635 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002636 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002637 final int key = makeKey(type, profileId);
2638 mGenerationRegistry.incrementGeneration(key);
2639
2640 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002641 }
2642 }
2643 }
Svetoslav683914b2015-01-15 14:22:26 -08002644 }
2645
Svetoslav683914b2015-01-15 14:22:26 -08002646 private boolean isGlobalSettingsKey(int key) {
2647 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2648 }
2649
2650 private boolean isSystemSettingsKey(int key) {
2651 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2652 }
2653
2654 private boolean isSecureSettingsKey(int key) {
2655 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2656 }
2657
Mark Rathjend891f012017-01-19 04:10:37 +00002658 private boolean isSsaidSettingsKey(int key) {
2659 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2660 }
2661
Svetoslav683914b2015-01-15 14:22:26 -08002662 private File getSettingsFile(int key) {
2663 if (isGlobalSettingsKey(key)) {
2664 final int userId = getUserIdFromKey(key);
2665 return new File(Environment.getUserSystemDirectory(userId),
2666 SETTINGS_FILE_GLOBAL);
2667 } else if (isSystemSettingsKey(key)) {
2668 final int userId = getUserIdFromKey(key);
2669 return new File(Environment.getUserSystemDirectory(userId),
2670 SETTINGS_FILE_SYSTEM);
2671 } else if (isSecureSettingsKey(key)) {
2672 final int userId = getUserIdFromKey(key);
2673 return new File(Environment.getUserSystemDirectory(userId),
2674 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002675 } else if (isSsaidSettingsKey(key)) {
2676 final int userId = getUserIdFromKey(key);
2677 return new File(Environment.getUserSystemDirectory(userId),
2678 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002679 } else {
2680 throw new IllegalArgumentException("Invalid settings key:" + key);
2681 }
2682 }
2683
2684 private Uri getNotificationUriFor(int key, String name) {
2685 if (isGlobalSettingsKey(key)) {
2686 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2687 : Settings.Global.CONTENT_URI;
2688 } else if (isSecureSettingsKey(key)) {
2689 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2690 : Settings.Secure.CONTENT_URI;
2691 } else if (isSystemSettingsKey(key)) {
2692 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2693 : Settings.System.CONTENT_URI;
2694 } else {
2695 throw new IllegalArgumentException("Invalid settings key:" + key);
2696 }
2697 }
2698
2699 private int getMaxBytesPerPackageForType(int type) {
2700 switch (type) {
2701 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002702 case SETTINGS_TYPE_SECURE:
2703 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002704 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2705 }
2706
2707 default: {
2708 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2709 }
2710 }
2711 }
2712
Svetoslav7e0683b2015-08-03 16:02:52 -07002713 private final class MyHandler extends Handler {
2714 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2715 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2716
2717 public MyHandler(Looper looper) {
2718 super(looper);
2719 }
2720
2721 @Override
2722 public void handleMessage(Message msg) {
2723 switch (msg.what) {
2724 case MSG_NOTIFY_URI_CHANGED: {
2725 final int userId = msg.arg1;
2726 Uri uri = (Uri) msg.obj;
2727 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2728 if (DEBUG) {
2729 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2730 }
2731 } break;
2732
2733 case MSG_NOTIFY_DATA_CHANGED: {
2734 mBackupManager.dataChanged();
2735 } break;
2736 }
2737 }
2738 }
2739
Svetoslav683914b2015-01-15 14:22:26 -08002740 private final class UpgradeController {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08002741 private static final int SETTINGS_VERSION = 139;
Svetoslav683914b2015-01-15 14:22:26 -08002742
2743 private final int mUserId;
2744
2745 public UpgradeController(int userId) {
2746 mUserId = userId;
2747 }
2748
2749 public void upgradeIfNeededLocked() {
2750 // The version of all settings for a user is the same (all users have secure).
2751 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002752 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002753
2754 // Try an update from the current state.
2755 final int oldVersion = secureSettings.getVersionLocked();
2756 final int newVersion = SETTINGS_VERSION;
2757
Svet Ganovc9755bc2015-03-28 13:21:22 -07002758 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002759 if (oldVersion == newVersion) {
2760 return;
2761 }
2762
2763 // Try to upgrade.
2764 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2765
2766 // If upgrade failed start from scratch and upgrade.
2767 if (curVersion != newVersion) {
2768 // Drop state we have for this user.
2769 removeUserStateLocked(mUserId, true);
2770
2771 // Recreate the database.
2772 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2773 SQLiteDatabase database = dbHelper.getWritableDatabase();
2774 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2775
2776 // Migrate the settings for this user.
2777 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2778
2779 // Now upgrade should work fine.
2780 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002781
2782 // Make a note what happened, so we don't wonder why data was lost
2783 String reason = "Settings rebuilt! Current version: "
2784 + curVersion + " while expected: " + newVersion;
2785 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002786 Settings.Global.DATABASE_DOWNGRADE_REASON,
2787 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002788 }
2789
2790 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002791 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002792 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002793 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002794 globalSettings.setVersionLocked(newVersion);
2795 }
2796
2797 // Set the secure settings version.
2798 secureSettings.setVersionLocked(newVersion);
2799
2800 // Set the system settings version.
2801 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002802 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002803 systemSettings.setVersionLocked(newVersion);
2804 }
2805
2806 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002807 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002808 }
2809
2810 private SettingsState getSecureSettingsLocked(int userId) {
2811 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2812 }
2813
Mark Rathjend891f012017-01-19 04:10:37 +00002814 private SettingsState getSsaidSettingsLocked(int userId) {
2815 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2816 }
2817
Svetoslav683914b2015-01-15 14:22:26 -08002818 private SettingsState getSystemSettingsLocked(int userId) {
2819 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2820 }
2821
Jeff Brown503cffc2015-03-26 18:08:51 -07002822 /**
2823 * You must perform all necessary mutations to bring the settings
2824 * for this user from the old to the new version. When you add a new
2825 * upgrade step you *must* update SETTINGS_VERSION.
2826 *
2827 * This is an example of moving a setting from secure to global.
2828 *
2829 * // v119: Example settings changes.
2830 * if (currentVersion == 118) {
2831 * if (userId == UserHandle.USER_OWNER) {
2832 * // Remove from the secure settings.
2833 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2834 * String name = "example_setting_to_move";
2835 * String value = secureSettings.getSetting(name);
2836 * secureSettings.deleteSetting(name);
2837 *
2838 * // Add to the global settings.
2839 * SettingsState globalSettings = getGlobalSettingsLocked();
2840 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2841 * }
2842 *
2843 * // Update the current version.
2844 * currentVersion = 119;
2845 * }
2846 */
Svetoslav683914b2015-01-15 14:22:26 -08002847 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2848 if (DEBUG) {
2849 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2850 + oldVersion + " to version: " + newVersion);
2851 }
2852
Jeff Brown503cffc2015-03-26 18:08:51 -07002853 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002854
John Spurlocke11ae112015-05-11 16:09:03 -04002855 // v119: Reset zen + ringer mode.
2856 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002857 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002858 final SettingsState globalSettings = getGlobalSettingsLocked();
2859 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002860 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
2861 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002862 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002863 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
2864 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04002865 }
2866 currentVersion = 119;
2867 }
2868
Jason Monk27bbb2d2015-03-31 16:46:39 -04002869 // v120: Add double tap to wake setting.
2870 if (currentVersion == 119) {
2871 SettingsState secureSettings = getSecureSettingsLocked(userId);
2872 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2873 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002874 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04002875 SettingsState.SYSTEM_PACKAGE_NAME);
2876
2877 currentVersion = 120;
2878 }
2879
Svetoslav7e0683b2015-08-03 16:02:52 -07002880 if (currentVersion == 120) {
2881 // Before 121, we used a different string encoding logic. We just bump the
2882 // version here; SettingsState knows how to handle pre-version 120 files.
2883 currentVersion = 121;
2884 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002885
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002886 if (currentVersion == 121) {
2887 // Version 122: allow OEMs to set a default payment component in resources.
2888 // Note that we only write the default if no default has been set;
2889 // if there is, we just leave the default at whatever it currently is.
2890 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2891 String defaultComponent = (getContext().getResources().getString(
2892 R.string.def_nfc_payment_component));
2893 Setting currentSetting = secureSettings.getSettingLocked(
2894 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2895 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002896 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002897 secureSettings.insertSettingLocked(
2898 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002899 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002900 }
2901 currentVersion = 122;
2902 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002903
2904 if (currentVersion == 122) {
2905 // Version 123: Adding a default value for the ability to add a user from
2906 // the lock screen.
2907 if (userId == UserHandle.USER_SYSTEM) {
2908 final SettingsState globalSettings = getGlobalSettingsLocked();
2909 Setting currentSetting = globalSettings.getSettingLocked(
2910 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002911 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002912 globalSettings.insertSettingLocked(
2913 Settings.Global.ADD_USERS_WHEN_LOCKED,
2914 getContext().getResources().getBoolean(
2915 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002916 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002917 }
2918 }
2919 currentVersion = 123;
2920 }
Bryce Leebd179282015-12-17 19:01:37 -08002921
2922 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002923 final SettingsState globalSettings = getGlobalSettingsLocked();
2924 String defaultDisabledProfiles = (getContext().getResources().getString(
2925 R.string.def_bluetooth_disabled_profiles));
2926 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002927 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002928 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002929 }
2930
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002931 if (currentVersion == 124) {
2932 // Version 124: allow OEMs to set a default value for whether IME should be
2933 // shown when a physical keyboard is connected.
2934 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2935 Setting currentSetting = secureSettings.getSettingLocked(
2936 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002937 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002938 secureSettings.insertSettingLocked(
2939 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2940 getContext().getResources().getBoolean(
2941 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08002942 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002943 }
2944 currentVersion = 125;
2945 }
2946
Ruben Brunk98576cf2016-03-07 18:54:28 -08002947 if (currentVersion == 125) {
2948 // Version 125: Allow OEMs to set the default VR service.
2949 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2950
2951 Setting currentSetting = secureSettings.getSettingLocked(
2952 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002953 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002954 ArraySet<ComponentName> l =
2955 SystemConfig.getInstance().getDefaultVrComponents();
2956
2957 if (l != null && !l.isEmpty()) {
2958 StringBuilder b = new StringBuilder();
2959 boolean start = true;
2960 for (ComponentName c : l) {
2961 if (!start) {
2962 b.append(':');
2963 }
2964 b.append(c.flattenToString());
2965 start = false;
2966 }
2967 secureSettings.insertSettingLocked(
2968 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08002969 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08002970 }
2971
2972 }
2973 currentVersion = 126;
2974 }
2975
Daniel U02ba6122016-04-01 18:41:42 +01002976 if (currentVersion == 126) {
2977 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2978 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2979 if (mUserManager.isManagedProfile(userId)) {
2980 final SettingsState systemSecureSettings =
2981 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2982
2983 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2984 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002985 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002986 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2987 secureSettings.insertSettingLocked(
2988 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002989 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01002990 SettingsState.SYSTEM_PACKAGE_NAME);
2991 }
2992
2993 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2994 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002995 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002996 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2997 secureSettings.insertSettingLocked(
2998 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002999 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003000 SettingsState.SYSTEM_PACKAGE_NAME);
3001 }
3002 }
3003 currentVersion = 127;
3004 }
3005
Steven Ngdc20ba62016-04-26 18:19:04 +01003006 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003007 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003008 currentVersion = 128;
3009 }
3010
Julia Reynolds1f721e12016-07-11 08:50:58 -04003011 if (currentVersion == 128) {
3012 // Version 128: Allow OEMs to grant DND access to default apps. Note that
3013 // the new apps are appended to the list of already approved apps.
3014 final SettingsState systemSecureSettings =
3015 getSecureSettingsLocked(userId);
3016
3017 final Setting policyAccess = systemSecureSettings.getSettingLocked(
3018 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
3019 String defaultPolicyAccess = getContext().getResources().getString(
3020 com.android.internal.R.string.config_defaultDndAccessPackages);
3021 if (!TextUtils.isEmpty(defaultPolicyAccess)) {
3022 if (policyAccess.isNull()) {
3023 systemSecureSettings.insertSettingLocked(
3024 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003025 defaultPolicyAccess, null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003026 SettingsState.SYSTEM_PACKAGE_NAME);
3027 } else {
3028 StringBuilder currentSetting =
3029 new StringBuilder(policyAccess.getValue());
3030 currentSetting.append(":");
3031 currentSetting.append(defaultPolicyAccess);
3032 systemSecureSettings.updateSettingLocked(
3033 Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003034 currentSetting.toString(), null, true,
Julia Reynolds1f721e12016-07-11 08:50:58 -04003035 SettingsState.SYSTEM_PACKAGE_NAME);
3036 }
3037 }
3038
3039 currentVersion = 129;
3040 }
3041
Dan Sandler71f85e92016-07-20 13:46:05 -04003042 if (currentVersion == 129) {
3043 // default longpress timeout changed from 500 to 400. If unchanged from the old
3044 // default, update to the new default.
3045 final SettingsState systemSecureSettings =
3046 getSecureSettingsLocked(userId);
3047 final String oldValue = systemSecureSettings.getSettingLocked(
3048 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3049 if (TextUtils.equals("500", oldValue)) {
3050 systemSecureSettings.insertSettingLocked(
3051 Settings.Secure.LONG_PRESS_TIMEOUT,
3052 String.valueOf(getContext().getResources().getInteger(
3053 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003054 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003055 }
3056 currentVersion = 130;
3057 }
3058
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003059 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003060 // Split Ambient settings
3061 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3062 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3063 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3064
3065 if (dozeExplicitlyDisabled) {
3066 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003067 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003068 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003069 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003070 }
3071 currentVersion = 131;
3072 }
3073
3074 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003075 // Initialize new multi-press timeout to default value
3076 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3077 final String oldValue = systemSecureSettings.getSettingLocked(
3078 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3079 if (TextUtils.equals(null, oldValue)) {
3080 systemSecureSettings.insertSettingLocked(
3081 Settings.Secure.MULTI_PRESS_TIMEOUT,
3082 String.valueOf(getContext().getResources().getInteger(
3083 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003084 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003085 }
3086
Adrian Roos69741a22016-10-21 14:49:17 -07003087 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003088 }
3089
Adrian Roos69741a22016-10-21 14:49:17 -07003090 if (currentVersion == 132) {
3091 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003092 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3093 String defaultSyncParentSounds = (getContext().getResources()
3094 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3095 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003096 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3097 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003098 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003099 }
3100
Adrian Roos69741a22016-10-21 14:49:17 -07003101 if (currentVersion == 133) {
3102 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003103 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3104 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3105 null) {
3106 String defaultEndButtonBehavior = Integer.toString(getContext()
3107 .getResources().getInteger(R.integer.def_end_button_behavior));
3108 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003109 defaultEndButtonBehavior, null, true,
3110 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003111 }
Adrian Roos69741a22016-10-21 14:49:17 -07003112 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003113 }
3114
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003115 if (currentVersion == 134) {
3116 // Remove setting that specifies if magnification values should be preserved.
3117 // This setting defaulted to true and never has a UI.
3118 getSecureSettingsLocked(userId).deleteSettingLocked(
3119 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3120 currentVersion = 135;
3121 }
3122
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003123 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003124 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003125 currentVersion = 136;
3126 }
3127
Mark Rathjend891f012017-01-19 04:10:37 +00003128 if (currentVersion == 136) {
3129 // Version 136: Store legacy SSAID for all apps currently installed on the
3130 // device as first step in migrating SSAID to be unique per application.
3131
3132 final boolean isUpgrade;
3133 try {
3134 isUpgrade = mPackageManager.isUpgrade();
3135 } catch (RemoteException e) {
3136 throw new IllegalStateException("Package manager not available");
3137 }
3138 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3139 // user data or first boot on a new device should use new ssaid generation.
3140 if (isUpgrade) {
3141 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003142 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3143 userId, Settings.Secure.ANDROID_ID);
3144 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3145 || legacySsaidSetting.getValue() == null) {
3146 throw new IllegalStateException("Legacy ssaid not accessible");
3147 }
3148 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003149
3150 // Fill each uid with the legacy ssaid to be backwards compatible.
3151 final List<PackageInfo> packages;
3152 try {
3153 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3154 } catch (RemoteException e) {
3155 throw new IllegalStateException("Package manager not available");
3156 }
3157
3158 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3159 for (PackageInfo info : packages) {
3160 // Check if the UID already has an entry in the table.
3161 final String uid = Integer.toString(info.applicationInfo.uid);
3162 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3163
3164 if (ssaid.isNull() || ssaid.getValue() == null) {
3165 // Android Id doesn't exist for this package so create it.
3166 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3167 info.packageName);
3168 }
3169 }
3170 }
3171
3172 currentVersion = 137;
3173 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003174 if (currentVersion == 137) {
3175 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3176 // default value set to 1. The user can no longer change the value of this
3177 // setting through the UI.
3178 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3179 if (!mUserManager.hasUserRestriction(
Victor Chang5663e052017-02-20 13:15:45 +00003180 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))) {
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003181 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3182 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3183 }
3184 currentVersion = 138;
3185 }
Mark Rathjend891f012017-01-19 04:10:37 +00003186
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003187 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003188 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003189 currentVersion = 139;
3190 }
3191
Dan Sandler71f85e92016-07-20 13:46:05 -04003192 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003193 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003194 + newVersion + " left it at "
3195 + currentVersion + " instead; this is probably a bug", new Throwable());
3196 if (DEBUG) {
3197 throw new RuntimeException("db upgrade error");
3198 }
3199 }
3200
Jeff Brown503cffc2015-03-26 18:08:51 -07003201 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08003202
Jeff Brown503cffc2015-03-26 18:08:51 -07003203 // Return the current version.
3204 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003205 }
3206 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003207 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003208}