blob: 881e8defc12b31ba1bf9246b9f7457bf3e66d2fe [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;
Christopher Tated5fe1472012-09-10 15:48:38 -070020import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070021import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080022import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070023import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080024import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070026import android.content.ContentValues;
27import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.Intent;
29import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080030import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070031import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070034import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040040import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Svet Ganov53a441c2016-04-19 19:38:00 -070045import android.os.Debug;
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;
Christopher Tate06efb532012-08-24 15:29:27 -070056import android.os.UserHandle;
57import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070058import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059import android.provider.Settings;
60import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080061import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070062import android.util.Slog;
63import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040064
Svetoslav683914b2015-01-15 14:22:26 -080065import com.android.internal.annotations.GuardedBy;
66import com.android.internal.content.PackageMonitor;
67import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080068import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070069import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080070import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040071
Svetoslav683914b2015-01-15 14:22:26 -080072import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080073import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080074import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080075import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080076import java.security.SecureRandom;
77import java.util.Arrays;
78import java.util.List;
Svetoslav683914b2015-01-15 14:22:26 -080079import java.util.Set;
80import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070081
Svetoslav683914b2015-01-15 14:22:26 -080082/**
83 * <p>
84 * This class is a content provider that publishes the system settings.
85 * It can be accessed via the content provider APIs or via custom call
86 * commands. The latter is a bit faster and is the preferred way to access
87 * the platform settings.
88 * </p>
89 * <p>
90 * There are three settings types, global (with signature level protection
91 * and shared across users), secure (with signature permission level
92 * protection and per user), and system (with dangerous permission level
93 * protection and per user). Global settings are stored under the device owner.
94 * Each of these settings is represented by a {@link
95 * com.android.providers.settings.SettingsState} object mapped to an integer
96 * key derived from the setting type in the most significant bits and user
97 * id in the least significant bits. Settings are synchronously loaded on
98 * instantiation of a SettingsState and asynchronously persisted on mutation.
99 * Settings are stored in the user specific system directory.
100 * </p>
101 * <p>
102 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
103 * and get a warning. Targeting higher API version prohibits this as the
104 * system settings are not a place for apps to save their state. When a package
105 * is removed the settings it added are deleted. Apps cannot delete system
106 * settings added by the platform. System settings values are validated to
107 * ensure the clients do not put bad values. Global and secure settings are
108 * changed only by trusted parties, therefore no validation is performed. Also
109 * there is a limit on the amount of app specific settings that can be added
110 * to prevent unlimited growth of the system process memory footprint.
111 * </p>
112 */
113@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800115 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700116
Svetoslav683914b2015-01-15 14:22:26 -0800117 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
118
119 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700120
Christopher Tate06efb532012-08-24 15:29:27 -0700121 private static final String TABLE_SYSTEM = "system";
122 private static final String TABLE_SECURE = "secure";
123 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800124
125 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final String TABLE_FAVORITES = "favorites";
127 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800128 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
129 private static final String TABLE_BOOKMARKS = "bookmarks";
130 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Svetoslav683914b2015-01-15 14:22:26 -0800132 // The set of removed legacy tables.
133 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700134 static {
Svetoslav683914b2015-01-15 14:22:26 -0800135 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
136 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
137 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
138 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
139 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
140 }
Christopher Tate06efb532012-08-24 15:29:27 -0700141
Svetoslav683914b2015-01-15 14:22:26 -0800142 private static final int MUTATION_OPERATION_INSERT = 1;
143 private static final int MUTATION_OPERATION_DELETE = 2;
144 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400145
Svetoslav683914b2015-01-15 14:22:26 -0800146 private static final String[] ALL_COLUMNS = new String[] {
147 Settings.NameValueTable._ID,
148 Settings.NameValueTable.NAME,
149 Settings.NameValueTable.VALUE
150 };
151
Svet Ganov53a441c2016-04-19 19:38:00 -0700152 public static final int SETTINGS_TYPE_GLOBAL = 0;
153 public static final int SETTINGS_TYPE_SYSTEM = 1;
154 public static final int SETTINGS_TYPE_SECURE = 2;
Svetoslav683914b2015-01-15 14:22:26 -0800155
Svet Ganov53a441c2016-04-19 19:38:00 -0700156 public static final int SETTINGS_TYPE_MASK = 0xF0000000;
157 public static final int SETTINGS_TYPE_SHIFT = 28;
158
159 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
160 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700161
Svetoslav683914b2015-01-15 14:22:26 -0800162 // Per user secure settings that moved to the for all users global settings.
163 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
164 static {
165 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700166 }
167
Svetoslav683914b2015-01-15 14:22:26 -0800168 // Per user system settings that moved to the for all users global settings.
169 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
170 static {
171 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172 }
173
Svetoslav683914b2015-01-15 14:22:26 -0800174 // Per user system settings that moved to the per user secure settings.
175 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
176 static {
177 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 }
179
Svetoslav683914b2015-01-15 14:22:26 -0800180 // Per all users global settings that moved to the per user secure settings.
181 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
182 static {
183 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700184 }
185
Svetoslav683914b2015-01-15 14:22:26 -0800186 // Per user secure settings that are cloned for the managed profiles of the user.
187 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
188 static {
189 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700190 }
191
Svetoslav683914b2015-01-15 14:22:26 -0800192 // Per user system settings that are cloned for the managed profiles of the user.
193 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
194 static {
195 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400196 }
197
Svetoslav683914b2015-01-15 14:22:26 -0800198 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700199
Svetoslav683914b2015-01-15 14:22:26 -0800200 @GuardedBy("mLock")
201 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700202
Svet Ganova8f90262016-05-10 08:44:48 -0700203 @GuardedBy("mLock")
204 private HandlerThread mHandlerThread;
205
206 @GuardedBy("mLock")
207 private Handler mBackgroundHandler;
208
Svetoslav7ec28e82015-05-20 17:01:10 -0700209 // We have to call in the user manager with no lock held,
210 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800211
Svetoslav7ec28e82015-05-20 17:01:10 -0700212 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700213 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700214
Svet Ganov53a441c2016-04-19 19:38:00 -0700215 public static int makeKey(int type, int userId) {
216 return (type << SETTINGS_TYPE_SHIFT) | userId;
217 }
218
219 public static int getTypeFromKey(int key) {
220 return key >>> SETTINGS_TYPE_SHIFT;
221 }
222
223 public static int getUserIdFromKey(int key) {
224 return key & ~SETTINGS_TYPE_MASK;
225 }
226
227 public static String settingTypeToString(int type) {
228 switch (type) {
229 case SETTINGS_TYPE_GLOBAL: {
230 return "SETTINGS_GLOBAL";
231 }
232 case SETTINGS_TYPE_SECURE: {
233 return "SETTINGS_SECURE";
234 }
235 case SETTINGS_TYPE_SYSTEM: {
236 return "SETTINGS_SYSTEM";
237 }
238 default: {
239 return "UNKNOWN";
240 }
241 }
242 }
243
244 public static String keyToString(int key) {
245 return "Key[user=" + getUserIdFromKey(key) + ";type="
246 + settingTypeToString(getTypeFromKey(key)) + "]";
247 }
248
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249 @Override
250 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800251 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700252 mUserManager = UserManager.get(getContext());
253 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700254 mHandlerThread = new HandlerThread(LOG_TAG,
255 Process.THREAD_PRIORITY_BACKGROUND);
256 mHandlerThread.start();
257 mBackgroundHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800258 mSettingsRegistry = new SettingsRegistry();
259 }
260 registerBroadcastReceivers();
Svet Ganov53a441c2016-04-19 19:38:00 -0700261 startWatchingUserRestrictionChanges();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262 return true;
263 }
264
Svetoslav683914b2015-01-15 14:22:26 -0800265 @Override
266 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700267 final int requestingUserId = getRequestingUserId(args);
268 switch (method) {
269 case Settings.CALL_METHOD_GET_GLOBAL: {
270 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700271 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800272 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700273
274 case Settings.CALL_METHOD_GET_SECURE: {
275 Setting setting = getSecureSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700276 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700277 }
278
279 case Settings.CALL_METHOD_GET_SYSTEM: {
280 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700281 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700282 }
283
284 case Settings.CALL_METHOD_PUT_GLOBAL: {
285 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700286 insertGlobalSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700287 break;
288 }
289
290 case Settings.CALL_METHOD_PUT_SECURE: {
291 String value = getSettingValue(args);
Svet Ganov53a441c2016-04-19 19:38:00 -0700292 insertSecureSetting(name, value, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700293 break;
294 }
295
296 case Settings.CALL_METHOD_PUT_SYSTEM: {
297 String value = getSettingValue(args);
298 insertSystemSetting(name, value, requestingUserId);
299 break;
300 }
301
302 default: {
303 Slog.w(LOG_TAG, "call() with invalid method: " + method);
304 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700305 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700306
Christopher Tate06efb532012-08-24 15:29:27 -0700307 return null;
308 }
309
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800310 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800311 public String getType(Uri uri) {
312 Arguments args = new Arguments(uri, null, null, true);
313 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 return "vnd.android.cursor.dir/" + args.table;
315 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700316 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700317 }
318 }
319
320 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800321 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
322 String order) {
323 if (DEBUG) {
324 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325 }
326
Svetoslav683914b2015-01-15 14:22:26 -0800327 Arguments args = new Arguments(uri, where, whereArgs, true);
328 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700329
Svetoslav683914b2015-01-15 14:22:26 -0800330 // If a legacy table that is gone, done.
331 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
332 return new MatrixCursor(normalizedProjection, 0);
333 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700334
Svetoslav7ec28e82015-05-20 17:01:10 -0700335 switch (args.table) {
336 case TABLE_GLOBAL: {
337 if (args.name != null) {
338 Setting setting = getGlobalSetting(args.name);
339 return packageSettingForQuery(setting, normalizedProjection);
340 } else {
341 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700342 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700343 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700344
Svetoslav7ec28e82015-05-20 17:01:10 -0700345 case TABLE_SECURE: {
346 final int userId = UserHandle.getCallingUserId();
347 if (args.name != null) {
348 Setting setting = getSecureSetting(args.name, userId);
349 return packageSettingForQuery(setting, normalizedProjection);
350 } else {
351 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800352 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700353 }
Svetoslav683914b2015-01-15 14:22:26 -0800354
Svetoslav7ec28e82015-05-20 17:01:10 -0700355 case TABLE_SYSTEM: {
356 final int userId = UserHandle.getCallingUserId();
357 if (args.name != null) {
358 Setting setting = getSystemSetting(args.name, userId);
359 return packageSettingForQuery(setting, normalizedProjection);
360 } else {
361 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800362 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700363 }
Svetoslav683914b2015-01-15 14:22:26 -0800364
Svetoslav7ec28e82015-05-20 17:01:10 -0700365 default: {
366 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700367 }
368 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700369 }
370
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800372 public Uri insert(Uri uri, ContentValues values) {
373 if (DEBUG) {
374 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700375 }
376
Svetoslav683914b2015-01-15 14:22:26 -0800377 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700378
Svetoslav683914b2015-01-15 14:22:26 -0800379 // If a legacy table that is gone, done.
380 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 return null;
382 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700383
Svetoslav683914b2015-01-15 14:22:26 -0800384 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700385 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800386 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700387 }
388
Svetoslav683914b2015-01-15 14:22:26 -0800389 String value = values.getAsString(Settings.Secure.VALUE);
390
Svetoslav7ec28e82015-05-20 17:01:10 -0700391 switch (table) {
392 case TABLE_GLOBAL: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700393 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700394 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700395 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700396 } break;
397
398 case TABLE_SECURE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700399 if (insertSecureSetting(name, value, UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700400 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
401 }
402 } break;
403
404 case TABLE_SYSTEM: {
405 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
406 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
407 }
408 } break;
409
410 default: {
411 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700412 }
413 }
414
Svetoslav683914b2015-01-15 14:22:26 -0800415 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700416 }
417
418 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800419 public int bulkInsert(Uri uri, ContentValues[] allValues) {
420 if (DEBUG) {
421 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700423
Svetoslav683914b2015-01-15 14:22:26 -0800424 int insertionCount = 0;
425 final int valuesCount = allValues.length;
426 for (int i = 0; i < valuesCount; i++) {
427 ContentValues values = allValues[i];
428 if (insert(uri, values) != null) {
429 insertionCount++;
430 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700431 }
Svetoslav683914b2015-01-15 14:22:26 -0800432
433 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700434 }
435
436 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800437 public int delete(Uri uri, String where, String[] whereArgs) {
438 if (DEBUG) {
439 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700441
Svetoslav683914b2015-01-15 14:22:26 -0800442 Arguments args = new Arguments(uri, where, whereArgs, false);
443
444 // If a legacy table that is gone, done.
445 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
446 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700447 }
Svetoslav683914b2015-01-15 14:22:26 -0800448
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700449 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800450 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700451 }
Svetoslav683914b2015-01-15 14:22:26 -0800452
Svetoslav7ec28e82015-05-20 17:01:10 -0700453 switch (args.table) {
454 case TABLE_GLOBAL: {
455 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700456 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700457 }
Svetoslav683914b2015-01-15 14:22:26 -0800458
Svetoslav7ec28e82015-05-20 17:01:10 -0700459 case TABLE_SECURE: {
460 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700461 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700462 }
Svetoslav683914b2015-01-15 14:22:26 -0800463
Svetoslav7ec28e82015-05-20 17:01:10 -0700464 case TABLE_SYSTEM: {
465 final int userId = UserHandle.getCallingUserId();
466 return deleteSystemSetting(args.name, userId) ? 1 : 0;
467 }
468
469 default: {
470 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800471 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700472 }
Svetoslav683914b2015-01-15 14:22:26 -0800473 }
474
475 @Override
476 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
477 if (DEBUG) {
478 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700479 }
Svetoslav683914b2015-01-15 14:22:26 -0800480
481 Arguments args = new Arguments(uri, where, whereArgs, false);
482
483 // If a legacy table that is gone, done.
484 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
485 return 0;
486 }
487
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700488 String name = values.getAsString(Settings.Secure.NAME);
489 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800490 return 0;
491 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700492 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800493
Svetoslav7ec28e82015-05-20 17:01:10 -0700494 switch (args.table) {
495 case TABLE_GLOBAL: {
496 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700497 return updateGlobalSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700498 }
Svetoslav683914b2015-01-15 14:22:26 -0800499
Svetoslav7ec28e82015-05-20 17:01:10 -0700500 case TABLE_SECURE: {
501 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700502 return updateSecureSetting(args.name, value, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700503 }
Svetoslav683914b2015-01-15 14:22:26 -0800504
Svetoslav7ec28e82015-05-20 17:01:10 -0700505 case TABLE_SYSTEM: {
506 final int userId = UserHandle.getCallingUserId();
507 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
508 }
Svetoslav683914b2015-01-15 14:22:26 -0800509
Svetoslav7ec28e82015-05-20 17:01:10 -0700510 default: {
511 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800512 }
513 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514 }
515
516 @Override
517 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey413573a2016-02-22 17:52:45 -0700518 final String cacheName;
519 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
520 cacheName = Settings.System.RINGTONE_CACHE;
521 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
522 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
523 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
524 cacheName = Settings.System.ALARM_ALERT_CACHE;
525 } else {
526 throw new FileNotFoundException("Direct file access no longer supported; "
527 + "ringtone playback is available through android.media.Ringtone");
528 }
529
530 final File cacheFile = new File(
531 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
532 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
533 }
534
535 private File getRingtoneCacheDir(int userId) {
536 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
537 cacheDir.mkdir();
538 SELinux.restorecon(cacheDir);
539 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700540 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800541
Svetoslavb505ccc2015-02-17 12:41:04 -0800542 @Override
543 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
544 synchronized (mLock) {
545 final long identity = Binder.clearCallingIdentity();
546 try {
547 List<UserInfo> users = mUserManager.getUsers(true);
548 final int userCount = users.size();
549 for (int i = 0; i < userCount; i++) {
550 UserInfo user = users.get(i);
551 dumpForUser(user.id, pw);
552 }
553 } finally {
554 Binder.restoreCallingIdentity(identity);
555 }
556 }
557 }
558
559 private void dumpForUser(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700560 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800561 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700562 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800563 dumpSettings(globalCursor, pw);
564 pw.println();
565 }
566
567 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700568 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800569 dumpSettings(secureCursor, pw);
570 pw.println();
571
572 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700573 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800574 dumpSettings(systemCursor, pw);
575 pw.println();
576 }
577
578 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700579 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800580 return;
581 }
582
583 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
584 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
585 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
586
587 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700588 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
589 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
590 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800591 pw.println();
592 } while (cursor.moveToNext());
593 }
594
Svetoslav7e0683b2015-08-03 16:02:52 -0700595 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700596 if (s != null) {
597 return s;
598 }
599 return "{null}";
600 }
601
Svetoslav683914b2015-01-15 14:22:26 -0800602 private void registerBroadcastReceivers() {
603 IntentFilter userFilter = new IntentFilter();
604 userFilter.addAction(Intent.ACTION_USER_REMOVED);
605 userFilter.addAction(Intent.ACTION_USER_STOPPED);
606
607 getContext().registerReceiver(new BroadcastReceiver() {
608 @Override
609 public void onReceive(Context context, Intent intent) {
610 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700611 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800612
613 switch (intent.getAction()) {
614 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700615 synchronized (mLock) {
616 mSettingsRegistry.removeUserStateLocked(userId, true);
617 }
Svetoslav683914b2015-01-15 14:22:26 -0800618 } break;
619
620 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700621 synchronized (mLock) {
622 mSettingsRegistry.removeUserStateLocked(userId, false);
623 }
Svetoslav683914b2015-01-15 14:22:26 -0800624 } break;
625 }
626 }
627 }, userFilter);
628
629 PackageMonitor monitor = new PackageMonitor() {
630 @Override
631 public void onPackageRemoved(String packageName, int uid) {
632 synchronized (mLock) {
633 mSettingsRegistry.onPackageRemovedLocked(packageName,
634 UserHandle.getUserId(uid));
635 }
636 }
637 };
638
639 // package changes
640 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
641 UserHandle.ALL, true);
642 }
643
Svet Ganov53a441c2016-04-19 19:38:00 -0700644 private void startWatchingUserRestrictionChanges() {
645 // TODO: The current design of settings looking different based on user restrictions
646 // should be reworked to keep them separate and system code should check the setting
647 // first followed by checking the user restriction before performing an operation.
648 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
649 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
650 Bundle prevRestrictions) -> {
651 // We are changing the settings affected by restrictions to their current
652 // value with a forced update to ensure that all cross profile dependencies
653 // are taken into account. Also make sure the settings update to.. the same
654 // value passes the security checks, so clear binder calling id.
655 if (newRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)
656 != prevRestrictions.containsKey(UserManager.DISALLOW_SHARE_LOCATION)) {
657 final long identity = Binder.clearCallingIdentity();
658 try {
659 synchronized (mLock) {
660 Setting setting = getSecureSetting(
661 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
662 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
663 setting != null ? setting.getValue() : null, userId, true);
664 }
665 } finally {
666 Binder.restoreCallingIdentity(identity);
667 }
668 }
669 if (newRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
670 != prevRestrictions.containsKey(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
671 final long identity = Binder.clearCallingIdentity();
672 try {
673 synchronized (mLock) {
674 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
675 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
676 setting != null ? setting.getValue() : null, userId, true);
677 }
678 } finally {
679 Binder.restoreCallingIdentity(identity);
680 }
681 }
682 if (newRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)
683 != prevRestrictions.containsKey(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
684 final long identity = Binder.clearCallingIdentity();
685 try {
686 synchronized (mLock) {
687 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
688 updateGlobalSetting(Settings.Global.ADB_ENABLED,
689 setting != null ? setting.getValue() : null, userId, true);
690 }
691 } finally {
692 Binder.restoreCallingIdentity(identity);
693 }
694 }
695 if (newRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)
696 != prevRestrictions.containsKey(UserManager.ENSURE_VERIFY_APPS)) {
697 final long identity = Binder.clearCallingIdentity();
698 try {
699 synchronized (mLock) {
700 Setting enable = getGlobalSetting(
701 Settings.Global.PACKAGE_VERIFIER_ENABLE);
702 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
703 enable != null ? enable.getValue() : null, userId, true);
704 Setting include = getGlobalSetting(
705 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
706 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
707 include != null ? include.getValue() : null, userId, true);
708 }
709 } finally {
710 Binder.restoreCallingIdentity(identity);
711 }
712 }
713 if (newRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
714 != prevRestrictions.containsKey(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
715 final long identity = Binder.clearCallingIdentity();
716 try {
717 synchronized (mLock) {
718 Setting setting = getGlobalSetting(
719 Settings.Global.PREFERRED_NETWORK_MODE);
720 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
721 setting != null ? setting.getValue() : null, userId, true);
722 }
723 } finally {
724 Binder.restoreCallingIdentity(identity);
725 }
726 }
727 });
728 }
729
Svetoslav7ec28e82015-05-20 17:01:10 -0700730 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800731 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700732 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800733 }
734
Svetoslav7ec28e82015-05-20 17:01:10 -0700735 synchronized (mLock) {
736 // Get the settings.
737 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700738 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800739
Svetoslav7ec28e82015-05-20 17:01:10 -0700740 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800741
Svetoslav7ec28e82015-05-20 17:01:10 -0700742 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800743
Svetoslav7ec28e82015-05-20 17:01:10 -0700744 String[] normalizedProjection = normalizeProjection(projection);
745 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800746
Svetoslav7ec28e82015-05-20 17:01:10 -0700747 // Anyone can get the global settings, so no security checks.
748 for (int i = 0; i < nameCount; i++) {
749 String name = names.get(i);
750 Setting setting = settingsState.getSettingLocked(name);
751 appendSettingToCursor(result, setting);
752 }
753
754 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800755 }
Svetoslav683914b2015-01-15 14:22:26 -0800756 }
757
Svetoslav7ec28e82015-05-20 17:01:10 -0700758 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800759 if (DEBUG) {
760 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
761 }
762
763 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700764 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700765 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700766 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800767 }
Svetoslav683914b2015-01-15 14:22:26 -0800768 }
769
Svet Ganov53a441c2016-04-19 19:38:00 -0700770 private boolean updateGlobalSetting(String name, String value, int requestingUserId,
771 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800772 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700773 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800774 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700775 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
776 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800777 }
778
Svet Ganov53a441c2016-04-19 19:38:00 -0700779 private boolean insertGlobalSetting(String name, String value, int requestingUserId,
780 boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700781 if (DEBUG) {
782 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
783 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700784 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
785 forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700786 }
787
Svet Ganov53a441c2016-04-19 19:38:00 -0700788 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800789 if (DEBUG) {
790 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
791 }
Svet Ganov53a441c2016-04-19 19:38:00 -0700792 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
793 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800794 }
795
Svetoslav7ec28e82015-05-20 17:01:10 -0700796 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700797 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800798 // Make sure the caller can change the settings - treated as secure.
799 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
800
Svetoslav683914b2015-01-15 14:22:26 -0800801 // Resolve the userId on whose behalf the call is made.
802 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
803
Makoto Onuki28da2e32015-11-20 11:30:44 -0800804 // If this is a setting that is currently restricted for this user, do not allow
805 // unrestricting changes.
806 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800807 return false;
808 }
809
810 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700811 synchronized (mLock) {
812 switch (operation) {
813 case MUTATION_OPERATION_INSERT: {
814 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700815 .insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
816 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700817 }
Svetoslav683914b2015-01-15 14:22:26 -0800818
Svetoslav7ec28e82015-05-20 17:01:10 -0700819 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700820 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
821 UserHandle.USER_SYSTEM, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700822 }
Svetoslav683914b2015-01-15 14:22:26 -0800823
Svetoslav7ec28e82015-05-20 17:01:10 -0700824 case MUTATION_OPERATION_UPDATE: {
825 return mSettingsRegistry
Svet Ganov53a441c2016-04-19 19:38:00 -0700826 .updateSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM,
827 name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700828 }
Svetoslav683914b2015-01-15 14:22:26 -0800829 }
830 }
831
832 return false;
833 }
834
Svetoslav7ec28e82015-05-20 17:01:10 -0700835 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800836 if (DEBUG) {
837 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
838 }
839
840 // Resolve the userId on whose behalf the call is made.
841 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
842
Svetoslav7ec28e82015-05-20 17:01:10 -0700843 synchronized (mLock) {
844 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700845 SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800846
Svetoslav7ec28e82015-05-20 17:01:10 -0700847 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800848
Svetoslav7ec28e82015-05-20 17:01:10 -0700849 String[] normalizedProjection = normalizeProjection(projection);
850 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800851
Svetoslav7ec28e82015-05-20 17:01:10 -0700852 for (int i = 0; i < nameCount; i++) {
853 String name = names.get(i);
854 // Determine the owning user as some profile settings are cloned from the parent.
855 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
856 name);
Svetoslav683914b2015-01-15 14:22:26 -0800857
Svetoslav7ec28e82015-05-20 17:01:10 -0700858 // Special case for location (sigh).
859 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700860 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -0700861 }
Svetoslav683914b2015-01-15 14:22:26 -0800862
Svetoslav7ec28e82015-05-20 17:01:10 -0700863 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700864 SETTINGS_TYPE_SECURE, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700865 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800866 }
867
Svetoslav7ec28e82015-05-20 17:01:10 -0700868 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800869 }
Svetoslav683914b2015-01-15 14:22:26 -0800870 }
871
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800873 if (DEBUG) {
874 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
875 }
876
877 // Resolve the userId on whose behalf the call is made.
878 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
879
880 // Determine the owning user as some profile settings are cloned from the parent.
881 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
882
883 // Special case for location (sigh).
884 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -0700885 return mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
886 owningUserId).getNullSetting();
Svetoslav683914b2015-01-15 14:22:26 -0800887 }
888
889 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700890 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700891 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -0700892 owningUserId, name);
893 }
Svetoslav683914b2015-01-15 14:22:26 -0800894 }
895
Svet Ganov53a441c2016-04-19 19:38:00 -0700896 private boolean insertSecureSetting(String name, String value, int requestingUserId,
897 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800898 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700899 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800900 + requestingUserId + ")");
901 }
902
Svet Ganov53a441c2016-04-19 19:38:00 -0700903 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT,
904 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800905 }
906
Svet Ganov53a441c2016-04-19 19:38:00 -0700907 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800908 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700909 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800910 }
911
Svet Ganov53a441c2016-04-19 19:38:00 -0700912 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE,
913 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800914 }
915
Svet Ganov53a441c2016-04-19 19:38:00 -0700916 private boolean updateSecureSetting(String name, String value, int requestingUserId,
917 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800918 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700919 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800920 + requestingUserId + ")");
921 }
922
Svet Ganov53a441c2016-04-19 19:38:00 -0700923 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE,
924 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800925 }
926
Svetoslav7ec28e82015-05-20 17:01:10 -0700927 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svet Ganov53a441c2016-04-19 19:38:00 -0700928 int operation, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800929 // Make sure the caller can change the settings.
930 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
931
Svetoslav683914b2015-01-15 14:22:26 -0800932 // Resolve the userId on whose behalf the call is made.
933 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
934
Makoto Onuki28da2e32015-11-20 11:30:44 -0800935 // If this is a setting that is currently restricted for this user, do not allow
936 // unrestricting changes.
937 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value)) {
Svetoslav683914b2015-01-15 14:22:26 -0800938 return false;
939 }
940
941 // Determine the owning user as some profile settings are cloned from the parent.
942 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
943
944 // Only the owning user can change the setting.
945 if (owningUserId != callingUserId) {
946 return false;
947 }
948
949 // Special cases for location providers (sigh).
950 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700951 return updateLocationProvidersAllowedLocked(value, owningUserId, forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -0800952 }
953
954 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700955 synchronized (mLock) {
956 switch (operation) {
957 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700958 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
959 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700960 }
Svetoslav683914b2015-01-15 14:22:26 -0800961
Svetoslav7ec28e82015-05-20 17:01:10 -0700962 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700963 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
964 owningUserId, name, forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700965 }
Svetoslav683914b2015-01-15 14:22:26 -0800966
Svetoslav7ec28e82015-05-20 17:01:10 -0700967 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700968 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
969 owningUserId, name, value, getCallingPackage(), forceNotify);
Svetoslav7ec28e82015-05-20 17:01:10 -0700970 }
Svetoslav683914b2015-01-15 14:22:26 -0800971 }
972 }
973
974 return false;
975 }
976
Svetoslav7ec28e82015-05-20 17:01:10 -0700977 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800978 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700979 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800980 }
981
982 // Resolve the userId on whose behalf the call is made.
983 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
984
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 synchronized (mLock) {
986 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700987 SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800988
Svetoslav7ec28e82015-05-20 17:01:10 -0700989 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800990
Svetoslav7ec28e82015-05-20 17:01:10 -0700991 String[] normalizedProjection = normalizeProjection(projection);
992 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800993
Svetoslav7ec28e82015-05-20 17:01:10 -0700994 for (int i = 0; i < nameCount; i++) {
995 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800996
Svetoslav7ec28e82015-05-20 17:01:10 -0700997 // Determine the owning user as some profile settings are cloned from the parent.
998 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
999 name);
Svetoslav683914b2015-01-15 14:22:26 -08001000
Svetoslav7ec28e82015-05-20 17:01:10 -07001001 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001002 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001003 appendSettingToCursor(result, setting);
1004 }
1005
1006 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001007 }
Svetoslav683914b2015-01-15 14:22:26 -08001008 }
1009
Svetoslav7ec28e82015-05-20 17:01:10 -07001010 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001011 if (DEBUG) {
1012 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1013 }
1014
1015 // Resolve the userId on whose behalf the call is made.
1016 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1017
1018 // Determine the owning user as some profile settings are cloned from the parent.
1019 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1020
1021 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001022 synchronized (mLock) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001023 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 }
Svetoslav683914b2015-01-15 14:22:26 -08001025 }
1026
Svetoslav7ec28e82015-05-20 17:01:10 -07001027 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001028 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001029 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001030 + requestingUserId + ")");
1031 }
1032
Svetoslav7ec28e82015-05-20 17:01:10 -07001033 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001034 }
1035
Svetoslav7ec28e82015-05-20 17:01:10 -07001036 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001037 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001038 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001039 }
1040
Svetoslav7ec28e82015-05-20 17:01:10 -07001041 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001042 }
1043
Svetoslav7ec28e82015-05-20 17:01:10 -07001044 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001045 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001046 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001047 + requestingUserId + ")");
1048 }
1049
Svetoslav7ec28e82015-05-20 17:01:10 -07001050 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001051 }
1052
Svetoslav7ec28e82015-05-20 17:01:10 -07001053 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001054 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001055 if (!hasWriteSecureSettingsPermission()) {
1056 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1057 // operation is allowed for the calling package through appops.
1058 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1059 Binder.getCallingUid(), getCallingPackage(), true)) {
1060 return false;
1061 }
Svetoslav683914b2015-01-15 14:22:26 -08001062 }
1063
Svetoslav683914b2015-01-15 14:22:26 -08001064 // Resolve the userId on whose behalf the call is made.
1065 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1066
Svetoslavd8d25e02015-11-20 13:09:26 -08001067 // Enforce what the calling package can mutate the system settings.
1068 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1069
Svetoslav683914b2015-01-15 14:22:26 -08001070 // Determine the owning user as some profile settings are cloned from the parent.
1071 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1072
1073 // Only the owning user id can change the setting.
1074 if (owningUserId != callingUserId) {
1075 return false;
1076 }
1077
Jeff Sharkey413573a2016-02-22 17:52:45 -07001078 // Invalidate any relevant cache files
1079 String cacheName = null;
1080 if (Settings.System.RINGTONE.equals(name)) {
1081 cacheName = Settings.System.RINGTONE_CACHE;
1082 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1083 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1084 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1085 cacheName = Settings.System.ALARM_ALERT_CACHE;
1086 }
1087 if (cacheName != null) {
1088 final File cacheFile = new File(
1089 getRingtoneCacheDir(UserHandle.getCallingUserId()), cacheName);
1090 cacheFile.delete();
1091 }
1092
Svetoslav683914b2015-01-15 14:22:26 -08001093 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001094 synchronized (mLock) {
1095 switch (operation) {
1096 case MUTATION_OPERATION_INSERT: {
1097 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001098 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
1099 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001100 }
1101
1102 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001103 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
1104 owningUserId, name, false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001105 }
1106
1107 case MUTATION_OPERATION_UPDATE: {
1108 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001109 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
1110 owningUserId, name, value, getCallingPackage(), false);
Svetoslav7ec28e82015-05-20 17:01:10 -07001111 }
Svetoslav683914b2015-01-15 14:22:26 -08001112 }
1113
Svetoslav7ec28e82015-05-20 17:01:10 -07001114 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001115 }
Svetoslav683914b2015-01-15 14:22:26 -08001116 }
1117
Billy Lau6ad2d662015-07-18 00:26:58 +01001118 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001119 // Write secure settings is a more protected permission. If caller has it we are good.
1120 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1121 == PackageManager.PERMISSION_GRANTED) {
1122 return true;
1123 }
1124
Svetoslavf41334b2015-06-23 12:06:03 -07001125 return false;
1126 }
1127
Svetoslav683914b2015-01-15 14:22:26 -08001128 private void validateSystemSettingValue(String name, String value) {
1129 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1130 if (validator != null && !validator.validate(value)) {
1131 throw new IllegalArgumentException("Invalid value: " + value
1132 + " for setting: " + name);
1133 }
1134 }
1135
1136 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1137 int owningUserId) {
1138 // Optimization - location providers are restricted only for managed profiles.
1139 if (callingUserId == owningUserId) {
1140 return false;
1141 }
1142 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1143 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1144 new UserHandle(callingUserId))) {
1145 return true;
1146 }
1147 return false;
1148 }
1149
Makoto Onuki28da2e32015-11-20 11:30:44 -08001150 /**
1151 * Checks whether changing a setting to a value is prohibited by the corresponding user
1152 * restriction.
1153 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001154 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1155 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001156 *
1157 * @return true if the change is prohibited, false if the change is allowed.
1158 */
1159 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
1160 String value) {
1161 String restriction;
1162 switch (setting) {
1163 case Settings.Secure.LOCATION_MODE:
1164 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1165 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1166 // here normally, but we still protect it here from a direct provider write.
1167 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1168 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1169 break;
1170
1171 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1172 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1173 // a provider, which should be allowed even if the user restriction is set.
1174 if (value != null && value.startsWith("-")) return false;
1175 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1176 break;
1177
1178 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1179 if ("0".equals(value)) return false;
1180 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1181 break;
1182
1183 case Settings.Global.ADB_ENABLED:
1184 if ("0".equals(value)) return false;
1185 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1186 break;
1187
1188 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1189 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1190 if ("1".equals(value)) return false;
1191 restriction = UserManager.ENSURE_VERIFY_APPS;
1192 break;
1193
1194 case Settings.Global.PREFERRED_NETWORK_MODE:
1195 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1196 break;
1197
1198 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001199 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001200 if ("0".equals(value)) return false;
1201 restriction = UserManager.DISALLOW_DATA_ROAMING;
1202 break;
1203 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001204 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001205 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001206
1207 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001208 }
1209
1210 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1211 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1212 }
1213
1214 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
1215 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1216 }
1217
1218 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1219 final int parentId = getGroupParentLocked(userId);
1220 if (parentId != userId && keys.contains(name)) {
1221 return parentId;
1222 }
1223 return userId;
1224 }
1225
Svetoslavf41334b2015-06-23 12:06:03 -07001226 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001227 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001228 // System/root/shell can mutate whatever secure settings they want.
1229 final int callingUid = Binder.getCallingUid();
1230 if (callingUid == android.os.Process.SYSTEM_UID
1231 || callingUid == Process.SHELL_UID
1232 || callingUid == Process.ROOT_UID) {
1233 return;
1234 }
1235
1236 switch (operation) {
1237 case MUTATION_OPERATION_INSERT:
1238 // Insert updates.
1239 case MUTATION_OPERATION_UPDATE: {
1240 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1241 return;
1242 }
1243
1244 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001245 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001246
1247 // Privileged apps can do whatever they want.
1248 if ((packageInfo.applicationInfo.privateFlags
1249 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1250 return;
1251 }
1252
1253 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1254 packageInfo.applicationInfo.targetSdkVersion, name);
1255 } break;
1256
1257 case MUTATION_OPERATION_DELETE: {
1258 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1259 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1260 throw new IllegalArgumentException("You cannot delete system defined"
1261 + " secure settings.");
1262 }
1263
1264 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001265 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001266
1267 // Privileged apps can do whatever they want.
1268 if ((packageInfo.applicationInfo.privateFlags &
1269 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1270 return;
1271 }
1272
1273 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1274 packageInfo.applicationInfo.targetSdkVersion, name);
1275 } break;
1276 }
1277 }
1278
Xiaohui Chen43765b72015-08-31 10:57:33 -07001279 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001280 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001281 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1282 getCallingPackage(), 0, userId);
1283 if (packageInfo != null) {
1284 return packageInfo;
1285 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001286 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001287 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001288 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001289 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001290 }
1291
1292 private int getGroupParentLocked(int userId) {
1293 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001294 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001295 return userId;
1296 }
1297 // We are in the same process with the user manager and the returned
1298 // user info is a cached instance, so just look up instead of cache.
1299 final long identity = Binder.clearCallingIdentity();
1300 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001301 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001302 UserInfo userInfo = mUserManager.getProfileParent(userId);
1303 return (userInfo != null) ? userInfo.id : userId;
1304 } finally {
1305 Binder.restoreCallingIdentity(identity);
1306 }
1307 }
1308
Svetoslav683914b2015-01-15 14:22:26 -08001309 private void enforceWritePermission(String permission) {
1310 if (getContext().checkCallingOrSelfPermission(permission)
1311 != PackageManager.PERMISSION_GRANTED) {
1312 throw new SecurityException("Permission denial: writing to settings requires:"
1313 + permission);
1314 }
1315 }
1316
1317 /*
1318 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1319 * This setting contains a list of the currently enabled location providers.
1320 * But helper functions in android.providers.Settings can enable or disable
1321 * a single provider by using a "+" or "-" prefix before the provider name.
1322 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001323 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1324 * is set, the said method will only allow values with the "-" prefix.
1325 *
Svetoslav683914b2015-01-15 14:22:26 -08001326 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001327 */
Svet Ganov53a441c2016-04-19 19:38:00 -07001328 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId,
1329 boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001330 if (TextUtils.isEmpty(value)) {
1331 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001332 }
1333
Svetoslav683914b2015-01-15 14:22:26 -08001334 final char prefix = value.charAt(0);
1335 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001336 if (forceNotify) {
1337 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1338 mSettingsRegistry.notifyForSettingsChange(key,
1339 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1340 }
Svetoslav683914b2015-01-15 14:22:26 -08001341 return false;
1342 }
1343
1344 // skip prefix
1345 value = value.substring(1);
1346
Svetoslav7ec28e82015-05-20 17:01:10 -07001347 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001348 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1349
1350 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1351
1352 int index = oldProviders.indexOf(value);
1353 int end = index + value.length();
1354
1355 // check for commas to avoid matching on partial string
1356 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1357 index = -1;
1358 }
1359
1360 // check for commas to avoid matching on partial string
1361 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1362 index = -1;
1363 }
1364
1365 String newProviders;
1366
1367 if (prefix == '+' && index < 0) {
1368 // append the provider to the list if not present
1369 if (oldProviders.length() == 0) {
1370 newProviders = value;
1371 } else {
1372 newProviders = oldProviders + ',' + value;
1373 }
1374 } else if (prefix == '-' && index >= 0) {
1375 // remove the provider from the list if present
1376 // remove leading or trailing comma
1377 if (index > 0) {
1378 index--;
1379 } else if (end < oldProviders.length()) {
1380 end++;
1381 }
1382
1383 newProviders = oldProviders.substring(0, index);
1384 if (end < oldProviders.length()) {
1385 newProviders += oldProviders.substring(end);
1386 }
1387 } else {
1388 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001389 if (forceNotify) {
1390 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1391 mSettingsRegistry.notifyForSettingsChange(key,
1392 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1393 }
Svetoslav683914b2015-01-15 14:22:26 -08001394 return false;
1395 }
1396
Svet Ganov53a441c2016-04-19 19:38:00 -07001397 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001398 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svet Ganov53a441c2016-04-19 19:38:00 -07001399 getCallingPackage(), forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001400 }
1401
Svetoslav683914b2015-01-15 14:22:26 -08001402 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1403 int targetSdkVersion, String name) {
1404 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1405 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1406 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1407 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1408 + " This will soon become an error.");
1409 } else {
1410 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1411 + " This will soon become an error.");
1412 }
1413 } else {
1414 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1415 throw new IllegalArgumentException("You cannot change private secure settings.");
1416 } else {
1417 throw new IllegalArgumentException("You cannot keep your settings in"
1418 + " the secure settings.");
1419 }
1420 }
1421 }
1422
1423 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1424 if (requestingUserId == UserHandle.getCallingUserId()) {
1425 return requestingUserId;
1426 }
1427 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1428 Binder.getCallingUid(), requestingUserId, false, true,
1429 "get/set setting for user", null);
1430 }
1431
Svet Ganov53a441c2016-04-19 19:38:00 -07001432 private Bundle packageValueForCallResult(Setting setting,
1433 boolean trackingGeneration) {
1434 if (!trackingGeneration) {
1435 if (setting.isNull()) {
1436 return NULL_SETTING_BUNDLE;
1437 }
1438 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001439 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001440 Bundle result = new Bundle();
1441 result.putString(Settings.NameValueTable.VALUE,
1442 !setting.isNull() ? setting.getValue() : null);
1443 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getkey());
1444 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001445 }
1446
1447 private static int getRequestingUserId(Bundle args) {
1448 final int callingUserId = UserHandle.getCallingUserId();
1449 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1450 : callingUserId;
1451 }
1452
Svet Ganov53a441c2016-04-19 19:38:00 -07001453 private boolean isTrackingGeneration(Bundle args) {
1454 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1455 }
1456
Svetoslav683914b2015-01-15 14:22:26 -08001457 private static String getSettingValue(Bundle args) {
1458 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1459 }
1460
1461 private static String getValidTableOrThrow(Uri uri) {
1462 if (uri.getPathSegments().size() > 0) {
1463 String table = uri.getPathSegments().get(0);
1464 if (DatabaseHelper.isValidTable(table)) {
1465 return table;
1466 }
1467 throw new IllegalArgumentException("Bad root path: " + table);
1468 }
1469 throw new IllegalArgumentException("Invalid URI:" + uri);
1470 }
1471
1472 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001473 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001474 return new MatrixCursor(projection, 0);
1475 }
1476 MatrixCursor cursor = new MatrixCursor(projection, 1);
1477 appendSettingToCursor(cursor, setting);
1478 return cursor;
1479 }
1480
1481 private static String[] normalizeProjection(String[] projection) {
1482 if (projection == null) {
1483 return ALL_COLUMNS;
1484 }
1485
1486 final int columnCount = projection.length;
1487 for (int i = 0; i < columnCount; i++) {
1488 String column = projection[i];
1489 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1490 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001491 }
1492 }
1493
Svetoslav683914b2015-01-15 14:22:26 -08001494 return projection;
1495 }
1496
1497 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001498 if (setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07001499 return;
1500 }
Svetoslav683914b2015-01-15 14:22:26 -08001501 final int columnCount = cursor.getColumnCount();
1502
1503 String[] values = new String[columnCount];
1504
1505 for (int i = 0; i < columnCount; i++) {
1506 String column = cursor.getColumnName(i);
1507
1508 switch (column) {
1509 case Settings.NameValueTable._ID: {
1510 values[i] = setting.getId();
1511 } break;
1512
1513 case Settings.NameValueTable.NAME: {
1514 values[i] = setting.getName();
1515 } break;
1516
1517 case Settings.NameValueTable.VALUE: {
1518 values[i] = setting.getValue();
1519 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001520 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001521 }
1522
Svetoslav683914b2015-01-15 14:22:26 -08001523 cursor.addRow(values);
1524 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001525
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001526 private static boolean isKeyValid(String key) {
1527 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1528 }
1529
Svetoslav683914b2015-01-15 14:22:26 -08001530 private static final class Arguments {
1531 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1532 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1533
1534 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1535 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1536
1537 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1538 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1539
1540 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1541 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1542
1543 public final String table;
1544 public final String name;
1545
1546 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1547 final int segmentSize = uri.getPathSegments().size();
1548 switch (segmentSize) {
1549 case 1: {
1550 if (where != null
1551 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1552 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1553 && whereArgs.length == 1) {
1554 name = whereArgs[0];
1555 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001556 return;
Svetoslav683914b2015-01-15 14:22:26 -08001557 } else if (where != null
1558 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1559 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1560 final int startIndex = Math.max(where.indexOf("'"),
1561 where.indexOf("\"")) + 1;
1562 final int endIndex = Math.max(where.lastIndexOf("'"),
1563 where.lastIndexOf("\""));
1564 name = where.substring(startIndex, endIndex);
1565 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001566 return;
Svetoslav683914b2015-01-15 14:22:26 -08001567 } else if (supportAll && where == null && whereArgs == null) {
1568 name = null;
1569 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001570 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001571 }
Svetoslav683914b2015-01-15 14:22:26 -08001572 } break;
1573
Svetoslav28494652015-02-12 14:11:42 -08001574 case 2: {
1575 if (where == null && whereArgs == null) {
1576 name = uri.getPathSegments().get(1);
1577 table = computeTableForSetting(uri, name);
1578 return;
1579 }
1580 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001581 }
Svetoslav28494652015-02-12 14:11:42 -08001582
1583 EventLogTags.writeUnsupportedSettingsQuery(
1584 uri.toSafeString(), where, Arrays.toString(whereArgs));
1585 String message = String.format( "Supported SQL:\n"
1586 + " uri content://some_table/some_property with null where and where args\n"
1587 + " uri content://some_table with query name=? and single name as arg\n"
1588 + " uri content://some_table with query name=some_name and null args\n"
1589 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1590 Arrays.toString(whereArgs));
1591 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001592 }
1593
Svetoslav28494652015-02-12 14:11:42 -08001594 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001595 String table = getValidTableOrThrow(uri);
1596
1597 if (name != null) {
1598 if (sSystemMovedToSecureSettings.contains(name)) {
1599 table = TABLE_SECURE;
1600 }
1601
1602 if (sSystemMovedToGlobalSettings.contains(name)) {
1603 table = TABLE_GLOBAL;
1604 }
1605
1606 if (sSecureMovedToGlobalSettings.contains(name)) {
1607 table = TABLE_GLOBAL;
1608 }
1609
1610 if (sGlobalMovedToSecureSettings.contains(name)) {
1611 table = TABLE_SECURE;
1612 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001613 }
Svetoslav683914b2015-01-15 14:22:26 -08001614
1615 return table;
1616 }
1617 }
1618
1619 final class SettingsRegistry {
1620 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1621
Svetoslav683914b2015-01-15 14:22:26 -08001622 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1623 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1624 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1625
1626 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1627
Svet Ganov53a441c2016-04-19 19:38:00 -07001628 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08001629
Svetoslav7e0683b2015-08-03 16:02:52 -07001630 private final Handler mHandler;
1631
Svet Ganov53a441c2016-04-19 19:38:00 -07001632 private final BackupManager mBackupManager;
1633
Svetoslav683914b2015-01-15 14:22:26 -08001634 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07001635 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07001636 mGenerationRegistry = new GenerationRegistry(mLock);
1637 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08001638 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001639 }
1640
Svetoslav683914b2015-01-15 14:22:26 -08001641 public List<String> getSettingsNamesLocked(int type, int userId) {
1642 final int key = makeKey(type, userId);
1643 SettingsState settingsState = peekSettingsStateLocked(key);
1644 return settingsState.getSettingNamesLocked();
1645 }
1646
1647 public SettingsState getSettingsLocked(int type, int userId) {
1648 final int key = makeKey(type, userId);
1649 return peekSettingsStateLocked(key);
1650 }
1651
1652 public void ensureSettingsForUserLocked(int userId) {
1653 // Migrate the setting for this user if needed.
1654 migrateLegacySettingsForUserIfNeededLocked(userId);
1655
1656 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001657 if (userId == UserHandle.USER_SYSTEM) {
1658 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001659 ensureSettingsStateLocked(globalKey);
1660 }
1661
1662 // Ensure secure settings loaded.
1663 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1664 ensureSettingsStateLocked(secureKey);
1665
1666 // Make sure the secure settings have an Android id set.
1667 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1668 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1669
1670 // Ensure system settings loaded.
1671 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1672 ensureSettingsStateLocked(systemKey);
1673
1674 // Upgrade the settings to the latest version.
1675 UpgradeController upgrader = new UpgradeController(userId);
1676 upgrader.upgradeIfNeededLocked();
1677 }
1678
1679 private void ensureSettingsStateLocked(int key) {
1680 if (mSettingsStates.get(key) == null) {
1681 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1682 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
Svet Ganova8f90262016-05-10 08:44:48 -07001683 maxBytesPerPackage, mBackgroundHandler);
Svetoslav683914b2015-01-15 14:22:26 -08001684 mSettingsStates.put(key, settingsState);
1685 }
1686 }
1687
1688 public void removeUserStateLocked(int userId, boolean permanently) {
1689 // We always keep the global settings in memory.
1690
1691 // Nuke system settings.
1692 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1693 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1694 if (systemSettingsState != null) {
1695 if (permanently) {
1696 mSettingsStates.remove(systemKey);
1697 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001698 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001699 systemSettingsState.destroyLocked(new Runnable() {
1700 @Override
1701 public void run() {
1702 mSettingsStates.remove(systemKey);
1703 }
1704 });
1705 }
1706 }
1707
1708 // Nuke secure settings.
1709 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1710 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1711 if (secureSettingsState != null) {
1712 if (permanently) {
1713 mSettingsStates.remove(secureKey);
1714 secureSettingsState.destroyLocked(null);
1715 } else {
1716 secureSettingsState.destroyLocked(new Runnable() {
1717 @Override
1718 public void run() {
1719 mSettingsStates.remove(secureKey);
1720 }
1721 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001722 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001723 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001724
1725 // Nuke generation tracking data
1726 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001727 }
1728
Svetoslav683914b2015-01-15 14:22:26 -08001729 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001730 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001731 final int key = makeKey(type, userId);
1732
1733 SettingsState settingsState = peekSettingsStateLocked(key);
1734 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1735
Svet Ganov53a441c2016-04-19 19:38:00 -07001736 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001737 notifyForSettingsChange(key, name);
1738 }
1739 return success;
1740 }
1741
Svet Ganov53a441c2016-04-19 19:38:00 -07001742 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001743 final int key = makeKey(type, userId);
1744
1745 SettingsState settingsState = peekSettingsStateLocked(key);
1746 final boolean success = settingsState.deleteSettingLocked(name);
1747
Svet Ganov53a441c2016-04-19 19:38:00 -07001748 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001749 notifyForSettingsChange(key, name);
1750 }
1751 return success;
1752 }
1753
1754 public Setting getSettingLocked(int type, int userId, String name) {
1755 final int key = makeKey(type, userId);
1756
1757 SettingsState settingsState = peekSettingsStateLocked(key);
1758 return settingsState.getSettingLocked(name);
1759 }
1760
1761 public boolean updateSettingLocked(int type, int userId, String name, String value,
Svet Ganov53a441c2016-04-19 19:38:00 -07001762 String packageName, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001763 final int key = makeKey(type, userId);
1764
1765 SettingsState settingsState = peekSettingsStateLocked(key);
1766 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1767
Svet Ganov53a441c2016-04-19 19:38:00 -07001768 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08001769 notifyForSettingsChange(key, name);
1770 }
1771
1772 return success;
1773 }
1774
1775 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001776 // Global and secure settings are signature protected. Apps signed
1777 // by the platform certificate are generally not uninstalled and
1778 // the main exception is tests. We trust components signed
1779 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001780
1781 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1782 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001783 if (systemSettings != null) {
1784 systemSettings.onPackageRemovedLocked(packageName);
1785 }
Svetoslav683914b2015-01-15 14:22:26 -08001786 }
1787
1788 private SettingsState peekSettingsStateLocked(int key) {
1789 SettingsState settingsState = mSettingsStates.get(key);
1790 if (settingsState != null) {
1791 return settingsState;
1792 }
1793
1794 ensureSettingsForUserLocked(getUserIdFromKey(key));
1795 return mSettingsStates.get(key);
1796 }
1797
1798 private void migrateAllLegacySettingsIfNeeded() {
1799 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001800 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001801 File globalFile = getSettingsFile(key);
1802 if (globalFile.exists()) {
1803 return;
1804 }
1805
1806 final long identity = Binder.clearCallingIdentity();
1807 try {
1808 List<UserInfo> users = mUserManager.getUsers(true);
1809
1810 final int userCount = users.size();
1811 for (int i = 0; i < userCount; i++) {
1812 final int userId = users.get(i).id;
1813
1814 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1815 SQLiteDatabase database = dbHelper.getWritableDatabase();
1816 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1817
1818 // Upgrade to the latest version.
1819 UpgradeController upgrader = new UpgradeController(userId);
1820 upgrader.upgradeIfNeededLocked();
1821
1822 // Drop from memory if not a running user.
1823 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1824 removeUserStateLocked(userId, false);
1825 }
1826 }
1827 } finally {
1828 Binder.restoreCallingIdentity(identity);
1829 }
1830 }
1831 }
1832
1833 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1834 // Every user has secure settings and if no file we need to migrate.
1835 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1836 File secureFile = getSettingsFile(secureKey);
1837 if (secureFile.exists()) {
1838 return;
1839 }
1840
1841 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1842 SQLiteDatabase database = dbHelper.getWritableDatabase();
1843
1844 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1845 }
1846
1847 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1848 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001849 // Move over the system settings.
1850 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1851 ensureSettingsStateLocked(systemKey);
1852 SettingsState systemSettings = mSettingsStates.get(systemKey);
1853 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1854 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08001855
1856 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001857 // Do this after System settings, since this is the first thing we check when deciding
1858 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08001859 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1860 ensureSettingsStateLocked(secureKey);
1861 SettingsState secureSettings = mSettingsStates.get(secureKey);
1862 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1863 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1864 secureSettings.persistSyncLocked();
1865
Amith Yamasanibf2ef612016-03-07 16:37:18 -08001866 // Move over the global settings if owner.
1867 // Do this last, since this is the first thing we check when deciding
1868 // to skip over migration from db to xml for owner user.
1869 if (userId == UserHandle.USER_SYSTEM) {
1870 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1871 ensureSettingsStateLocked(globalKey);
1872 SettingsState globalSettings = mSettingsStates.get(globalKey);
1873 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1874 globalSettings.persistSyncLocked();
1875 }
Svetoslav683914b2015-01-15 14:22:26 -08001876
1877 // Drop the database as now all is moved and persisted.
1878 if (DROP_DATABASE_ON_MIGRATION) {
1879 dbHelper.dropDatabase();
1880 } else {
1881 dbHelper.backupDatabase();
1882 }
1883 }
1884
1885 private void migrateLegacySettingsLocked(SettingsState settingsState,
1886 SQLiteDatabase database, String table) {
1887 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1888 queryBuilder.setTables(table);
1889
1890 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1891 null, null, null, null, null);
1892
1893 if (cursor == null) {
1894 return;
1895 }
1896
1897 try {
1898 if (!cursor.moveToFirst()) {
1899 return;
1900 }
1901
1902 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1903 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1904
1905 settingsState.setVersionLocked(database.getVersion());
1906
1907 while (!cursor.isAfterLast()) {
1908 String name = cursor.getString(nameColumnIdx);
1909 String value = cursor.getString(valueColumnIdx);
1910 settingsState.insertSettingLocked(name, value,
1911 SettingsState.SYSTEM_PACKAGE_NAME);
1912 cursor.moveToNext();
1913 }
1914 } finally {
1915 cursor.close();
1916 }
1917 }
1918
1919 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1920 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1921
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09001922 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001923 return;
1924 }
1925
1926 final int userId = getUserIdFromKey(secureSettings.mKey);
1927
1928 final UserInfo user;
1929 final long identity = Binder.clearCallingIdentity();
1930 try {
1931 user = mUserManager.getUserInfo(userId);
1932 } finally {
1933 Binder.restoreCallingIdentity(identity);
1934 }
1935 if (user == null) {
1936 // Can happen due to races when deleting users - treat as benign.
1937 return;
1938 }
1939
1940 String androidId = Long.toHexString(new SecureRandom().nextLong());
1941 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1942 SettingsState.SYSTEM_PACKAGE_NAME);
1943
1944 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1945 + "] for user " + userId);
1946
1947 // Write a drop box entry if it's a restricted profile
1948 if (user.isRestricted()) {
1949 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1950 Context.DROPBOX_SERVICE);
1951 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1952 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1953 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1954 }
1955 }
1956 }
1957
1958 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001959 final int userId = getUserIdFromKey(key);
1960 Uri uri = getNotificationUriFor(key, name);
1961
Svetoslav7e0683b2015-08-03 16:02:52 -07001962 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1963 userId, 0, uri).sendToTarget();
1964
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001965 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001966 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1967 sSecureCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001968 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001969 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
1970 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001971 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001972
1973 mGenerationRegistry.incrementGeneration(key);
1974
1975 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001976 }
1977
Svet Ganov53a441c2016-04-19 19:38:00 -07001978 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001979 Set<String> keysCloned) {
1980 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001981 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001982 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001983 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001984 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07001985 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07001986 final int key = makeKey(type, profileId);
1987 mGenerationRegistry.incrementGeneration(key);
1988
1989 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001990 }
1991 }
1992 }
Svetoslav683914b2015-01-15 14:22:26 -08001993 }
1994
Svetoslav683914b2015-01-15 14:22:26 -08001995 private boolean isGlobalSettingsKey(int key) {
1996 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1997 }
1998
1999 private boolean isSystemSettingsKey(int key) {
2000 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2001 }
2002
2003 private boolean isSecureSettingsKey(int key) {
2004 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2005 }
2006
2007 private File getSettingsFile(int key) {
2008 if (isGlobalSettingsKey(key)) {
2009 final int userId = getUserIdFromKey(key);
2010 return new File(Environment.getUserSystemDirectory(userId),
2011 SETTINGS_FILE_GLOBAL);
2012 } else if (isSystemSettingsKey(key)) {
2013 final int userId = getUserIdFromKey(key);
2014 return new File(Environment.getUserSystemDirectory(userId),
2015 SETTINGS_FILE_SYSTEM);
2016 } else if (isSecureSettingsKey(key)) {
2017 final int userId = getUserIdFromKey(key);
2018 return new File(Environment.getUserSystemDirectory(userId),
2019 SETTINGS_FILE_SECURE);
2020 } else {
2021 throw new IllegalArgumentException("Invalid settings key:" + key);
2022 }
2023 }
2024
2025 private Uri getNotificationUriFor(int key, String name) {
2026 if (isGlobalSettingsKey(key)) {
2027 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2028 : Settings.Global.CONTENT_URI;
2029 } else if (isSecureSettingsKey(key)) {
2030 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2031 : Settings.Secure.CONTENT_URI;
2032 } else if (isSystemSettingsKey(key)) {
2033 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2034 : Settings.System.CONTENT_URI;
2035 } else {
2036 throw new IllegalArgumentException("Invalid settings key:" + key);
2037 }
2038 }
2039
2040 private int getMaxBytesPerPackageForType(int type) {
2041 switch (type) {
2042 case SETTINGS_TYPE_GLOBAL:
2043 case SETTINGS_TYPE_SECURE: {
2044 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2045 }
2046
2047 default: {
2048 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2049 }
2050 }
2051 }
2052
Svetoslav7e0683b2015-08-03 16:02:52 -07002053 private final class MyHandler extends Handler {
2054 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2055 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2056
2057 public MyHandler(Looper looper) {
2058 super(looper);
2059 }
2060
2061 @Override
2062 public void handleMessage(Message msg) {
2063 switch (msg.what) {
2064 case MSG_NOTIFY_URI_CHANGED: {
2065 final int userId = msg.arg1;
2066 Uri uri = (Uri) msg.obj;
2067 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2068 if (DEBUG) {
2069 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2070 }
2071 } break;
2072
2073 case MSG_NOTIFY_DATA_CHANGED: {
2074 mBackupManager.dataChanged();
2075 } break;
2076 }
2077 }
2078 }
2079
Svetoslav683914b2015-01-15 14:22:26 -08002080 private final class UpgradeController {
Daniel U02ba6122016-04-01 18:41:42 +01002081 private static final int SETTINGS_VERSION = 127;
Svetoslav683914b2015-01-15 14:22:26 -08002082
2083 private final int mUserId;
2084
2085 public UpgradeController(int userId) {
2086 mUserId = userId;
2087 }
2088
2089 public void upgradeIfNeededLocked() {
2090 // The version of all settings for a user is the same (all users have secure).
2091 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002092 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002093
2094 // Try an update from the current state.
2095 final int oldVersion = secureSettings.getVersionLocked();
2096 final int newVersion = SETTINGS_VERSION;
2097
Svet Ganovc9755bc2015-03-28 13:21:22 -07002098 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002099 if (oldVersion == newVersion) {
2100 return;
2101 }
2102
2103 // Try to upgrade.
2104 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2105
2106 // If upgrade failed start from scratch and upgrade.
2107 if (curVersion != newVersion) {
2108 // Drop state we have for this user.
2109 removeUserStateLocked(mUserId, true);
2110
2111 // Recreate the database.
2112 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2113 SQLiteDatabase database = dbHelper.getWritableDatabase();
2114 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2115
2116 // Migrate the settings for this user.
2117 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2118
2119 // Now upgrade should work fine.
2120 onUpgradeLocked(mUserId, oldVersion, newVersion);
2121 }
2122
2123 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002124 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002125 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002126 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002127 globalSettings.setVersionLocked(newVersion);
2128 }
2129
2130 // Set the secure settings version.
2131 secureSettings.setVersionLocked(newVersion);
2132
2133 // Set the system settings version.
2134 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002135 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002136 systemSettings.setVersionLocked(newVersion);
2137 }
2138
2139 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002140 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002141 }
2142
2143 private SettingsState getSecureSettingsLocked(int userId) {
2144 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2145 }
2146
2147 private SettingsState getSystemSettingsLocked(int userId) {
2148 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
2149 }
2150
Jeff Brown503cffc2015-03-26 18:08:51 -07002151 /**
2152 * You must perform all necessary mutations to bring the settings
2153 * for this user from the old to the new version. When you add a new
2154 * upgrade step you *must* update SETTINGS_VERSION.
2155 *
2156 * This is an example of moving a setting from secure to global.
2157 *
2158 * // v119: Example settings changes.
2159 * if (currentVersion == 118) {
2160 * if (userId == UserHandle.USER_OWNER) {
2161 * // Remove from the secure settings.
2162 * SettingsState secureSettings = getSecureSettingsLocked(userId);
2163 * String name = "example_setting_to_move";
2164 * String value = secureSettings.getSetting(name);
2165 * secureSettings.deleteSetting(name);
2166 *
2167 * // Add to the global settings.
2168 * SettingsState globalSettings = getGlobalSettingsLocked();
2169 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
2170 * }
2171 *
2172 * // Update the current version.
2173 * currentVersion = 119;
2174 * }
2175 */
Svetoslav683914b2015-01-15 14:22:26 -08002176 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
2177 if (DEBUG) {
2178 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
2179 + oldVersion + " to version: " + newVersion);
2180 }
2181
Jeff Brown503cffc2015-03-26 18:08:51 -07002182 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08002183
John Spurlocke11ae112015-05-11 16:09:03 -04002184 // v119: Reset zen + ringer mode.
2185 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002186 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04002187 final SettingsState globalSettings = getGlobalSettingsLocked();
2188 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
2189 Integer.toString(Settings.Global.ZEN_MODE_OFF),
2190 SettingsState.SYSTEM_PACKAGE_NAME);
2191 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
2192 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
2193 SettingsState.SYSTEM_PACKAGE_NAME);
2194 }
2195 currentVersion = 119;
2196 }
2197
Jason Monk27bbb2d2015-03-31 16:46:39 -04002198 // v120: Add double tap to wake setting.
2199 if (currentVersion == 119) {
2200 SettingsState secureSettings = getSecureSettingsLocked(userId);
2201 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
2202 getContext().getResources().getBoolean(
2203 R.bool.def_double_tap_to_wake) ? "1" : "0",
2204 SettingsState.SYSTEM_PACKAGE_NAME);
2205
2206 currentVersion = 120;
2207 }
2208
Svetoslav7e0683b2015-08-03 16:02:52 -07002209 if (currentVersion == 120) {
2210 // Before 121, we used a different string encoding logic. We just bump the
2211 // version here; SettingsState knows how to handle pre-version 120 files.
2212 currentVersion = 121;
2213 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002214
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002215 if (currentVersion == 121) {
2216 // Version 122: allow OEMs to set a default payment component in resources.
2217 // Note that we only write the default if no default has been set;
2218 // if there is, we just leave the default at whatever it currently is.
2219 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2220 String defaultComponent = (getContext().getResources().getString(
2221 R.string.def_nfc_payment_component));
2222 Setting currentSetting = secureSettings.getSettingLocked(
2223 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2224 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002225 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02002226 secureSettings.insertSettingLocked(
2227 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2228 defaultComponent,
2229 SettingsState.SYSTEM_PACKAGE_NAME);
2230 }
2231 currentVersion = 122;
2232 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002233
2234 if (currentVersion == 122) {
2235 // Version 123: Adding a default value for the ability to add a user from
2236 // the lock screen.
2237 if (userId == UserHandle.USER_SYSTEM) {
2238 final SettingsState globalSettings = getGlobalSettingsLocked();
2239 Setting currentSetting = globalSettings.getSettingLocked(
2240 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002241 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08002242 globalSettings.insertSettingLocked(
2243 Settings.Global.ADD_USERS_WHEN_LOCKED,
2244 getContext().getResources().getBoolean(
2245 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
2246 SettingsState.SYSTEM_PACKAGE_NAME);
2247 }
2248 }
2249 currentVersion = 123;
2250 }
Bryce Leebd179282015-12-17 19:01:37 -08002251
2252 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08002253 final SettingsState globalSettings = getGlobalSettingsLocked();
2254 String defaultDisabledProfiles = (getContext().getResources().getString(
2255 R.string.def_bluetooth_disabled_profiles));
2256 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
2257 defaultDisabledProfiles, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08002258 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08002259 }
2260
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002261 if (currentVersion == 124) {
2262 // Version 124: allow OEMs to set a default value for whether IME should be
2263 // shown when a physical keyboard is connected.
2264 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2265 Setting currentSetting = secureSettings.getSettingLocked(
2266 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002267 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08002268 secureSettings.insertSettingLocked(
2269 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
2270 getContext().getResources().getBoolean(
2271 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
2272 SettingsState.SYSTEM_PACKAGE_NAME);
2273 }
2274 currentVersion = 125;
2275 }
2276
Ruben Brunk98576cf2016-03-07 18:54:28 -08002277 if (currentVersion == 125) {
2278 // Version 125: Allow OEMs to set the default VR service.
2279 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2280
2281 Setting currentSetting = secureSettings.getSettingLocked(
2282 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002283 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08002284 ArraySet<ComponentName> l =
2285 SystemConfig.getInstance().getDefaultVrComponents();
2286
2287 if (l != null && !l.isEmpty()) {
2288 StringBuilder b = new StringBuilder();
2289 boolean start = true;
2290 for (ComponentName c : l) {
2291 if (!start) {
2292 b.append(':');
2293 }
2294 b.append(c.flattenToString());
2295 start = false;
2296 }
2297 secureSettings.insertSettingLocked(
2298 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
2299 SettingsState.SYSTEM_PACKAGE_NAME);
2300 }
2301
2302 }
2303 currentVersion = 126;
2304 }
2305
Daniel U02ba6122016-04-01 18:41:42 +01002306 if (currentVersion == 126) {
2307 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
2308 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
2309 if (mUserManager.isManagedProfile(userId)) {
2310 final SettingsState systemSecureSettings =
2311 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
2312
2313 final Setting showNotifications = systemSecureSettings.getSettingLocked(
2314 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002315 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002316 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2317 secureSettings.insertSettingLocked(
2318 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2319 showNotifications.getValue(),
2320 SettingsState.SYSTEM_PACKAGE_NAME);
2321 }
2322
2323 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
2324 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002325 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01002326 final SettingsState secureSettings = getSecureSettingsLocked(userId);
2327 secureSettings.insertSettingLocked(
2328 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2329 allowPrivate.getValue(),
2330 SettingsState.SYSTEM_PACKAGE_NAME);
2331 }
2332 }
2333 currentVersion = 127;
2334 }
2335
Jeff Brown503cffc2015-03-26 18:08:51 -07002336 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002337
Jeff Brown503cffc2015-03-26 18:08:51 -07002338 // Return the current version.
2339 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002340 }
2341 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002342 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002343}