blob: 3971706b02d8ac5b17ec353cd3b6d9791f586ef0 [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;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070024import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentValues;
26import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070027import android.content.Intent;
28import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080029import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070030import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080031import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070033import android.content.pm.UserInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080035import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.sqlite.SQLiteDatabase;
37import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040039import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070041import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070044import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080045import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070046import android.os.Handler;
47import android.os.Looper;
48import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070050import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070051import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070053import android.os.UserHandle;
54import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070055import android.provider.Settings;
56import android.text.TextUtils;
Svetoslav683914b2015-01-15 14:22:26 -080057import android.util.ArrayMap;
58import android.util.ArraySet;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.util.Slog;
60import android.util.SparseArray;
John Spurlocke11ae112015-05-11 16:09:03 -040061
Svetoslav683914b2015-01-15 14:22:26 -080062import com.android.internal.annotations.GuardedBy;
63import com.android.internal.content.PackageMonitor;
64import com.android.internal.os.BackgroundThread;
John Spurlocke11ae112015-05-11 16:09:03 -040065
Svetoslav683914b2015-01-15 14:22:26 -080066import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080067import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080068import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080069import java.io.PrintWriter;
Svetoslav683914b2015-01-15 14:22:26 -080070import java.security.SecureRandom;
71import java.util.Arrays;
72import java.util.List;
73import java.util.Map;
74import java.util.Set;
75import java.util.regex.Pattern;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070076
Svetoslav683914b2015-01-15 14:22:26 -080077import com.android.providers.settings.SettingsState.Setting;
78
79/**
80 * <p>
81 * This class is a content provider that publishes the system settings.
82 * It can be accessed via the content provider APIs or via custom call
83 * commands. The latter is a bit faster and is the preferred way to access
84 * the platform settings.
85 * </p>
86 * <p>
87 * There are three settings types, global (with signature level protection
88 * and shared across users), secure (with signature permission level
89 * protection and per user), and system (with dangerous permission level
90 * protection and per user). Global settings are stored under the device owner.
91 * Each of these settings is represented by a {@link
92 * com.android.providers.settings.SettingsState} object mapped to an integer
93 * key derived from the setting type in the most significant bits and user
94 * id in the least significant bits. Settings are synchronously loaded on
95 * instantiation of a SettingsState and asynchronously persisted on mutation.
96 * Settings are stored in the user specific system directory.
97 * </p>
98 * <p>
99 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
100 * and get a warning. Targeting higher API version prohibits this as the
101 * system settings are not a place for apps to save their state. When a package
102 * is removed the settings it added are deleted. Apps cannot delete system
103 * settings added by the platform. System settings values are validated to
104 * ensure the clients do not put bad values. Global and secure settings are
105 * changed only by trusted parties, therefore no validation is performed. Also
106 * there is a limit on the amount of app specific settings that can be added
107 * to prevent unlimited growth of the system process memory footprint.
108 * </p>
109 */
110@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700111public class SettingsProvider extends ContentProvider {
Svetoslav683914b2015-01-15 14:22:26 -0800112 private static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113
Svetoslav683914b2015-01-15 14:22:26 -0800114 private static final boolean DROP_DATABASE_ON_MIGRATION = !Build.IS_DEBUGGABLE;
115
116 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700117
Christopher Tate06efb532012-08-24 15:29:27 -0700118 private static final String TABLE_SYSTEM = "system";
119 private static final String TABLE_SECURE = "secure";
120 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800121
122 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String TABLE_FAVORITES = "favorites";
124 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800125 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
126 private static final String TABLE_BOOKMARKS = "bookmarks";
127 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Svetoslav683914b2015-01-15 14:22:26 -0800129 // The set of removed legacy tables.
130 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700131 static {
Svetoslav683914b2015-01-15 14:22:26 -0800132 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
133 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
134 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
135 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
136 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
137 }
Christopher Tate06efb532012-08-24 15:29:27 -0700138
Svetoslav683914b2015-01-15 14:22:26 -0800139 private static final int MUTATION_OPERATION_INSERT = 1;
140 private static final int MUTATION_OPERATION_DELETE = 2;
141 private static final int MUTATION_OPERATION_UPDATE = 3;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400142
Svetoslav683914b2015-01-15 14:22:26 -0800143 private static final String[] ALL_COLUMNS = new String[] {
144 Settings.NameValueTable._ID,
145 Settings.NameValueTable.NAME,
146 Settings.NameValueTable.VALUE
147 };
148
149 private static final Bundle NULL_SETTING = Bundle.forPair(Settings.NameValueTable.VALUE, null);
150
151 // Per user settings that cannot be modified if associated user restrictions are enabled.
152 private static final Map<String, String> sSettingToUserRestrictionMap = new ArrayMap<>();
153 static {
154 sSettingToUserRestrictionMap.put(Settings.Secure.LOCATION_MODE,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400155 UserManager.DISALLOW_SHARE_LOCATION);
Svetoslav683914b2015-01-15 14:22:26 -0800156 sSettingToUserRestrictionMap.put(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
157 UserManager.DISALLOW_SHARE_LOCATION);
158 sSettingToUserRestrictionMap.put(Settings.Secure.INSTALL_NON_MARKET_APPS,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400159 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Svetoslav683914b2015-01-15 14:22:26 -0800160 sSettingToUserRestrictionMap.put(Settings.Global.ADB_ENABLED,
161 UserManager.DISALLOW_DEBUGGING_FEATURES);
162 sSettingToUserRestrictionMap.put(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400163 UserManager.ENSURE_VERIFY_APPS);
Svetoslav683914b2015-01-15 14:22:26 -0800164 sSettingToUserRestrictionMap.put(Settings.Global.PREFERRED_NETWORK_MODE,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400165 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Christopher Tate06efb532012-08-24 15:29:27 -0700166 }
167
Svetoslav683914b2015-01-15 14:22:26 -0800168 // Per user secure settings that moved to the for all users global settings.
169 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
170 static {
171 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700172 }
173
Svetoslav683914b2015-01-15 14:22:26 -0800174 // Per user system settings that moved to the for all users global settings.
175 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
176 static {
177 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 }
179
Svetoslav683914b2015-01-15 14:22:26 -0800180 // Per user system settings that moved to the per user secure settings.
181 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
182 static {
183 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700184 }
185
Svetoslav683914b2015-01-15 14:22:26 -0800186 // Per all users global settings that moved to the per user secure settings.
187 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
188 static {
189 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700190 }
191
Svetoslav683914b2015-01-15 14:22:26 -0800192 // Per user secure settings that are cloned for the managed profiles of the user.
193 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
194 static {
195 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196 }
197
Svetoslav683914b2015-01-15 14:22:26 -0800198 // Per user system settings that are cloned for the managed profiles of the user.
199 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
200 static {
201 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400202 }
203
Svetoslav683914b2015-01-15 14:22:26 -0800204 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700205
Svetoslav683914b2015-01-15 14:22:26 -0800206 @GuardedBy("mLock")
207 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700208
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
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700215 @Override
216 public boolean onCreate() {
Svetoslav683914b2015-01-15 14:22:26 -0800217 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700218 mUserManager = UserManager.get(getContext());
219 mPackageManager = AppGlobals.getPackageManager();
Svetoslav683914b2015-01-15 14:22:26 -0800220 mSettingsRegistry = new SettingsRegistry();
221 }
222 registerBroadcastReceivers();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700223 return true;
224 }
225
Svetoslav683914b2015-01-15 14:22:26 -0800226 @Override
227 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700228 final int requestingUserId = getRequestingUserId(args);
229 switch (method) {
230 case Settings.CALL_METHOD_GET_GLOBAL: {
231 Setting setting = getGlobalSetting(name);
232 return packageValueForCallResult(setting);
Svetoslav683914b2015-01-15 14:22:26 -0800233 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700234
235 case Settings.CALL_METHOD_GET_SECURE: {
236 Setting setting = getSecureSetting(name, requestingUserId);
237 return packageValueForCallResult(setting);
238 }
239
240 case Settings.CALL_METHOD_GET_SYSTEM: {
241 Setting setting = getSystemSetting(name, requestingUserId);
242 return packageValueForCallResult(setting);
243 }
244
245 case Settings.CALL_METHOD_PUT_GLOBAL: {
246 String value = getSettingValue(args);
247 insertGlobalSetting(name, value, requestingUserId);
248 break;
249 }
250
251 case Settings.CALL_METHOD_PUT_SECURE: {
252 String value = getSettingValue(args);
253 insertSecureSetting(name, value, requestingUserId);
254 break;
255 }
256
257 case Settings.CALL_METHOD_PUT_SYSTEM: {
258 String value = getSettingValue(args);
259 insertSystemSetting(name, value, requestingUserId);
260 break;
261 }
262
263 default: {
264 Slog.w(LOG_TAG, "call() with invalid method: " + method);
265 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700266 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700267
Christopher Tate06efb532012-08-24 15:29:27 -0700268 return null;
269 }
270
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800271 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800272 public String getType(Uri uri) {
273 Arguments args = new Arguments(uri, null, null, true);
274 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700275 return "vnd.android.cursor.dir/" + args.table;
276 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700277 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278 }
279 }
280
281 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800282 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
283 String order) {
284 if (DEBUG) {
285 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700286 }
287
Svetoslav683914b2015-01-15 14:22:26 -0800288 Arguments args = new Arguments(uri, where, whereArgs, true);
289 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700290
Svetoslav683914b2015-01-15 14:22:26 -0800291 // If a legacy table that is gone, done.
292 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
293 return new MatrixCursor(normalizedProjection, 0);
294 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700295
Svetoslav7ec28e82015-05-20 17:01:10 -0700296 switch (args.table) {
297 case TABLE_GLOBAL: {
298 if (args.name != null) {
299 Setting setting = getGlobalSetting(args.name);
300 return packageSettingForQuery(setting, normalizedProjection);
301 } else {
302 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700303 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700304 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700305
Svetoslav7ec28e82015-05-20 17:01:10 -0700306 case TABLE_SECURE: {
307 final int userId = UserHandle.getCallingUserId();
308 if (args.name != null) {
309 Setting setting = getSecureSetting(args.name, userId);
310 return packageSettingForQuery(setting, normalizedProjection);
311 } else {
312 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800313 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700314 }
Svetoslav683914b2015-01-15 14:22:26 -0800315
Svetoslav7ec28e82015-05-20 17:01:10 -0700316 case TABLE_SYSTEM: {
317 final int userId = UserHandle.getCallingUserId();
318 if (args.name != null) {
319 Setting setting = getSystemSetting(args.name, userId);
320 return packageSettingForQuery(setting, normalizedProjection);
321 } else {
322 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800323 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700324 }
Svetoslav683914b2015-01-15 14:22:26 -0800325
Svetoslav7ec28e82015-05-20 17:01:10 -0700326 default: {
327 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700328 }
329 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700330 }
331
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800333 public Uri insert(Uri uri, ContentValues values) {
334 if (DEBUG) {
335 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700336 }
337
Svetoslav683914b2015-01-15 14:22:26 -0800338 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700339
Svetoslav683914b2015-01-15 14:22:26 -0800340 // If a legacy table that is gone, done.
341 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 return null;
343 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700344
Svetoslav683914b2015-01-15 14:22:26 -0800345 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700346 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800347 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700348 }
349
Svetoslav683914b2015-01-15 14:22:26 -0800350 String value = values.getAsString(Settings.Secure.VALUE);
351
Svetoslav7ec28e82015-05-20 17:01:10 -0700352 switch (table) {
353 case TABLE_GLOBAL: {
354 if (insertGlobalSetting(name, value, UserHandle.getCallingUserId())) {
355 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700356 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700357 } break;
358
359 case TABLE_SECURE: {
360 if (insertSecureSetting(name, value, UserHandle.getCallingUserId())) {
361 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
362 }
363 } break;
364
365 case TABLE_SYSTEM: {
366 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
367 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
368 }
369 } break;
370
371 default: {
372 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700373 }
374 }
375
Svetoslav683914b2015-01-15 14:22:26 -0800376 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700377 }
378
379 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800380 public int bulkInsert(Uri uri, ContentValues[] allValues) {
381 if (DEBUG) {
382 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700384
Svetoslav683914b2015-01-15 14:22:26 -0800385 int insertionCount = 0;
386 final int valuesCount = allValues.length;
387 for (int i = 0; i < valuesCount; i++) {
388 ContentValues values = allValues[i];
389 if (insert(uri, values) != null) {
390 insertionCount++;
391 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700392 }
Svetoslav683914b2015-01-15 14:22:26 -0800393
394 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700395 }
396
397 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800398 public int delete(Uri uri, String where, String[] whereArgs) {
399 if (DEBUG) {
400 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700402
Svetoslav683914b2015-01-15 14:22:26 -0800403 Arguments args = new Arguments(uri, where, whereArgs, false);
404
405 // If a legacy table that is gone, done.
406 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
407 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700408 }
Svetoslav683914b2015-01-15 14:22:26 -0800409
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700410 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800411 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700412 }
Svetoslav683914b2015-01-15 14:22:26 -0800413
Svetoslav7ec28e82015-05-20 17:01:10 -0700414 switch (args.table) {
415 case TABLE_GLOBAL: {
416 final int userId = UserHandle.getCallingUserId();
417 return deleteGlobalSetting(args.name, userId) ? 1 : 0;
418 }
Svetoslav683914b2015-01-15 14:22:26 -0800419
Svetoslav7ec28e82015-05-20 17:01:10 -0700420 case TABLE_SECURE: {
421 final int userId = UserHandle.getCallingUserId();
422 return deleteSecureSetting(args.name, userId) ? 1 : 0;
423 }
Svetoslav683914b2015-01-15 14:22:26 -0800424
Svetoslav7ec28e82015-05-20 17:01:10 -0700425 case TABLE_SYSTEM: {
426 final int userId = UserHandle.getCallingUserId();
427 return deleteSystemSetting(args.name, userId) ? 1 : 0;
428 }
429
430 default: {
431 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800432 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700433 }
Svetoslav683914b2015-01-15 14:22:26 -0800434 }
435
436 @Override
437 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
438 if (DEBUG) {
439 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700440 }
Svetoslav683914b2015-01-15 14:22:26 -0800441
442 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;
447 }
448
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700449 String name = values.getAsString(Settings.Secure.NAME);
450 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800451 return 0;
452 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700453 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800454
Svetoslav7ec28e82015-05-20 17:01:10 -0700455 switch (args.table) {
456 case TABLE_GLOBAL: {
457 final int userId = UserHandle.getCallingUserId();
458 return updateGlobalSetting(args.name, value, userId) ? 1 : 0;
459 }
Svetoslav683914b2015-01-15 14:22:26 -0800460
Svetoslav7ec28e82015-05-20 17:01:10 -0700461 case TABLE_SECURE: {
462 final int userId = UserHandle.getCallingUserId();
463 return updateSecureSetting(args.name, value, userId) ? 1 : 0;
464 }
Svetoslav683914b2015-01-15 14:22:26 -0800465
Svetoslav7ec28e82015-05-20 17:01:10 -0700466 case TABLE_SYSTEM: {
467 final int userId = UserHandle.getCallingUserId();
468 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
469 }
Svetoslav683914b2015-01-15 14:22:26 -0800470
Svetoslav7ec28e82015-05-20 17:01:10 -0700471 default: {
472 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800473 }
474 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700475 }
476
477 @Override
478 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey3b566b82014-11-12 10:39:56 -0800479 throw new FileNotFoundException("Direct file access no longer supported; "
480 + "ringtone playback is available through android.media.Ringtone");
Marco Nelissen69f593c2009-07-28 09:55:04 -0700481 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800482
Svetoslavb505ccc2015-02-17 12:41:04 -0800483 @Override
484 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
485 synchronized (mLock) {
486 final long identity = Binder.clearCallingIdentity();
487 try {
488 List<UserInfo> users = mUserManager.getUsers(true);
489 final int userCount = users.size();
490 for (int i = 0; i < userCount; i++) {
491 UserInfo user = users.get(i);
492 dumpForUser(user.id, pw);
493 }
494 } finally {
495 Binder.restoreCallingIdentity(identity);
496 }
497 }
498 }
499
500 private void dumpForUser(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700501 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800502 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700503 Cursor globalCursor = getAllGlobalSettings(ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800504 dumpSettings(globalCursor, pw);
505 pw.println();
506 }
507
508 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700509 Cursor secureCursor = getAllSecureSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800510 dumpSettings(secureCursor, pw);
511 pw.println();
512
513 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700514 Cursor systemCursor = getAllSystemSettings(userId, ALL_COLUMNS);
Svetoslavb505ccc2015-02-17 12:41:04 -0800515 dumpSettings(systemCursor, pw);
516 pw.println();
517 }
518
519 private void dumpSettings(Cursor cursor, PrintWriter pw) {
Fyodor Kupolov1f450db2015-06-11 15:25:59 -0700520 if (cursor == null || !cursor.moveToFirst()) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800521 return;
522 }
523
524 final int idColumnIdx = cursor.getColumnIndex(Settings.NameValueTable._ID);
525 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
526 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
527
528 do {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700529 pw.append("_id:").append(toDumpString(cursor.getString(idColumnIdx)));
530 pw.append(" name:").append(toDumpString(cursor.getString(nameColumnIdx)));
531 pw.append(" value:").append(toDumpString(cursor.getString(valueColumnIdx)));
Svetoslavb505ccc2015-02-17 12:41:04 -0800532 pw.println();
533 } while (cursor.moveToNext());
534 }
535
Svetoslav7e0683b2015-08-03 16:02:52 -0700536 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700537 if (s != null) {
538 return s;
539 }
540 return "{null}";
541 }
542
Svetoslav683914b2015-01-15 14:22:26 -0800543 private void registerBroadcastReceivers() {
544 IntentFilter userFilter = new IntentFilter();
545 userFilter.addAction(Intent.ACTION_USER_REMOVED);
546 userFilter.addAction(Intent.ACTION_USER_STOPPED);
547
548 getContext().registerReceiver(new BroadcastReceiver() {
549 @Override
550 public void onReceive(Context context, Intent intent) {
551 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700552 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800553
554 switch (intent.getAction()) {
555 case Intent.ACTION_USER_REMOVED: {
556 mSettingsRegistry.removeUserStateLocked(userId, true);
557 } break;
558
559 case Intent.ACTION_USER_STOPPED: {
560 mSettingsRegistry.removeUserStateLocked(userId, false);
561 } break;
562 }
563 }
564 }, userFilter);
565
566 PackageMonitor monitor = new PackageMonitor() {
567 @Override
568 public void onPackageRemoved(String packageName, int uid) {
569 synchronized (mLock) {
570 mSettingsRegistry.onPackageRemovedLocked(packageName,
571 UserHandle.getUserId(uid));
572 }
573 }
574 };
575
576 // package changes
577 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
578 UserHandle.ALL, true);
579 }
580
Svetoslav7ec28e82015-05-20 17:01:10 -0700581 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800582 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700583 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800584 }
585
Svetoslav7ec28e82015-05-20 17:01:10 -0700586 synchronized (mLock) {
587 // Get the settings.
588 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Xiaohui Chen43765b72015-08-31 10:57:33 -0700589 SettingsRegistry.SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800590
Svetoslav7ec28e82015-05-20 17:01:10 -0700591 List<String> names = settingsState.getSettingNamesLocked();
Svetoslav683914b2015-01-15 14:22:26 -0800592
Svetoslav7ec28e82015-05-20 17:01:10 -0700593 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800594
Svetoslav7ec28e82015-05-20 17:01:10 -0700595 String[] normalizedProjection = normalizeProjection(projection);
596 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800597
Svetoslav7ec28e82015-05-20 17:01:10 -0700598 // Anyone can get the global settings, so no security checks.
599 for (int i = 0; i < nameCount; i++) {
600 String name = names.get(i);
601 Setting setting = settingsState.getSettingLocked(name);
602 appendSettingToCursor(result, setting);
603 }
604
605 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800606 }
Svetoslav683914b2015-01-15 14:22:26 -0800607 }
608
Svetoslav7ec28e82015-05-20 17:01:10 -0700609 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800610 if (DEBUG) {
611 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
612 }
613
614 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700615 synchronized (mLock) {
616 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700617 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800618 }
Svetoslav683914b2015-01-15 14:22:26 -0800619 }
620
Svetoslav7ec28e82015-05-20 17:01:10 -0700621 private boolean updateGlobalSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800622 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700623 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800624 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700625 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800626 }
627
Svetoslav7ec28e82015-05-20 17:01:10 -0700628 private boolean insertGlobalSetting(String name, String value, int requestingUserId) {
629 if (DEBUG) {
630 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ")");
631 }
632 return mutateGlobalSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
633 }
634
635 private boolean deleteGlobalSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800636 if (DEBUG) {
637 Slog.v(LOG_TAG, "deleteGlobalSettingLocked(" + name + ")");
638 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700639 return mutateGlobalSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800640 }
641
Svetoslav7ec28e82015-05-20 17:01:10 -0700642 private boolean mutateGlobalSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800643 int operation) {
644 // Make sure the caller can change the settings - treated as secure.
645 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
646
Svetoslav683914b2015-01-15 14:22:26 -0800647 // Resolve the userId on whose behalf the call is made.
648 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
649
650 // If this is a setting that is currently restricted for this user, done.
651 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId)) {
652 return false;
653 }
654
655 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700656 synchronized (mLock) {
657 switch (operation) {
658 case MUTATION_OPERATION_INSERT: {
659 return mSettingsRegistry
660 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700661 UserHandle.USER_SYSTEM, name, value, getCallingPackage());
Svetoslav7ec28e82015-05-20 17:01:10 -0700662 }
Svetoslav683914b2015-01-15 14:22:26 -0800663
Svetoslav7ec28e82015-05-20 17:01:10 -0700664 case MUTATION_OPERATION_DELETE: {
665 return mSettingsRegistry.deleteSettingLocked(
666 SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700667 UserHandle.USER_SYSTEM, name);
Svetoslav7ec28e82015-05-20 17:01:10 -0700668 }
Svetoslav683914b2015-01-15 14:22:26 -0800669
Svetoslav7ec28e82015-05-20 17:01:10 -0700670 case MUTATION_OPERATION_UPDATE: {
671 return mSettingsRegistry
672 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700673 UserHandle.USER_SYSTEM, name, value, getCallingPackage());
Svetoslav7ec28e82015-05-20 17:01:10 -0700674 }
Svetoslav683914b2015-01-15 14:22:26 -0800675 }
676 }
677
678 return false;
679 }
680
Svetoslav7ec28e82015-05-20 17:01:10 -0700681 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800682 if (DEBUG) {
683 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
684 }
685
686 // Resolve the userId on whose behalf the call is made.
687 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
688
Svetoslav7ec28e82015-05-20 17:01:10 -0700689 synchronized (mLock) {
690 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
691 SettingsRegistry.SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800692
Svetoslav7ec28e82015-05-20 17:01:10 -0700693 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800694
Svetoslav7ec28e82015-05-20 17:01:10 -0700695 String[] normalizedProjection = normalizeProjection(projection);
696 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800697
Svetoslav7ec28e82015-05-20 17:01:10 -0700698 for (int i = 0; i < nameCount; i++) {
699 String name = names.get(i);
700 // Determine the owning user as some profile settings are cloned from the parent.
701 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
702 name);
Svetoslav683914b2015-01-15 14:22:26 -0800703
Svetoslav7ec28e82015-05-20 17:01:10 -0700704 // Special case for location (sigh).
705 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
706 return null;
707 }
Svetoslav683914b2015-01-15 14:22:26 -0800708
Svetoslav7ec28e82015-05-20 17:01:10 -0700709 Setting setting = mSettingsRegistry.getSettingLocked(
710 SettingsRegistry.SETTINGS_TYPE_SECURE, owningUserId, name);
711 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -0800712 }
713
Svetoslav7ec28e82015-05-20 17:01:10 -0700714 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800715 }
Svetoslav683914b2015-01-15 14:22:26 -0800716 }
717
Svetoslav7ec28e82015-05-20 17:01:10 -0700718 private Setting getSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800719 if (DEBUG) {
720 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
721 }
722
723 // Resolve the userId on whose behalf the call is made.
724 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
725
726 // Determine the owning user as some profile settings are cloned from the parent.
727 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
728
729 // Special case for location (sigh).
730 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
731 return null;
732 }
733
734 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700735 synchronized (mLock) {
736 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
737 owningUserId, name);
738 }
Svetoslav683914b2015-01-15 14:22:26 -0800739 }
740
Svetoslav7ec28e82015-05-20 17:01:10 -0700741 private boolean insertSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800742 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700743 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800744 + requestingUserId + ")");
745 }
746
Svetoslav7ec28e82015-05-20 17:01:10 -0700747 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800748 }
749
Svetoslav7ec28e82015-05-20 17:01:10 -0700750 private boolean deleteSecureSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800751 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700752 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800753 }
754
Svetoslav7ec28e82015-05-20 17:01:10 -0700755 return mutateSecureSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800756 }
757
Svetoslav7ec28e82015-05-20 17:01:10 -0700758 private boolean updateSecureSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800759 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700760 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800761 + requestingUserId + ")");
762 }
763
Svetoslav7ec28e82015-05-20 17:01:10 -0700764 return mutateSecureSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800765 }
766
Svetoslav7ec28e82015-05-20 17:01:10 -0700767 private boolean mutateSecureSetting(String name, String value, int requestingUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800768 int operation) {
769 // Make sure the caller can change the settings.
770 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
771
Svetoslav683914b2015-01-15 14:22:26 -0800772 // Resolve the userId on whose behalf the call is made.
773 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
774
775 // If this is a setting that is currently restricted for this user, done.
776 if (isGlobalOrSecureSettingRestrictedForUser(name, callingUserId)) {
777 return false;
778 }
779
780 // Determine the owning user as some profile settings are cloned from the parent.
781 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
782
783 // Only the owning user can change the setting.
784 if (owningUserId != callingUserId) {
785 return false;
786 }
787
788 // Special cases for location providers (sigh).
789 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslavb596a2c2015-02-17 21:37:09 -0800790 return updateLocationProvidersAllowedLocked(value, owningUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800791 }
792
793 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700794 synchronized (mLock) {
795 switch (operation) {
796 case MUTATION_OPERATION_INSERT: {
797 return mSettingsRegistry
798 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
799 owningUserId, name, value, getCallingPackage());
800 }
Svetoslav683914b2015-01-15 14:22:26 -0800801
Svetoslav7ec28e82015-05-20 17:01:10 -0700802 case MUTATION_OPERATION_DELETE: {
803 return mSettingsRegistry.deleteSettingLocked(
804 SettingsRegistry.SETTINGS_TYPE_SECURE,
805 owningUserId, name);
806 }
Svetoslav683914b2015-01-15 14:22:26 -0800807
Svetoslav7ec28e82015-05-20 17:01:10 -0700808 case MUTATION_OPERATION_UPDATE: {
809 return mSettingsRegistry
810 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
811 owningUserId, name, value, getCallingPackage());
812 }
Svetoslav683914b2015-01-15 14:22:26 -0800813 }
814 }
815
816 return false;
817 }
818
Svetoslav7ec28e82015-05-20 17:01:10 -0700819 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800820 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700821 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800822 }
823
824 // Resolve the userId on whose behalf the call is made.
825 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
826
Svetoslav7ec28e82015-05-20 17:01:10 -0700827 synchronized (mLock) {
828 List<String> names = mSettingsRegistry.getSettingsNamesLocked(
829 SettingsRegistry.SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -0800830
Svetoslav7ec28e82015-05-20 17:01:10 -0700831 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800832
Svetoslav7ec28e82015-05-20 17:01:10 -0700833 String[] normalizedProjection = normalizeProjection(projection);
834 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800835
Svetoslav7ec28e82015-05-20 17:01:10 -0700836 for (int i = 0; i < nameCount; i++) {
837 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -0800838
Svetoslav7ec28e82015-05-20 17:01:10 -0700839 // Determine the owning user as some profile settings are cloned from the parent.
840 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
841 name);
Svetoslav683914b2015-01-15 14:22:26 -0800842
Svetoslav7ec28e82015-05-20 17:01:10 -0700843 Setting setting = mSettingsRegistry.getSettingLocked(
844 SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name);
845 appendSettingToCursor(result, setting);
846 }
847
848 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800849 }
Svetoslav683914b2015-01-15 14:22:26 -0800850 }
851
Svetoslav7ec28e82015-05-20 17:01:10 -0700852 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800853 if (DEBUG) {
854 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
855 }
856
857 // Resolve the userId on whose behalf the call is made.
858 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
859
860 // Determine the owning user as some profile settings are cloned from the parent.
861 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
862
863 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700864 synchronized (mLock) {
865 return mSettingsRegistry.getSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
866 owningUserId, name);
867 }
Svetoslav683914b2015-01-15 14:22:26 -0800868 }
869
Svetoslav7ec28e82015-05-20 17:01:10 -0700870 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800871 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800873 + requestingUserId + ")");
874 }
875
Svetoslav7ec28e82015-05-20 17:01:10 -0700876 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -0800877 }
878
Svetoslav7ec28e82015-05-20 17:01:10 -0700879 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800880 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700881 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800882 }
883
Svetoslav7ec28e82015-05-20 17:01:10 -0700884 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -0800885 }
886
Svetoslav7ec28e82015-05-20 17:01:10 -0700887 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -0800888 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700889 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -0800890 + requestingUserId + ")");
891 }
892
Svetoslav7ec28e82015-05-20 17:01:10 -0700893 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -0800894 }
895
Svetoslav7ec28e82015-05-20 17:01:10 -0700896 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -0800897 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +0100898 if (!hasWriteSecureSettingsPermission()) {
899 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
900 // operation is allowed for the calling package through appops.
901 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
902 Binder.getCallingUid(), getCallingPackage(), true)) {
903 return false;
904 }
Svetoslav683914b2015-01-15 14:22:26 -0800905 }
906
Svetoslav683914b2015-01-15 14:22:26 -0800907 // Resolve the userId on whose behalf the call is made.
908 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
909
Svetoslavd8d25e02015-11-20 13:09:26 -0800910 // Enforce what the calling package can mutate the system settings.
911 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
912
Svetoslav683914b2015-01-15 14:22:26 -0800913 // Determine the owning user as some profile settings are cloned from the parent.
914 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
915
916 // Only the owning user id can change the setting.
917 if (owningUserId != callingUserId) {
918 return false;
919 }
920
921 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700922 synchronized (mLock) {
923 switch (operation) {
924 case MUTATION_OPERATION_INSERT: {
925 validateSystemSettingValue(name, value);
926 return mSettingsRegistry
927 .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
928 owningUserId, name, value, getCallingPackage());
929 }
930
931 case MUTATION_OPERATION_DELETE: {
932 return mSettingsRegistry.deleteSettingLocked(
933 SettingsRegistry.SETTINGS_TYPE_SYSTEM,
934 owningUserId, name);
935 }
936
937 case MUTATION_OPERATION_UPDATE: {
938 validateSystemSettingValue(name, value);
939 return mSettingsRegistry
940 .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM,
941 owningUserId, name, value, getCallingPackage());
942 }
Svetoslav683914b2015-01-15 14:22:26 -0800943 }
944
Svetoslav7ec28e82015-05-20 17:01:10 -0700945 return false;
Svetoslav683914b2015-01-15 14:22:26 -0800946 }
Svetoslav683914b2015-01-15 14:22:26 -0800947 }
948
Billy Lau6ad2d662015-07-18 00:26:58 +0100949 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -0700950 // Write secure settings is a more protected permission. If caller has it we are good.
951 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
952 == PackageManager.PERMISSION_GRANTED) {
953 return true;
954 }
955
Svetoslavf41334b2015-06-23 12:06:03 -0700956 return false;
957 }
958
Svetoslav683914b2015-01-15 14:22:26 -0800959 private void validateSystemSettingValue(String name, String value) {
960 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
961 if (validator != null && !validator.validate(value)) {
962 throw new IllegalArgumentException("Invalid value: " + value
963 + " for setting: " + name);
964 }
965 }
966
967 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
968 int owningUserId) {
969 // Optimization - location providers are restricted only for managed profiles.
970 if (callingUserId == owningUserId) {
971 return false;
972 }
973 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
974 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
975 new UserHandle(callingUserId))) {
976 return true;
977 }
978 return false;
979 }
980
981 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId) {
982 String restriction = sSettingToUserRestrictionMap.get(setting);
983 if (restriction == null) {
984 return false;
985 }
986 return mUserManager.hasUserRestriction(restriction, new UserHandle(userId));
987 }
988
989 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
990 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
991 }
992
993 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
994 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
995 }
996
997 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
998 final int parentId = getGroupParentLocked(userId);
999 if (parentId != userId && keys.contains(name)) {
1000 return parentId;
1001 }
1002 return userId;
1003 }
1004
Svetoslavf41334b2015-06-23 12:06:03 -07001005 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001006 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001007 // System/root/shell can mutate whatever secure settings they want.
1008 final int callingUid = Binder.getCallingUid();
1009 if (callingUid == android.os.Process.SYSTEM_UID
1010 || callingUid == Process.SHELL_UID
1011 || callingUid == Process.ROOT_UID) {
1012 return;
1013 }
1014
1015 switch (operation) {
1016 case MUTATION_OPERATION_INSERT:
1017 // Insert updates.
1018 case MUTATION_OPERATION_UPDATE: {
1019 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1020 return;
1021 }
1022
1023 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001024 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001025
1026 // Privileged apps can do whatever they want.
1027 if ((packageInfo.applicationInfo.privateFlags
1028 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1029 return;
1030 }
1031
1032 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1033 packageInfo.applicationInfo.targetSdkVersion, name);
1034 } break;
1035
1036 case MUTATION_OPERATION_DELETE: {
1037 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1038 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1039 throw new IllegalArgumentException("You cannot delete system defined"
1040 + " secure settings.");
1041 }
1042
1043 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001044 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001045
1046 // Privileged apps can do whatever they want.
1047 if ((packageInfo.applicationInfo.privateFlags &
1048 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1049 return;
1050 }
1051
1052 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1053 packageInfo.applicationInfo.targetSdkVersion, name);
1054 } break;
1055 }
1056 }
1057
Xiaohui Chen43765b72015-08-31 10:57:33 -07001058 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001059 try {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001060 return mPackageManager.getPackageInfo(getCallingPackage(), 0, userId);
1061 } catch (RemoteException e) {
Svetoslav683914b2015-01-15 14:22:26 -08001062 throw new IllegalStateException("Calling package doesn't exist");
1063 }
1064 }
1065
1066 private int getGroupParentLocked(int userId) {
1067 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001068 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001069 return userId;
1070 }
1071 // We are in the same process with the user manager and the returned
1072 // user info is a cached instance, so just look up instead of cache.
1073 final long identity = Binder.clearCallingIdentity();
1074 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001075 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001076 UserInfo userInfo = mUserManager.getProfileParent(userId);
1077 return (userInfo != null) ? userInfo.id : userId;
1078 } finally {
1079 Binder.restoreCallingIdentity(identity);
1080 }
1081 }
1082
Svetoslav683914b2015-01-15 14:22:26 -08001083 private void enforceWritePermission(String permission) {
1084 if (getContext().checkCallingOrSelfPermission(permission)
1085 != PackageManager.PERMISSION_GRANTED) {
1086 throw new SecurityException("Permission denial: writing to settings requires:"
1087 + permission);
1088 }
1089 }
1090
1091 /*
1092 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1093 * This setting contains a list of the currently enabled location providers.
1094 * But helper functions in android.providers.Settings can enable or disable
1095 * a single provider by using a "+" or "-" prefix before the provider name.
1096 *
1097 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001098 */
Svetoslavb596a2c2015-02-17 21:37:09 -08001099 private boolean updateLocationProvidersAllowedLocked(String value, int owningUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001100 if (TextUtils.isEmpty(value)) {
1101 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001102 }
1103
Svetoslav683914b2015-01-15 14:22:26 -08001104 final char prefix = value.charAt(0);
1105 if (prefix != '+' && prefix != '-') {
1106 return false;
1107 }
1108
1109 // skip prefix
1110 value = value.substring(1);
1111
Svetoslav7ec28e82015-05-20 17:01:10 -07001112 Setting settingValue = getSecureSetting(
Svetoslav683914b2015-01-15 14:22:26 -08001113 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1114
1115 String oldProviders = (settingValue != null) ? settingValue.getValue() : "";
1116
1117 int index = oldProviders.indexOf(value);
1118 int end = index + value.length();
1119
1120 // check for commas to avoid matching on partial string
1121 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1122 index = -1;
1123 }
1124
1125 // check for commas to avoid matching on partial string
1126 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1127 index = -1;
1128 }
1129
1130 String newProviders;
1131
1132 if (prefix == '+' && index < 0) {
1133 // append the provider to the list if not present
1134 if (oldProviders.length() == 0) {
1135 newProviders = value;
1136 } else {
1137 newProviders = oldProviders + ',' + value;
1138 }
1139 } else if (prefix == '-' && index >= 0) {
1140 // remove the provider from the list if present
1141 // remove leading or trailing comma
1142 if (index > 0) {
1143 index--;
1144 } else if (end < oldProviders.length()) {
1145 end++;
1146 }
1147
1148 newProviders = oldProviders.substring(0, index);
1149 if (end < oldProviders.length()) {
1150 newProviders += oldProviders.substring(end);
1151 }
1152 } else {
1153 // nothing changed, so no need to update the database
1154 return false;
1155 }
1156
Svetoslavb596a2c2015-02-17 21:37:09 -08001157 return mSettingsRegistry.insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SECURE,
1158 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
1159 getCallingPackage());
Svetoslav683914b2015-01-15 14:22:26 -08001160 }
1161
Svetoslav683914b2015-01-15 14:22:26 -08001162 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1163 int targetSdkVersion, String name) {
1164 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1165 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1166 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1167 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1168 + " This will soon become an error.");
1169 } else {
1170 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1171 + " This will soon become an error.");
1172 }
1173 } else {
1174 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1175 throw new IllegalArgumentException("You cannot change private secure settings.");
1176 } else {
1177 throw new IllegalArgumentException("You cannot keep your settings in"
1178 + " the secure settings.");
1179 }
1180 }
1181 }
1182
1183 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1184 if (requestingUserId == UserHandle.getCallingUserId()) {
1185 return requestingUserId;
1186 }
1187 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1188 Binder.getCallingUid(), requestingUserId, false, true,
1189 "get/set setting for user", null);
1190 }
1191
1192 private static Bundle packageValueForCallResult(Setting setting) {
1193 if (setting == null) {
1194 return NULL_SETTING;
1195 }
1196 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
1197 }
1198
1199 private static int getRequestingUserId(Bundle args) {
1200 final int callingUserId = UserHandle.getCallingUserId();
1201 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1202 : callingUserId;
1203 }
1204
1205 private static String getSettingValue(Bundle args) {
1206 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1207 }
1208
1209 private static String getValidTableOrThrow(Uri uri) {
1210 if (uri.getPathSegments().size() > 0) {
1211 String table = uri.getPathSegments().get(0);
1212 if (DatabaseHelper.isValidTable(table)) {
1213 return table;
1214 }
1215 throw new IllegalArgumentException("Bad root path: " + table);
1216 }
1217 throw new IllegalArgumentException("Invalid URI:" + uri);
1218 }
1219
1220 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
1221 if (setting == null) {
1222 return new MatrixCursor(projection, 0);
1223 }
1224 MatrixCursor cursor = new MatrixCursor(projection, 1);
1225 appendSettingToCursor(cursor, setting);
1226 return cursor;
1227 }
1228
1229 private static String[] normalizeProjection(String[] projection) {
1230 if (projection == null) {
1231 return ALL_COLUMNS;
1232 }
1233
1234 final int columnCount = projection.length;
1235 for (int i = 0; i < columnCount; i++) {
1236 String column = projection[i];
1237 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
1238 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001239 }
1240 }
1241
Svetoslav683914b2015-01-15 14:22:26 -08001242 return projection;
1243 }
1244
1245 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
1246 final int columnCount = cursor.getColumnCount();
1247
1248 String[] values = new String[columnCount];
1249
1250 for (int i = 0; i < columnCount; i++) {
1251 String column = cursor.getColumnName(i);
1252
1253 switch (column) {
1254 case Settings.NameValueTable._ID: {
1255 values[i] = setting.getId();
1256 } break;
1257
1258 case Settings.NameValueTable.NAME: {
1259 values[i] = setting.getName();
1260 } break;
1261
1262 case Settings.NameValueTable.VALUE: {
1263 values[i] = setting.getValue();
1264 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001265 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001266 }
1267
Svetoslav683914b2015-01-15 14:22:26 -08001268 cursor.addRow(values);
1269 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001270
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001271 private static boolean isKeyValid(String key) {
1272 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
1273 }
1274
Svetoslav683914b2015-01-15 14:22:26 -08001275 private static final class Arguments {
1276 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
1277 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
1278
1279 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
1280 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
1281
1282 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
1283 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
1284
1285 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
1286 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
1287
1288 public final String table;
1289 public final String name;
1290
1291 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
1292 final int segmentSize = uri.getPathSegments().size();
1293 switch (segmentSize) {
1294 case 1: {
1295 if (where != null
1296 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
1297 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
1298 && whereArgs.length == 1) {
1299 name = whereArgs[0];
1300 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001301 return;
Svetoslav683914b2015-01-15 14:22:26 -08001302 } else if (where != null
1303 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
1304 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
1305 final int startIndex = Math.max(where.indexOf("'"),
1306 where.indexOf("\"")) + 1;
1307 final int endIndex = Math.max(where.lastIndexOf("'"),
1308 where.lastIndexOf("\""));
1309 name = where.substring(startIndex, endIndex);
1310 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08001311 return;
Svetoslav683914b2015-01-15 14:22:26 -08001312 } else if (supportAll && where == null && whereArgs == null) {
1313 name = null;
1314 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08001315 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001316 }
Svetoslav683914b2015-01-15 14:22:26 -08001317 } break;
1318
Svetoslav28494652015-02-12 14:11:42 -08001319 case 2: {
1320 if (where == null && whereArgs == null) {
1321 name = uri.getPathSegments().get(1);
1322 table = computeTableForSetting(uri, name);
1323 return;
1324 }
1325 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001326 }
Svetoslav28494652015-02-12 14:11:42 -08001327
1328 EventLogTags.writeUnsupportedSettingsQuery(
1329 uri.toSafeString(), where, Arrays.toString(whereArgs));
1330 String message = String.format( "Supported SQL:\n"
1331 + " uri content://some_table/some_property with null where and where args\n"
1332 + " uri content://some_table with query name=? and single name as arg\n"
1333 + " uri content://some_table with query name=some_name and null args\n"
1334 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
1335 Arrays.toString(whereArgs));
1336 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001337 }
1338
Svetoslav28494652015-02-12 14:11:42 -08001339 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001340 String table = getValidTableOrThrow(uri);
1341
1342 if (name != null) {
1343 if (sSystemMovedToSecureSettings.contains(name)) {
1344 table = TABLE_SECURE;
1345 }
1346
1347 if (sSystemMovedToGlobalSettings.contains(name)) {
1348 table = TABLE_GLOBAL;
1349 }
1350
1351 if (sSecureMovedToGlobalSettings.contains(name)) {
1352 table = TABLE_GLOBAL;
1353 }
1354
1355 if (sGlobalMovedToSecureSettings.contains(name)) {
1356 table = TABLE_SECURE;
1357 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001358 }
Svetoslav683914b2015-01-15 14:22:26 -08001359
1360 return table;
1361 }
1362 }
1363
1364 final class SettingsRegistry {
1365 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
1366
1367 private static final int SETTINGS_TYPE_GLOBAL = 0;
1368 private static final int SETTINGS_TYPE_SYSTEM = 1;
1369 private static final int SETTINGS_TYPE_SECURE = 2;
1370
1371 private static final int SETTINGS_TYPE_MASK = 0xF0000000;
1372 private static final int SETTINGS_TYPE_SHIFT = 28;
1373
1374 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
1375 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
1376 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
1377
1378 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
1379
1380 private final BackupManager mBackupManager;
1381
Svetoslav7e0683b2015-08-03 16:02:52 -07001382 private final Handler mHandler;
1383
Svetoslav683914b2015-01-15 14:22:26 -08001384 public SettingsRegistry() {
1385 mBackupManager = new BackupManager(getContext());
Svetoslav7e0683b2015-08-03 16:02:52 -07001386 mHandler = new MyHandler(getContext().getMainLooper());
Svetoslav683914b2015-01-15 14:22:26 -08001387 migrateAllLegacySettingsIfNeeded();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001388 }
1389
Svetoslav683914b2015-01-15 14:22:26 -08001390 public List<String> getSettingsNamesLocked(int type, int userId) {
1391 final int key = makeKey(type, userId);
1392 SettingsState settingsState = peekSettingsStateLocked(key);
1393 return settingsState.getSettingNamesLocked();
1394 }
1395
1396 public SettingsState getSettingsLocked(int type, int userId) {
1397 final int key = makeKey(type, userId);
1398 return peekSettingsStateLocked(key);
1399 }
1400
1401 public void ensureSettingsForUserLocked(int userId) {
1402 // Migrate the setting for this user if needed.
1403 migrateLegacySettingsForUserIfNeededLocked(userId);
1404
1405 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001406 if (userId == UserHandle.USER_SYSTEM) {
1407 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001408 ensureSettingsStateLocked(globalKey);
1409 }
1410
1411 // Ensure secure settings loaded.
1412 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1413 ensureSettingsStateLocked(secureKey);
1414
1415 // Make sure the secure settings have an Android id set.
1416 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1417 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1418
1419 // Ensure system settings loaded.
1420 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1421 ensureSettingsStateLocked(systemKey);
1422
1423 // Upgrade the settings to the latest version.
1424 UpgradeController upgrader = new UpgradeController(userId);
1425 upgrader.upgradeIfNeededLocked();
1426 }
1427
1428 private void ensureSettingsStateLocked(int key) {
1429 if (mSettingsStates.get(key) == null) {
1430 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
1431 SettingsState settingsState = new SettingsState(mLock, getSettingsFile(key), key,
1432 maxBytesPerPackage);
1433 mSettingsStates.put(key, settingsState);
1434 }
1435 }
1436
1437 public void removeUserStateLocked(int userId, boolean permanently) {
1438 // We always keep the global settings in memory.
1439
1440 // Nuke system settings.
1441 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1442 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
1443 if (systemSettingsState != null) {
1444 if (permanently) {
1445 mSettingsStates.remove(systemKey);
1446 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001447 } else {
Svetoslav683914b2015-01-15 14:22:26 -08001448 systemSettingsState.destroyLocked(new Runnable() {
1449 @Override
1450 public void run() {
1451 mSettingsStates.remove(systemKey);
1452 }
1453 });
1454 }
1455 }
1456
1457 // Nuke secure settings.
1458 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1459 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
1460 if (secureSettingsState != null) {
1461 if (permanently) {
1462 mSettingsStates.remove(secureKey);
1463 secureSettingsState.destroyLocked(null);
1464 } else {
1465 secureSettingsState.destroyLocked(new Runnable() {
1466 @Override
1467 public void run() {
1468 mSettingsStates.remove(secureKey);
1469 }
1470 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001471 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001472 }
1473 }
1474
Svetoslav683914b2015-01-15 14:22:26 -08001475 public boolean insertSettingLocked(int type, int userId, String name, String value,
1476 String packageName) {
1477 final int key = makeKey(type, userId);
1478
1479 SettingsState settingsState = peekSettingsStateLocked(key);
1480 final boolean success = settingsState.insertSettingLocked(name, value, packageName);
1481
1482 if (success) {
1483 notifyForSettingsChange(key, name);
1484 }
1485 return success;
1486 }
1487
1488 public boolean deleteSettingLocked(int type, int userId, String name) {
1489 final int key = makeKey(type, userId);
1490
1491 SettingsState settingsState = peekSettingsStateLocked(key);
1492 final boolean success = settingsState.deleteSettingLocked(name);
1493
1494 if (success) {
1495 notifyForSettingsChange(key, name);
1496 }
1497 return success;
1498 }
1499
1500 public Setting getSettingLocked(int type, int userId, String name) {
1501 final int key = makeKey(type, userId);
1502
1503 SettingsState settingsState = peekSettingsStateLocked(key);
1504 return settingsState.getSettingLocked(name);
1505 }
1506
1507 public boolean updateSettingLocked(int type, int userId, String name, String value,
1508 String packageName) {
1509 final int key = makeKey(type, userId);
1510
1511 SettingsState settingsState = peekSettingsStateLocked(key);
1512 final boolean success = settingsState.updateSettingLocked(name, value, packageName);
1513
1514 if (success) {
1515 notifyForSettingsChange(key, name);
1516 }
1517
1518 return success;
1519 }
1520
1521 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07001522 // Global and secure settings are signature protected. Apps signed
1523 // by the platform certificate are generally not uninstalled and
1524 // the main exception is tests. We trust components signed
1525 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08001526
1527 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1528 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07001529 if (systemSettings != null) {
1530 systemSettings.onPackageRemovedLocked(packageName);
1531 }
Svetoslav683914b2015-01-15 14:22:26 -08001532 }
1533
1534 private SettingsState peekSettingsStateLocked(int key) {
1535 SettingsState settingsState = mSettingsStates.get(key);
1536 if (settingsState != null) {
1537 return settingsState;
1538 }
1539
1540 ensureSettingsForUserLocked(getUserIdFromKey(key));
1541 return mSettingsStates.get(key);
1542 }
1543
1544 private void migrateAllLegacySettingsIfNeeded() {
1545 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001546 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001547 File globalFile = getSettingsFile(key);
1548 if (globalFile.exists()) {
1549 return;
1550 }
1551
1552 final long identity = Binder.clearCallingIdentity();
1553 try {
1554 List<UserInfo> users = mUserManager.getUsers(true);
1555
1556 final int userCount = users.size();
1557 for (int i = 0; i < userCount; i++) {
1558 final int userId = users.get(i).id;
1559
1560 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1561 SQLiteDatabase database = dbHelper.getWritableDatabase();
1562 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1563
1564 // Upgrade to the latest version.
1565 UpgradeController upgrader = new UpgradeController(userId);
1566 upgrader.upgradeIfNeededLocked();
1567
1568 // Drop from memory if not a running user.
1569 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
1570 removeUserStateLocked(userId, false);
1571 }
1572 }
1573 } finally {
1574 Binder.restoreCallingIdentity(identity);
1575 }
1576 }
1577 }
1578
1579 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
1580 // Every user has secure settings and if no file we need to migrate.
1581 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1582 File secureFile = getSettingsFile(secureKey);
1583 if (secureFile.exists()) {
1584 return;
1585 }
1586
1587 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
1588 SQLiteDatabase database = dbHelper.getWritableDatabase();
1589
1590 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
1591 }
1592
1593 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
1594 SQLiteDatabase database, int userId) {
1595 // Move over the global settings if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001596 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001597 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
1598 ensureSettingsStateLocked(globalKey);
1599 SettingsState globalSettings = mSettingsStates.get(globalKey);
1600 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
1601 globalSettings.persistSyncLocked();
1602 }
1603
1604 // Move over the secure settings.
1605 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
1606 ensureSettingsStateLocked(secureKey);
1607 SettingsState secureSettings = mSettingsStates.get(secureKey);
1608 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
1609 ensureSecureSettingAndroidIdSetLocked(secureSettings);
1610 secureSettings.persistSyncLocked();
1611
1612 // Move over the system settings.
1613 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
1614 ensureSettingsStateLocked(systemKey);
1615 SettingsState systemSettings = mSettingsStates.get(systemKey);
1616 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
1617 systemSettings.persistSyncLocked();
1618
1619 // Drop the database as now all is moved and persisted.
1620 if (DROP_DATABASE_ON_MIGRATION) {
1621 dbHelper.dropDatabase();
1622 } else {
1623 dbHelper.backupDatabase();
1624 }
1625 }
1626
1627 private void migrateLegacySettingsLocked(SettingsState settingsState,
1628 SQLiteDatabase database, String table) {
1629 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
1630 queryBuilder.setTables(table);
1631
1632 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
1633 null, null, null, null, null);
1634
1635 if (cursor == null) {
1636 return;
1637 }
1638
1639 try {
1640 if (!cursor.moveToFirst()) {
1641 return;
1642 }
1643
1644 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
1645 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
1646
1647 settingsState.setVersionLocked(database.getVersion());
1648
1649 while (!cursor.isAfterLast()) {
1650 String name = cursor.getString(nameColumnIdx);
1651 String value = cursor.getString(valueColumnIdx);
1652 settingsState.insertSettingLocked(name, value,
1653 SettingsState.SYSTEM_PACKAGE_NAME);
1654 cursor.moveToNext();
1655 }
1656 } finally {
1657 cursor.close();
1658 }
1659 }
1660
1661 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
1662 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
1663
1664 if (value != null) {
1665 return;
1666 }
1667
1668 final int userId = getUserIdFromKey(secureSettings.mKey);
1669
1670 final UserInfo user;
1671 final long identity = Binder.clearCallingIdentity();
1672 try {
1673 user = mUserManager.getUserInfo(userId);
1674 } finally {
1675 Binder.restoreCallingIdentity(identity);
1676 }
1677 if (user == null) {
1678 // Can happen due to races when deleting users - treat as benign.
1679 return;
1680 }
1681
1682 String androidId = Long.toHexString(new SecureRandom().nextLong());
1683 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
1684 SettingsState.SYSTEM_PACKAGE_NAME);
1685
1686 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
1687 + "] for user " + userId);
1688
1689 // Write a drop box entry if it's a restricted profile
1690 if (user.isRestricted()) {
1691 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
1692 Context.DROPBOX_SERVICE);
1693 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
1694 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
1695 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
1696 }
1697 }
1698 }
1699
1700 private void notifyForSettingsChange(int key, String name) {
1701 // Update the system property *first*, so if someone is listening for
1702 // a notification and then using the contract class to get their data,
1703 // the system property will be updated and they'll get the new data.
1704
1705 boolean backedUpDataChanged = false;
1706 String property = null;
1707 if (isGlobalSettingsKey(key)) {
1708 property = Settings.Global.SYS_PROP_SETTING_VERSION;
1709 backedUpDataChanged = true;
1710 } else if (isSecureSettingsKey(key)) {
1711 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
1712 backedUpDataChanged = true;
1713 } else if (isSystemSettingsKey(key)) {
1714 property = Settings.System.SYS_PROP_SETTING_VERSION;
1715 backedUpDataChanged = true;
1716 }
1717
1718 if (property != null) {
1719 final long version = SystemProperties.getLong(property, 0) + 1;
1720 SystemProperties.set(property, Long.toString(version));
1721 if (DEBUG) {
1722 Slog.v(LOG_TAG, "System property " + property + "=" + version);
1723 }
1724 }
1725
1726 // Inform the backup manager about a data change
1727 if (backedUpDataChanged) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001728 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Svetoslav683914b2015-01-15 14:22:26 -08001729 }
1730
1731 // Now send the notification through the content framework.
1732
1733 final int userId = getUserIdFromKey(key);
1734 Uri uri = getNotificationUriFor(key, name);
1735
Svetoslav7e0683b2015-08-03 16:02:52 -07001736 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1737 userId, 0, uri).sendToTarget();
1738
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001739 if (isSecureSettingsKey(key)) {
1740 maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
1741 } else if (isSystemSettingsKey(key)) {
1742 maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
1743 }
1744 }
1745
1746 private void maybeNotifyProfiles(int userId, Uri uri, String name,
1747 Set<String> keysCloned) {
1748 if (keysCloned.contains(name)) {
1749 List<UserInfo> profiles = mUserManager.getProfiles(userId);
1750 int size = profiles.size();
1751 for (int i = 0; i < size; i++) {
1752 UserInfo profile = profiles.get(i);
1753 // the notification for userId has already been sent.
1754 if (profile.id != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07001755 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
1756 profile.id, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01001757 }
1758 }
1759 }
Svetoslav683914b2015-01-15 14:22:26 -08001760 }
1761
1762 private int makeKey(int type, int userId) {
1763 return (type << SETTINGS_TYPE_SHIFT) | userId;
1764 }
1765
1766 private int getTypeFromKey(int key) {
1767 return key >> SETTINGS_TYPE_SHIFT;
1768 }
1769
1770 private int getUserIdFromKey(int key) {
1771 return key & ~SETTINGS_TYPE_MASK;
1772 }
1773
1774 private boolean isGlobalSettingsKey(int key) {
1775 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
1776 }
1777
1778 private boolean isSystemSettingsKey(int key) {
1779 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
1780 }
1781
1782 private boolean isSecureSettingsKey(int key) {
1783 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
1784 }
1785
1786 private File getSettingsFile(int key) {
1787 if (isGlobalSettingsKey(key)) {
1788 final int userId = getUserIdFromKey(key);
1789 return new File(Environment.getUserSystemDirectory(userId),
1790 SETTINGS_FILE_GLOBAL);
1791 } else if (isSystemSettingsKey(key)) {
1792 final int userId = getUserIdFromKey(key);
1793 return new File(Environment.getUserSystemDirectory(userId),
1794 SETTINGS_FILE_SYSTEM);
1795 } else if (isSecureSettingsKey(key)) {
1796 final int userId = getUserIdFromKey(key);
1797 return new File(Environment.getUserSystemDirectory(userId),
1798 SETTINGS_FILE_SECURE);
1799 } else {
1800 throw new IllegalArgumentException("Invalid settings key:" + key);
1801 }
1802 }
1803
1804 private Uri getNotificationUriFor(int key, String name) {
1805 if (isGlobalSettingsKey(key)) {
1806 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
1807 : Settings.Global.CONTENT_URI;
1808 } else if (isSecureSettingsKey(key)) {
1809 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
1810 : Settings.Secure.CONTENT_URI;
1811 } else if (isSystemSettingsKey(key)) {
1812 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
1813 : Settings.System.CONTENT_URI;
1814 } else {
1815 throw new IllegalArgumentException("Invalid settings key:" + key);
1816 }
1817 }
1818
1819 private int getMaxBytesPerPackageForType(int type) {
1820 switch (type) {
1821 case SETTINGS_TYPE_GLOBAL:
1822 case SETTINGS_TYPE_SECURE: {
1823 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
1824 }
1825
1826 default: {
1827 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
1828 }
1829 }
1830 }
1831
Svetoslav7e0683b2015-08-03 16:02:52 -07001832 private final class MyHandler extends Handler {
1833 private static final int MSG_NOTIFY_URI_CHANGED = 1;
1834 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
1835
1836 public MyHandler(Looper looper) {
1837 super(looper);
1838 }
1839
1840 @Override
1841 public void handleMessage(Message msg) {
1842 switch (msg.what) {
1843 case MSG_NOTIFY_URI_CHANGED: {
1844 final int userId = msg.arg1;
1845 Uri uri = (Uri) msg.obj;
1846 getContext().getContentResolver().notifyChange(uri, null, true, userId);
1847 if (DEBUG) {
1848 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
1849 }
1850 } break;
1851
1852 case MSG_NOTIFY_DATA_CHANGED: {
1853 mBackupManager.dataChanged();
1854 } break;
1855 }
1856 }
1857 }
1858
Svetoslav683914b2015-01-15 14:22:26 -08001859 private final class UpgradeController {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02001860 private static final int SETTINGS_VERSION = 122;
Svetoslav683914b2015-01-15 14:22:26 -08001861
1862 private final int mUserId;
1863
1864 public UpgradeController(int userId) {
1865 mUserId = userId;
1866 }
1867
1868 public void upgradeIfNeededLocked() {
1869 // The version of all settings for a user is the same (all users have secure).
1870 SettingsState secureSettings = getSettingsLocked(
1871 SettingsRegistry.SETTINGS_TYPE_SECURE, mUserId);
1872
1873 // Try an update from the current state.
1874 final int oldVersion = secureSettings.getVersionLocked();
1875 final int newVersion = SETTINGS_VERSION;
1876
Svet Ganovc9755bc2015-03-28 13:21:22 -07001877 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08001878 if (oldVersion == newVersion) {
1879 return;
1880 }
1881
1882 // Try to upgrade.
1883 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
1884
1885 // If upgrade failed start from scratch and upgrade.
1886 if (curVersion != newVersion) {
1887 // Drop state we have for this user.
1888 removeUserStateLocked(mUserId, true);
1889
1890 // Recreate the database.
1891 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
1892 SQLiteDatabase database = dbHelper.getWritableDatabase();
1893 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
1894
1895 // Migrate the settings for this user.
1896 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
1897
1898 // Now upgrade should work fine.
1899 onUpgradeLocked(mUserId, oldVersion, newVersion);
1900 }
1901
1902 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001903 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001904 SettingsState globalSettings = getSettingsLocked(
1905 SettingsRegistry.SETTINGS_TYPE_GLOBAL, mUserId);
1906 globalSettings.setVersionLocked(newVersion);
1907 }
1908
1909 // Set the secure settings version.
1910 secureSettings.setVersionLocked(newVersion);
1911
1912 // Set the system settings version.
1913 SettingsState systemSettings = getSettingsLocked(
1914 SettingsRegistry.SETTINGS_TYPE_SYSTEM, mUserId);
1915 systemSettings.setVersionLocked(newVersion);
1916 }
1917
1918 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001919 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001920 }
1921
1922 private SettingsState getSecureSettingsLocked(int userId) {
1923 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
1924 }
1925
1926 private SettingsState getSystemSettingsLocked(int userId) {
1927 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
1928 }
1929
Jeff Brown503cffc2015-03-26 18:08:51 -07001930 /**
1931 * You must perform all necessary mutations to bring the settings
1932 * for this user from the old to the new version. When you add a new
1933 * upgrade step you *must* update SETTINGS_VERSION.
1934 *
1935 * This is an example of moving a setting from secure to global.
1936 *
1937 * // v119: Example settings changes.
1938 * if (currentVersion == 118) {
1939 * if (userId == UserHandle.USER_OWNER) {
1940 * // Remove from the secure settings.
1941 * SettingsState secureSettings = getSecureSettingsLocked(userId);
1942 * String name = "example_setting_to_move";
1943 * String value = secureSettings.getSetting(name);
1944 * secureSettings.deleteSetting(name);
1945 *
1946 * // Add to the global settings.
1947 * SettingsState globalSettings = getGlobalSettingsLocked();
1948 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
1949 * }
1950 *
1951 * // Update the current version.
1952 * currentVersion = 119;
1953 * }
1954 */
Svetoslav683914b2015-01-15 14:22:26 -08001955 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
1956 if (DEBUG) {
1957 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
1958 + oldVersion + " to version: " + newVersion);
1959 }
1960
Jeff Brown503cffc2015-03-26 18:08:51 -07001961 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08001962
John Spurlocke11ae112015-05-11 16:09:03 -04001963 // v119: Reset zen + ringer mode.
1964 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07001965 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04001966 final SettingsState globalSettings = getGlobalSettingsLocked();
1967 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
1968 Integer.toString(Settings.Global.ZEN_MODE_OFF),
1969 SettingsState.SYSTEM_PACKAGE_NAME);
1970 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
1971 Integer.toString(AudioManager.RINGER_MODE_NORMAL),
1972 SettingsState.SYSTEM_PACKAGE_NAME);
1973 }
1974 currentVersion = 119;
1975 }
1976
Jason Monk27bbb2d2015-03-31 16:46:39 -04001977 // v120: Add double tap to wake setting.
1978 if (currentVersion == 119) {
1979 SettingsState secureSettings = getSecureSettingsLocked(userId);
1980 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
1981 getContext().getResources().getBoolean(
1982 R.bool.def_double_tap_to_wake) ? "1" : "0",
1983 SettingsState.SYSTEM_PACKAGE_NAME);
1984
1985 currentVersion = 120;
1986 }
1987
Svetoslav7e0683b2015-08-03 16:02:52 -07001988 if (currentVersion == 120) {
1989 // Before 121, we used a different string encoding logic. We just bump the
1990 // version here; SettingsState knows how to handle pre-version 120 files.
1991 currentVersion = 121;
1992 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07001993
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02001994 if (currentVersion == 121) {
1995 // Version 122: allow OEMs to set a default payment component in resources.
1996 // Note that we only write the default if no default has been set;
1997 // if there is, we just leave the default at whatever it currently is.
1998 final SettingsState secureSettings = getSecureSettingsLocked(userId);
1999 String defaultComponent = (getContext().getResources().getString(
2000 R.string.def_nfc_payment_component));
2001 Setting currentSetting = secureSettings.getSettingLocked(
2002 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
2003 if (defaultComponent != null && !defaultComponent.isEmpty() &&
2004 currentSetting == null) {
2005 secureSettings.insertSettingLocked(
2006 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
2007 defaultComponent,
2008 SettingsState.SYSTEM_PACKAGE_NAME);
2009 }
2010 currentVersion = 122;
2011 }
Jeff Brown503cffc2015-03-26 18:08:51 -07002012 // vXXX: Add new settings above this point.
Svetoslav683914b2015-01-15 14:22:26 -08002013
Jeff Brown503cffc2015-03-26 18:08:51 -07002014 // Return the current version.
2015 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08002016 }
2017 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002018 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002019}