blob: 8084edaa59992ef4894ab9e79dd757f7cc76661a [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
-b master501eec92009-07-06 13:53:11 -070019import java.io.FileNotFoundException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080020import java.security.SecureRandom;
Julia Reynolds5e458dd2014-07-07 16:07:01 -040021import java.util.HashMap;
Christopher Tate06efb532012-08-24 15:29:27 -070022import java.util.HashSet;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -070023import java.util.List;
Julia Reynolds5e458dd2014-07-07 16:07:01 -040024import java.util.Map;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070025import java.util.concurrent.atomic.AtomicBoolean;
26import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070027
Christopher Tated5fe1472012-09-10 15:48:38 -070028import android.app.ActivityManager;
Dianne Hackborn961321f2013-02-05 17:22:41 -080029import android.app.AppOpsManager;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070031import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentProvider;
33import android.content.ContentUris;
34import android.content.ContentValues;
35import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070036import android.content.Intent;
37import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070039import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070040import android.content.res.AssetFileDescriptor;
Christopher Tateafccaa82012-10-03 17:41:51 -070041import android.database.AbstractCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
43import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.database.sqlite.SQLiteQueryBuilder;
46import android.media.RingtoneManager;
47import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070048import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080049import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070050import android.os.DropBoxManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070051import android.os.FileObserver;
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;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.os.UserHandle;
56import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057import android.provider.MediaStore;
58import android.provider.Settings;
Amith Yamasaniccc7cb92014-09-23 11:32:34 -070059import android.provider.Settings.Secure;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060import android.text.TextUtils;
61import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080062import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.util.Slog;
64import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066public class SettingsProvider extends ContentProvider {
67 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070068 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070069
Christopher Tate0da13572013-10-13 17:34:49 -070070 private static final boolean USER_CHECK_THROWS = true;
71
Christopher Tate06efb532012-08-24 15:29:27 -070072 private static final String TABLE_SYSTEM = "system";
73 private static final String TABLE_SECURE = "secure";
74 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 private static final String TABLE_FAVORITES = "favorites";
76 private static final String TABLE_OLD_FAVORITES = "old_favorites";
77
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080078 private static final String[] COLUMN_VALUE = new String[] { "value" };
79
Christopher Tate06efb532012-08-24 15:29:27 -070080 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080081 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070083 private static final SparseArray<SettingsCache> sSystemCaches
84 = new SparseArray<SettingsCache>();
85 private static final SparseArray<SettingsCache> sSecureCaches
86 = new SparseArray<SettingsCache>();
87 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070088
89 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070090 // database mutations are currently being handled for this user.
91 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070092 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070093 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
94 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080095
Christopher Tate78d2a662012-09-13 16:19:44 -070096 // Each defined user has their own settings
97 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
98
Amith Yamasani4f7e2e32014-08-14 18:49:48 -070099 // Keep the list of managed profiles synced here
100 private List<UserInfo> mManagedProfiles = null;
101
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800102 // Over this size we don't reject loading or saving settings but
103 // we do consider them broken/malicious and don't keep them in
104 // memory at least:
105 private static final int MAX_CACHE_ENTRY_SIZE = 500;
106
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800107 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
108
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700109 // Used as a sentinel value in an instance equality test when we
110 // want to cache the existence of a key, but not store its value.
111 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
112
Christopher Tate06efb532012-08-24 15:29:27 -0700113 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700114 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700115
116 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700117 * Settings which need to be treated as global/shared in multi-user environments.
118 */
119 static final HashSet<String> sSecureGlobalKeys;
120 static final HashSet<String> sSystemGlobalKeys;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700121
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400122 // Settings that cannot be modified if associated user restrictions are enabled.
123 static final Map<String, String> sRestrictedKeys;
124
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700125 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
126
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700127 static final HashSet<String> sSecureCloneToManagedKeys;
128 static final HashSet<String> sSystemCloneToManagedKeys;
129
Christopher Tate06efb532012-08-24 15:29:27 -0700130 static {
131 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
132 // table, shared across all users
133 // These must match Settings.Secure.MOVED_TO_GLOBAL
134 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700135 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700136
137 // Keys from the 'system' table now moved to 'global'
138 // These must match Settings.System.MOVED_TO_GLOBAL
139 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700140 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400141
142 sRestrictedKeys = new HashMap<String, String>();
143 sRestrictedKeys.put(Settings.Secure.LOCATION_MODE, UserManager.DISALLOW_SHARE_LOCATION);
144 sRestrictedKeys.put(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
145 UserManager.DISALLOW_SHARE_LOCATION);
Julia Reynolds25838502014-07-10 12:29:40 -0400146 sRestrictedKeys.put(Settings.Secure.INSTALL_NON_MARKET_APPS,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400147 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
148 sRestrictedKeys.put(Settings.Global.ADB_ENABLED, UserManager.DISALLOW_DEBUGGING_FEATURES);
149 sRestrictedKeys.put(Settings.Global.PACKAGE_VERIFIER_ENABLE,
150 UserManager.ENSURE_VERIFY_APPS);
151 sRestrictedKeys.put(Settings.Global.PREFERRED_NETWORK_MODE,
152 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700153
154 sSecureCloneToManagedKeys = new HashSet<String>();
155 for (int i = 0; i < Settings.Secure.CLONE_TO_MANAGED_PROFILE.length; i++) {
156 sSecureCloneToManagedKeys.add(Settings.Secure.CLONE_TO_MANAGED_PROFILE[i]);
157 }
158 sSystemCloneToManagedKeys = new HashSet<String>();
159 for (int i = 0; i < Settings.System.CLONE_TO_MANAGED_PROFILE.length; i++) {
160 sSystemCloneToManagedKeys.add(Settings.System.CLONE_TO_MANAGED_PROFILE[i]);
161 }
Christopher Tate06efb532012-08-24 15:29:27 -0700162 }
163
164 private boolean settingMovedToGlobal(final String name) {
165 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
166 }
167
168 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700169 * Decode a content URL into the table, projection, and arguments
170 * used to access the corresponding database rows.
171 */
172 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700174 public final String where;
175 public final String[] args;
176
177 /** Operate on existing rows. */
178 SqlArguments(Uri url, String where, String[] args) {
179 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700180 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700181 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700182 if (!DatabaseHelper.isValidTable(this.table)) {
183 throw new IllegalArgumentException("Bad root path: " + this.table);
184 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700185 this.where = where;
186 this.args = args;
187 } else if (url.getPathSegments().size() != 2) {
188 throw new IllegalArgumentException("Invalid URI: " + url);
189 } else if (!TextUtils.isEmpty(where)) {
190 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
191 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700192 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700193 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700194 if (!DatabaseHelper.isValidTable(this.table)) {
195 throw new IllegalArgumentException("Bad root path: " + this.table);
196 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700197 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
198 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700199 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700200 final String name = url.getPathSegments().get(1);
201 this.args = new String[] { name };
202 // Rewrite the table for known-migrated names
203 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
204 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
205 this.table = TABLE_GLOBAL;
206 }
207 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700208 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700209 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700210 this.where = "_id=" + ContentUris.parseId(url);
211 this.args = null;
212 }
213 }
214 }
215
216 /** Insert new rows (no where clause allowed). */
217 SqlArguments(Uri url) {
218 if (url.getPathSegments().size() == 1) {
219 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700220 if (!DatabaseHelper.isValidTable(this.table)) {
221 throw new IllegalArgumentException("Bad root path: " + this.table);
222 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700223 this.where = null;
224 this.args = null;
225 } else {
226 throw new IllegalArgumentException("Invalid URI: " + url);
227 }
228 }
229 }
230
231 /**
232 * Get the content URI of a row added to a table.
233 * @param tableUri of the entire table
234 * @param values found in the row
235 * @param rowId of the row
236 * @return the content URI for this particular row
237 */
238 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
239 if (tableUri.getPathSegments().size() != 1) {
240 throw new IllegalArgumentException("Invalid URI: " + tableUri);
241 }
242 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700243 if (TABLE_SYSTEM.equals(table) ||
244 TABLE_SECURE.equals(table) ||
245 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 String name = values.getAsString(Settings.NameValueTable.NAME);
247 return Uri.withAppendedPath(tableUri, name);
248 } else {
249 return ContentUris.withAppendedId(tableUri, rowId);
250 }
251 }
252
253 /**
254 * Send a notification when a particular content URI changes.
255 * Modify the system property used to communicate the version of
256 * this table, for tables which have such a property. (The Settings
257 * contract class uses these to provide client-side caches.)
258 * @param uri to send notifications for
259 */
Christopher Tate06efb532012-08-24 15:29:27 -0700260 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700261 // Update the system property *first*, so if someone is listening for
262 // a notification and then using the contract class to get their data,
263 // the system property will be updated and they'll get the new data.
264
Amith Yamasanid1582142009-07-08 20:04:55 -0700265 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700266 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700267 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700268 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700269 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700270 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700271 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700272 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700273 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700274 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700275 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700276 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700277 }
278
279 if (property != null) {
280 long version = SystemProperties.getLong(property, 0) + 1;
281 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
282 SystemProperties.set(property, Long.toString(version));
283 }
284
-b master501eec92009-07-06 13:53:11 -0700285 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700286 if (backedUpDataChanged) {
287 mBackupManager.dataChanged();
288 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700289 // Now send the notification through the content framework.
290
291 String notify = uri.getQueryParameter("notify");
292 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700293 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700294 final long oldId = Binder.clearCallingIdentity();
295 try {
296 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
297 } finally {
298 Binder.restoreCallingIdentity(oldId);
299 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700300 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700301 } else {
302 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
303 }
304 }
305
306 /**
307 * Make sure the caller has permission to write this data.
308 * @param args supplied by the caller
309 * @throws SecurityException if the caller is forbidden to write.
310 */
311 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700312 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800313 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800314 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
315 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700316 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800317 String.format("Permission denial: writing to secure settings requires %1$s",
318 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 }
320 }
321
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400322 private void checkUserRestrictions(String setting, int userId) {
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400323 String userRestriction = sRestrictedKeys.get(setting);
324 if (!TextUtils.isEmpty(userRestriction)
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400325 && mUserManager.hasUserRestriction(userRestriction, new UserHandle(userId))) {
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400326 throw new SecurityException(
327 "Permission denial: user is restricted from changing this setting.");
328 }
329 }
330
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700331 // FileObserver for external modifications to the database file.
332 // Note that this is for platform developers only with
333 // userdebug/eng builds who should be able to tinker with the
334 // sqlite database out from under the SettingsProvider, which is
335 // normally the exclusive owner of the database. But we keep this
336 // enabled all the time to minimize development-vs-user
337 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700338 private static SparseArray<SettingsFileObserver> sObserverInstances
339 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700340 private class SettingsFileObserver extends FileObserver {
341 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700342 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700343 private final String mPath;
344
Christopher Tate06efb532012-08-24 15:29:27 -0700345 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700346 super(path, FileObserver.CLOSE_WRITE |
347 FileObserver.CREATE | FileObserver.DELETE |
348 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700349 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700350 mPath = path;
351 }
352
353 public void onEvent(int event, String path) {
Dianne Hackborn8d051722014-10-01 14:59:58 -0700354 final AtomicInteger mutationCount;
355 synchronized (SettingsProvider.this) {
356 mutationCount = sKnownMutationsInFlight.get(mUserHandle);
357 }
358 if (mutationCount != null && mutationCount.get() > 0) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700359 // our own modification.
360 return;
361 }
Christopher Tate06efb532012-08-24 15:29:27 -0700362 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
363 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700364 if (!mIsDirty.compareAndSet(false, true)) {
365 // already handled. (we get a few update events
366 // during an sqlite write)
367 return;
368 }
Christopher Tate06efb532012-08-24 15:29:27 -0700369 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
370 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700371 mIsDirty.set(false);
372 }
373 }
374
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700375 @Override
376 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700377 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700378 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800379
Dianne Hackborn961321f2013-02-05 17:22:41 -0800380 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700381 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700382
Christopher Tate78d2a662012-09-13 16:19:44 -0700383 IntentFilter userFilter = new IntentFilter();
384 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700385 userFilter.addAction(Intent.ACTION_USER_ADDED);
Christopher Tate78d2a662012-09-13 16:19:44 -0700386 getContext().registerReceiver(new BroadcastReceiver() {
387 @Override
388 public void onReceive(Context context, Intent intent) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700389 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
390 UserHandle.USER_OWNER);
Christopher Tate78d2a662012-09-13 16:19:44 -0700391 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700392 onUserRemoved(userHandle);
393 } else if (intent.getAction().equals(Intent.ACTION_USER_ADDED)) {
394 onProfilesChanged();
Christopher Tate06efb532012-08-24 15:29:27 -0700395 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700396 }
397 }, userFilter);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700398
399 onProfilesChanged();
400
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401 return true;
402 }
403
Christopher Tate06efb532012-08-24 15:29:27 -0700404 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700405 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700406 // the db file itself will be deleted automatically, but we need to tear down
407 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700408 FileObserver observer = sObserverInstances.get(userHandle);
409 if (observer != null) {
410 observer.stopWatching();
411 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700412 }
Christopher Tate06efb532012-08-24 15:29:27 -0700413
414 mOpenHelpers.delete(userHandle);
415 sSystemCaches.delete(userHandle);
416 sSecureCaches.delete(userHandle);
417 sKnownMutationsInFlight.delete(userHandle);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700418 onProfilesChanged();
419 }
420 }
421
422 /**
423 * Updates the list of managed profiles. It assumes that only the primary user
424 * can have managed profiles. Modify this code if that changes in the future.
425 */
426 void onProfilesChanged() {
427 synchronized (this) {
428 mManagedProfiles = mUserManager.getProfiles(UserHandle.USER_OWNER);
429 if (mManagedProfiles != null) {
430 // Remove the primary user from the list
431 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
432 if (mManagedProfiles.get(i).id == UserHandle.USER_OWNER) {
433 mManagedProfiles.remove(i);
434 }
435 }
436 // If there are no managed profiles, reset the variable
437 if (mManagedProfiles.size() == 0) {
438 mManagedProfiles = null;
439 }
440 }
441 if (LOCAL_LOGV) {
442 Slog.d(TAG, "Managed Profiles = " + mManagedProfiles);
443 }
Christopher Tate06efb532012-08-24 15:29:27 -0700444 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700445 }
446
Christopher Tate78d2a662012-09-13 16:19:44 -0700447 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700448 if (LOCAL_LOGV) {
449 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
450 }
451
Christopher Tate78d2a662012-09-13 16:19:44 -0700452 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700453
Christopher Tate78d2a662012-09-13 16:19:44 -0700454 synchronized (this) {
455 dbhelper = mOpenHelpers.get(userHandle);
456 if (dbhelper == null) {
457 dbhelper = new DatabaseHelper(getContext(), userHandle);
458 mOpenHelpers.append(userHandle, dbhelper);
459
460 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
461 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
462 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
463 }
464 }
465
466 // Initialization of the db *outside* the locks. It's possible that racing
467 // threads might wind up here, the second having read the cache entries
468 // written by the first, but that's benign: the SQLite helper implementation
469 // manages concurrency itself, and it's important that we not run the db
470 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700471 SQLiteDatabase db = dbhelper.getWritableDatabase();
472
Christopher Tate78d2a662012-09-13 16:19:44 -0700473 // Watch for external modifications to the database files,
474 // keeping our caches in sync. We synchronize the observer set
475 // separately, and of course it has to run after the db file
476 // itself was set up by the DatabaseHelper.
477 synchronized (sObserverInstances) {
478 if (sObserverInstances.get(userHandle) == null) {
479 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
480 sObserverInstances.append(userHandle, observer);
481 observer.startWatching();
482 }
483 }
Christopher Tate06efb532012-08-24 15:29:27 -0700484
Christopher Tate4dc7a682012-09-11 12:15:49 -0700485 ensureAndroidIdIsSet(userHandle);
486
Christopher Tate06efb532012-08-24 15:29:27 -0700487 startAsyncCachePopulation(userHandle);
488 }
489
490 class CachePrefetchThread extends Thread {
491 private int mUserHandle;
492
493 CachePrefetchThread(int userHandle) {
494 super("populate-settings-caches");
495 mUserHandle = userHandle;
496 }
497
498 @Override
499 public void run() {
500 fullyPopulateCaches(mUserHandle);
501 }
502 }
503
504 private void startAsyncCachePopulation(int userHandle) {
505 new CachePrefetchThread(userHandle).start();
506 }
507
508 private void fullyPopulateCaches(final int userHandle) {
509 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
510 // Only populate the globals cache once, for the owning user
511 if (userHandle == UserHandle.USER_OWNER) {
512 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
513 }
514 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
515 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700516 }
517
518 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700519 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
520 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700521 Cursor c = db.query(
522 table,
523 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
524 null, null, null, null, null,
525 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
526 try {
527 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800528 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700529 cache.setFullyMatchesDisk(true); // optimistic
530 int rows = 0;
531 while (c.moveToNext()) {
532 rows++;
533 String name = c.getString(0);
534 String value = c.getString(1);
535 cache.populate(name, value);
536 }
537 if (rows > MAX_CACHE_ENTRIES) {
538 // Somewhat redundant, as removeEldestEntry() will
539 // have already done this, but to be explicit:
540 cache.setFullyMatchesDisk(false);
541 Log.d(TAG, "row count exceeds max cache entries for table " + table);
542 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800543 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
544 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700545 }
546 } finally {
547 c.close();
548 }
549 }
550
Christopher Tate4dc7a682012-09-11 12:15:49 -0700551 private boolean ensureAndroidIdIsSet(int userHandle) {
552 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800553 new String[] { Settings.NameValueTable.VALUE },
554 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700555 new String[] { Settings.Secure.ANDROID_ID }, null,
556 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800557 try {
558 final String value = c.moveToNext() ? c.getString(0) : null;
559 if (value == null) {
Christopher Tate38e7a602013-09-03 16:57:34 -0700560 // sanity-check the user before touching the db
561 final UserInfo user = mUserManager.getUserInfo(userHandle);
562 if (user == null) {
563 // can happen due to races when deleting users; treat as benign
564 return false;
565 }
566
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700567 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800568 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800569 final ContentValues values = new ContentValues();
570 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
571 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700572 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800573 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700574 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800575 return false;
576 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700577 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
578 + "] for user " + userHandle);
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700579 // Write a dropbox entry if it's a restricted profile
Christopher Tate38e7a602013-09-03 16:57:34 -0700580 if (user.isRestricted()) {
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700581 DropBoxManager dbm = (DropBoxManager)
582 getContext().getSystemService(Context.DROPBOX_SERVICE);
583 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
584 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
585 + ",restricted_profile_ssaid,"
586 + newAndroidIdValue + "\n");
587 }
588 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800589 }
590 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800591 } finally {
592 c.close();
593 }
594 }
595
Christopher Tate06efb532012-08-24 15:29:27 -0700596 // Lazy-initialize the settings caches for non-primary users
597 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700598 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
599 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700600 }
601
602 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700603 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate0da13572013-10-13 17:34:49 -0700604 if (callingUser >= Process.SYSTEM_UID) {
605 if (USER_CHECK_THROWS) {
606 throw new IllegalArgumentException("Uid rather than user handle: " + callingUser);
607 } else {
608 Slog.wtf(TAG, "establish db for uid rather than user: " + callingUser);
609 }
610 }
611
Christopher Tate06efb532012-08-24 15:29:27 -0700612 long oldId = Binder.clearCallingIdentity();
613 try {
614 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
615 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700616 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700617 dbHelper = mOpenHelpers.get(callingUser);
618 }
619 return dbHelper;
620 } finally {
621 Binder.restoreCallingIdentity(oldId);
622 }
623 }
624
625 public SettingsCache cacheForTable(final int callingUser, String tableName) {
626 if (TABLE_SYSTEM.equals(tableName)) {
627 return getOrConstructCache(callingUser, sSystemCaches);
628 }
629 if (TABLE_SECURE.equals(tableName)) {
630 return getOrConstructCache(callingUser, sSecureCaches);
631 }
632 if (TABLE_GLOBAL.equals(tableName)) {
633 return sGlobalCache;
634 }
635 return null;
636 }
637
638 /**
639 * Used for wiping a whole cache on deletes when we're not
640 * sure what exactly was deleted or changed.
641 */
642 public void invalidateCache(final int callingUser, String tableName) {
643 SettingsCache cache = cacheForTable(callingUser, tableName);
644 if (cache == null) {
645 return;
646 }
647 synchronized (cache) {
648 cache.evictAll();
649 cache.mCacheFullyMatchesDisk = false;
650 }
651 }
652
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800653 /**
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700654 * Checks if the calling user is a managed profile of the primary user.
655 * Currently only the primary user (USER_OWNER) can have managed profiles.
656 * @param callingUser the user trying to read/write settings
657 * @return true if it is a managed profile of the primary user
658 */
659 private boolean isManagedProfile(int callingUser) {
660 synchronized (this) {
661 if (mManagedProfiles == null) return false;
662 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
663 if (mManagedProfiles.get(i).id == callingUser) {
664 return true;
665 }
666 }
667 return false;
668 }
669 }
670
671 /**
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800672 * Fast path that avoids the use of chatty remoted Cursors.
673 */
674 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700675 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700676 int callingUser = UserHandle.getCallingUserId();
677 if (args != null) {
678 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
679 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700680 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
681 Binder.getCallingUid(), reqUser, false, true,
682 "get/set setting for user", null);
683 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700684 }
685 }
686
Christopher Tate61695ff2012-10-05 12:05:13 -0700687 // Note: we assume that get/put operations for moved-to-global names have already
688 // been directed to the new location on the caller side (otherwise we'd fix them
689 // up here).
690 DatabaseHelper dbHelper;
691 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700692
Christopher Tate61695ff2012-10-05 12:05:13 -0700693 // Get methods
694 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
695 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700696 // Check if this request should be (re)directed to the primary user's db
697 if (callingUser == UserHandle.USER_OWNER
698 || shouldShadowParentProfile(callingUser, sSystemCloneToManagedKeys, request)) {
699 dbHelper = getOrEstablishDatabase(UserHandle.USER_OWNER);
700 } else {
701 dbHelper = getOrEstablishDatabase(callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700702 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700703 cache = sSystemCaches.get(callingUser);
704 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
705 }
706 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
707 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700708 // Check if this is a setting to be copied from the primary user
709 if (shouldShadowParentProfile(callingUser, sSecureCloneToManagedKeys, request)) {
710 // If the request if for location providers and there's a restriction, return none
711 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(request)
712 && mUserManager.hasUserRestriction(
713 UserManager.DISALLOW_SHARE_LOCATION, new UserHandle(callingUser))) {
714 return sSecureCaches.get(callingUser).putIfAbsent(request, "");
715 }
716 dbHelper = getOrEstablishDatabase(UserHandle.USER_OWNER);
717 } else {
718 dbHelper = getOrEstablishDatabase(callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700719 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700720 cache = sSecureCaches.get(callingUser);
721 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
722 }
723 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
724 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
725 // fast path: owner db & cache are immutable after onCreate() so we need not
726 // guard on the attempt to look them up
727 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
728 sGlobalCache, request);
729 }
Christopher Tate06efb532012-08-24 15:29:27 -0700730
Christopher Tate61695ff2012-10-05 12:05:13 -0700731 // Put methods - new value is in the args bundle under the key named by
732 // the Settings.NameValueTable.VALUE static.
733 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800734 ? null : args.getString(Settings.NameValueTable.VALUE);
735
736 // Framework can't do automatic permission checking for calls, so we need
737 // to do it here.
738 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
739 != PackageManager.PERMISSION_GRANTED) {
740 throw new SecurityException(
741 String.format("Permission denial: writing to settings requires %1$s",
742 android.Manifest.permission.WRITE_SETTINGS));
743 }
744
745 // Also need to take care of app op.
746 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700747 getCallingPackage()) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn961321f2013-02-05 17:22:41 -0800748 return null;
749 }
Christopher Tate06efb532012-08-24 15:29:27 -0700750
Christopher Tate61695ff2012-10-05 12:05:13 -0700751 final ContentValues values = new ContentValues();
752 values.put(Settings.NameValueTable.NAME, request);
753 values.put(Settings.NameValueTable.VALUE, newValue);
754 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700755 if (LOCAL_LOGV) {
756 Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for "
757 + callingUser);
758 }
759 // Extra check for USER_OWNER to optimize for the 99%
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700760 if (callingUser != UserHandle.USER_OWNER && shouldShadowParentProfile(callingUser,
761 sSystemCloneToManagedKeys, request)) {
762 // Don't write these settings, as they are cloned from the parent profile
763 return null;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700764 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700765 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700766 // Clone the settings to the managed profiles so that notifications can be sent out
767 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
768 && sSystemCloneToManagedKeys.contains(request)) {
769 final long token = Binder.clearCallingIdentity();
770 try {
771 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
772 if (LOCAL_LOGV) {
773 Slog.v(TAG, "putting to additional user "
774 + mManagedProfiles.get(i).id);
775 }
776 insertForUser(Settings.System.CONTENT_URI, values,
777 mManagedProfiles.get(i).id);
778 }
779 } finally {
780 Binder.restoreCallingIdentity(token);
781 }
782 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700783 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700784 if (LOCAL_LOGV) {
785 Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for "
786 + callingUser);
787 }
788 // Extra check for USER_OWNER to optimize for the 99%
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700789 if (callingUser != UserHandle.USER_OWNER && shouldShadowParentProfile(callingUser,
790 sSecureCloneToManagedKeys, request)) {
791 // Don't write these settings, as they are cloned from the parent profile
792 return null;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700793 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700794 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700795 // Clone the settings to the managed profiles so that notifications can be sent out
796 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
797 && sSecureCloneToManagedKeys.contains(request)) {
798 final long token = Binder.clearCallingIdentity();
799 try {
800 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
801 if (LOCAL_LOGV) {
802 Slog.v(TAG, "putting to additional user "
803 + mManagedProfiles.get(i).id);
804 }
Zoltan Szatmary-Ban35349352014-09-11 11:28:20 +0100805 try {
806 insertForUser(Settings.Secure.CONTENT_URI, values,
807 mManagedProfiles.get(i).id);
808 } catch (SecurityException e) {
809 // Temporary fix, see b/17450158
810 Slog.w(TAG, "Cannot clone request '" + request + "' with value '"
811 + newValue + "' to managed profile (id "
812 + mManagedProfiles.get(i).id + ")", e);
813 }
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700814 }
815 } finally {
816 Binder.restoreCallingIdentity(token);
817 }
818 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700819 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700820 if (LOCAL_LOGV) {
821 Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for "
822 + callingUser);
823 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700824 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
825 } else {
826 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700827 }
828
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800829 return null;
830 }
831
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700832 /**
833 * Check if the user is a managed profile and name is one of the settings to be cloned
834 * from the parent profile.
835 */
836 private boolean shouldShadowParentProfile(int userId, HashSet<String> keys, String name) {
837 return isManagedProfile(userId) && keys.contains(name);
838 }
839
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800840 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
841 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700842 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
843 final SettingsCache cache, String key) {
844 if (cache == null) {
845 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
846 return null;
847 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800848 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800849 Bundle value = cache.get(key);
850 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700851 if (value != TOO_LARGE_TO_CACHE_MARKER) {
852 return value;
853 }
854 // else we fall through and read the value from disk
855 } else if (cache.fullyMatchesDisk()) {
856 // Fast path (very common). Don't even try touch disk
857 // if we know we've slurped it all in. Trying to
858 // touch the disk would mean waiting for yaffs2 to
859 // give us access, which could takes hundreds of
860 // milliseconds. And we're very likely being called
861 // from somebody's UI thread...
862 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800863 }
864 }
865
Christopher Tate06efb532012-08-24 15:29:27 -0700866 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800867 Cursor cursor = null;
868 try {
869 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
870 null, null, null, null);
871 if (cursor != null && cursor.getCount() == 1) {
872 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800873 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800874 }
875 } catch (SQLiteException e) {
876 Log.w(TAG, "settings lookup error", e);
877 return null;
878 } finally {
879 if (cursor != null) cursor.close();
880 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800881 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800882 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800883 }
884
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700885 @Override
886 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700887 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
888 }
889
Christopher Tateb7564452012-09-19 16:21:18 -0700890 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700891 String sort, int forUser) {
892 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700893 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700894 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700895 dbH = getOrEstablishDatabase(
896 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700897 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800899 // The favorites table was moved from this provider to a provider inside Home
900 // Home still need to query this table to upgrade from pre-cupcake builds
901 // However, a cupcake+ build with no data does not contain this table which will
902 // cause an exception in the SQL stack. The following line is a special case to
903 // let the caller of the query have a chance to recover and avoid the exception
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 if (TABLE_FAVORITES.equals(args.table)) {
905 return null;
906 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
907 args.table = TABLE_FAVORITES;
908 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
909 if (cursor != null) {
910 boolean exists = cursor.getCount() > 0;
911 cursor.close();
912 if (!exists) return null;
913 } else {
914 return null;
915 }
916 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800917
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700918 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
919 qb.setTables(args.table);
920
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700921 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700922 // the default Cursor interface does not support per-user observation
923 try {
924 AbstractCursor c = (AbstractCursor) ret;
925 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
926 } catch (ClassCastException e) {
927 // details of the concrete Cursor implementation have changed and this code has
928 // not been updated to match -- complain and fail hard.
929 Log.wtf(TAG, "Incompatible cursor derivation!");
930 throw e;
931 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700932 return ret;
933 }
934
935 @Override
936 public String getType(Uri url) {
937 // If SqlArguments supplies a where clause, then it must be an item
938 // (because we aren't supplying our own where clause).
939 SqlArguments args = new SqlArguments(url, null, null);
940 if (TextUtils.isEmpty(args.where)) {
941 return "vnd.android.cursor.dir/" + args.table;
942 } else {
943 return "vnd.android.cursor.item/" + args.table;
944 }
945 }
946
947 @Override
948 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700949 final int callingUser = UserHandle.getCallingUserId();
950 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700951 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 if (TABLE_FAVORITES.equals(args.table)) {
953 return 0;
954 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700955 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700956 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700957
Dianne Hackborn8d051722014-10-01 14:59:58 -0700958 final AtomicInteger mutationCount;
959 synchronized (this) {
960 mutationCount = sKnownMutationsInFlight.get(callingUser);
961 }
962 if (mutationCount != null) {
963 mutationCount.incrementAndGet();
964 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700965 DatabaseHelper dbH = getOrEstablishDatabase(
966 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700967 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700968 db.beginTransaction();
969 try {
970 int numValues = values.length;
971 for (int i = 0; i < numValues; i++) {
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400972 checkUserRestrictions(values[i].getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700973 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800974 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700975 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
976 }
977 db.setTransactionSuccessful();
978 } finally {
979 db.endTransaction();
Dianne Hackborn8d051722014-10-01 14:59:58 -0700980 if (mutationCount != null) {
981 mutationCount.decrementAndGet();
982 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700983 }
984
Christopher Tate06efb532012-08-24 15:29:27 -0700985 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700986 return values.length;
987 }
988
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700989 /*
990 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
991 * This setting contains a list of the currently enabled location providers.
992 * But helper functions in android.providers.Settings can enable or disable
993 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800994 *
995 * @returns whether the database needs to be updated or not, also modifying
996 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700997 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500998 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700999 String value = initialValues.getAsString(Settings.Secure.VALUE);
1000 String newProviders = null;
1001 if (value != null && value.length() > 1) {
1002 char prefix = value.charAt(0);
1003 if (prefix == '+' || prefix == '-') {
1004 // skip prefix
1005 value = value.substring(1);
1006
1007 // read list of enabled providers into "providers"
1008 String providers = "";
1009 String[] columns = {Settings.Secure.VALUE};
1010 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -05001011 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001012 if (cursor != null && cursor.getCount() == 1) {
1013 try {
1014 cursor.moveToFirst();
1015 providers = cursor.getString(0);
1016 } finally {
1017 cursor.close();
1018 }
1019 }
1020
1021 int index = providers.indexOf(value);
1022 int end = index + value.length();
1023 // check for commas to avoid matching on partial string
1024 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
1025 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
1026
1027 if (prefix == '+' && index < 0) {
1028 // append the provider to the list if not present
1029 if (providers.length() == 0) {
1030 newProviders = value;
1031 } else {
1032 newProviders = providers + ',' + value;
1033 }
1034 } else if (prefix == '-' && index >= 0) {
1035 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -04001036 // remove leading or trailing comma
1037 if (index > 0) {
1038 index--;
1039 } else if (end < providers.length()) {
1040 end++;
1041 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001042
1043 newProviders = providers.substring(0, index);
1044 if (end < providers.length()) {
1045 newProviders += providers.substring(end);
1046 }
1047 } else {
1048 // nothing changed, so no need to update the database
1049 return false;
1050 }
1051
1052 if (newProviders != null) {
1053 initialValues.put(Settings.Secure.VALUE, newProviders);
1054 }
1055 }
1056 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001057
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001058 return true;
1059 }
1060
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001061 @Override
1062 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -07001063 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
1064 }
1065
1066 // Settings.put*ForUser() always winds up here, so this is where we apply
1067 // policy around permission to write settings for other users.
1068 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
1069 final int callingUser = UserHandle.getCallingUserId();
1070 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001071 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -07001072 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1073 "Not permitted to access settings for other users");
1074 }
1075
1076 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
1077 + " by " + callingUser);
1078
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001079 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 if (TABLE_FAVORITES.equals(args.table)) {
1081 return null;
1082 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001083
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001084 // Special case LOCATION_PROVIDERS_ALLOWED.
1085 // Support enabling/disabling a single provider (using "+" or "-" prefix)
1086 String name = initialValues.getAsString(Settings.Secure.NAME);
1087 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -05001088 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001089 }
1090
Christopher Tatec221d2b2012-10-03 18:33:52 -07001091 // If this is an insert() of a key that has been migrated to the global store,
1092 // redirect the operation to that store
1093 if (name != null) {
1094 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
1095 if (!TABLE_GLOBAL.equals(args.table)) {
1096 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
1097 }
1098 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
1099 }
1100 }
1101
Christopher Tate34637e52012-10-04 15:00:00 -07001102 // Check write permissions only after determining which table the insert will touch
1103 checkWritePermissions(args);
1104
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001105 checkUserRestrictions(name, desiredUserHandle);
Julia Reynolds5e458dd2014-07-07 16:07:01 -04001106
Christopher Tate06efb532012-08-24 15:29:27 -07001107 // The global table is stored under the owner, always
1108 if (TABLE_GLOBAL.equals(args.table)) {
1109 desiredUserHandle = UserHandle.USER_OWNER;
1110 }
1111
1112 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001113 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
1114 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
1115 return Uri.withAppendedPath(url, name);
1116 }
1117
Dianne Hackborn8d051722014-10-01 14:59:58 -07001118 final AtomicInteger mutationCount;
1119 synchronized (this) {
1120 mutationCount = sKnownMutationsInFlight.get(callingUser);
1121 }
1122 if (mutationCount != null) {
1123 mutationCount.incrementAndGet();
1124 }
Christopher Tate78d2a662012-09-13 16:19:44 -07001125 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001126 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001127 final long rowId = db.insert(args.table, null, initialValues);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001128 if (mutationCount != null) {
1129 mutationCount.decrementAndGet();
1130 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001131 if (rowId <= 0) return null;
1132
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001133 SettingsCache.populate(cache, initialValues); // before we notify
1134
Christopher Tate78d2a662012-09-13 16:19:44 -07001135 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
1136 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001137 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001138 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -07001139 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001140 return url;
1141 }
1142
1143 @Override
1144 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001145 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001146 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001147 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 if (TABLE_FAVORITES.equals(args.table)) {
1149 return 0;
1150 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
1151 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001152 } else if (TABLE_GLOBAL.equals(args.table)) {
1153 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001155 checkWritePermissions(args);
1156
Dianne Hackborn8d051722014-10-01 14:59:58 -07001157 final AtomicInteger mutationCount;
1158 synchronized (this) {
1159 mutationCount = sKnownMutationsInFlight.get(callingUser);
1160 }
1161 if (mutationCount != null) {
1162 mutationCount.incrementAndGet();
1163 }
Christopher Tate78d2a662012-09-13 16:19:44 -07001164 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001165 SQLiteDatabase db = dbH.getWritableDatabase();
1166 int count = db.delete(args.table, args.where, args.args);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001167 if (mutationCount != null) {
1168 mutationCount.decrementAndGet();
1169 }
Christopher Tate06efb532012-08-24 15:29:27 -07001170 if (count > 0) {
1171 invalidateCache(callingUser, args.table); // before we notify
1172 sendNotify(url, callingUser);
1173 }
1174 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001175 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1176 return count;
1177 }
1178
1179 @Override
1180 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001181 // NOTE: update() is never called by the front-end Settings API, and updates that
1182 // wind up affecting rows in Secure that are globally shared will not have the
1183 // intended effect (the update will be invisible to the rest of the system).
1184 // This should have no practical effect, since writes to the Secure db can only
1185 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001186 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001187 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001188 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 if (TABLE_FAVORITES.equals(args.table)) {
1190 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001191 } else if (TABLE_GLOBAL.equals(args.table)) {
1192 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001194 checkWritePermissions(args);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001195 checkUserRestrictions(initialValues.getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001196
Dianne Hackborn8d051722014-10-01 14:59:58 -07001197 final AtomicInteger mutationCount;
1198 synchronized (this) {
1199 mutationCount = sKnownMutationsInFlight.get(callingUser);
1200 }
1201 if (mutationCount != null) {
1202 mutationCount.incrementAndGet();
1203 }
Christopher Tate78d2a662012-09-13 16:19:44 -07001204 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001205 SQLiteDatabase db = dbH.getWritableDatabase();
1206 int count = db.update(args.table, initialValues, args.where, args.args);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001207 if (mutationCount != null) {
1208 mutationCount.decrementAndGet();
1209 }
Christopher Tate06efb532012-08-24 15:29:27 -07001210 if (count > 0) {
1211 invalidateCache(callingUser, args.table); // before we notify
1212 sendNotify(url, callingUser);
1213 }
1214 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001215 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1216 return count;
1217 }
1218
1219 @Override
1220 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1221
1222 /*
1223 * When a client attempts to openFile the default ringtone or
1224 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001225 * default ringtone's Uri (if it is in the media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001226 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001227 int ringtoneType = RingtoneManager.getDefaultType(uri);
1228 // Above call returns -1 if the Uri doesn't match a default type
1229 if (ringtoneType != -1) {
1230 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001231
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001232 // Get the current value for the default sound
1233 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001234
Marco Nelissen69f593c2009-07-28 09:55:04 -07001235 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001236 // Proxy the openFile call to media provider
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001237 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001238 if (authority.equals(MediaStore.AUTHORITY)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001239 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1240 }
1241 }
1242 }
1243
1244 return super.openFile(uri, mode);
1245 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001246
1247 @Override
1248 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1249
1250 /*
1251 * When a client attempts to openFile the default ringtone or
1252 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001253 * default ringtone's Uri (if it is in the media provider).
Marco Nelissen69f593c2009-07-28 09:55:04 -07001254 */
1255 int ringtoneType = RingtoneManager.getDefaultType(uri);
1256 // Above call returns -1 if the Uri doesn't match a default type
1257 if (ringtoneType != -1) {
1258 Context context = getContext();
1259
1260 // Get the current value for the default sound
1261 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1262
1263 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001264 // Proxy the openFile call to media provider
Marco Nelissen69f593c2009-07-28 09:55:04 -07001265 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001266 if (authority.equals(MediaStore.AUTHORITY)) {
Marco Nelissen69f593c2009-07-28 09:55:04 -07001267 ParcelFileDescriptor pfd = null;
1268 try {
1269 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1270 return new AssetFileDescriptor(pfd, 0, -1);
1271 } catch (FileNotFoundException ex) {
1272 // fall through and open the fallback ringtone below
1273 }
1274 }
1275
1276 try {
1277 return super.openAssetFile(soundUri, mode);
1278 } catch (FileNotFoundException ex) {
1279 // Since a non-null Uri was specified, but couldn't be opened,
1280 // fall back to the built-in ringtone.
1281 return context.getResources().openRawResourceFd(
1282 com.android.internal.R.raw.fallbackring);
1283 }
1284 }
1285 // no need to fall through and have openFile() try again, since we
1286 // already know that will fail.
1287 throw new FileNotFoundException(); // or return null ?
1288 }
1289
1290 // Note that this will end up calling openFile() above.
1291 return super.openAssetFile(uri, mode);
1292 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001293
1294 /**
1295 * In-memory LRU Cache of system and secure settings, along with
1296 * associated helper functions to keep cache coherent with the
1297 * database.
1298 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001299 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001300
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001301 private final String mCacheName;
1302 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1303
1304 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001305 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001306 mCacheName = name;
1307 }
1308
1309 /**
1310 * Is the whole database table slurped into this cache?
1311 */
1312 public boolean fullyMatchesDisk() {
1313 synchronized (this) {
1314 return mCacheFullyMatchesDisk;
1315 }
1316 }
1317
1318 public void setFullyMatchesDisk(boolean value) {
1319 synchronized (this) {
1320 mCacheFullyMatchesDisk = value;
1321 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001322 }
1323
1324 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001325 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1326 if (evicted) {
1327 mCacheFullyMatchesDisk = false;
1328 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001329 }
1330
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001331 /**
1332 * Atomic cache population, conditional on size of value and if
1333 * we lost a race.
1334 *
1335 * @returns a Bundle to send back to the client from call(), even
1336 * if we lost the race.
1337 */
1338 public Bundle putIfAbsent(String key, String value) {
1339 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1340 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1341 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001342 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001343 put(key, bundle);
1344 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001345 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001346 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001347 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001348 }
1349
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001350 /**
1351 * Populates a key in a given (possibly-null) cache.
1352 */
1353 public static void populate(SettingsCache cache, ContentValues contentValues) {
1354 if (cache == null) {
1355 return;
1356 }
1357 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1358 if (name == null) {
1359 Log.w(TAG, "null name populating settings cache.");
1360 return;
1361 }
1362 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001363 cache.populate(name, value);
1364 }
1365
1366 public void populate(String name, String value) {
1367 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001368 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001369 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001370 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001371 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001372 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001373 }
1374 }
1375
1376 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001377 * For suppressing duplicate/redundant settings inserts early,
1378 * checking our cache first (but without faulting it in),
1379 * before going to sqlite with the mutation.
1380 */
1381 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1382 if (cache == null) return false;
1383 synchronized (cache) {
1384 Bundle bundle = cache.get(name);
1385 if (bundle == null) return false;
1386 String oldValue = bundle.getPairValue();
1387 if (oldValue == null && value == null) return true;
1388 if ((oldValue == null) != (value == null)) return false;
1389 return oldValue.equals(value);
1390 }
1391 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001392 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001393}