blob: 6828301cf2d947ce7913a3b5c08aa20098ea6dba [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;
Christopher Tateafccaa82012-10-03 17:41:51 -070040import android.database.AbstractCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.Cursor;
42import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteQueryBuilder;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070046import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080047import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070048import android.os.DropBoxManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070049import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070051import android.os.Process;
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;
Amith Yamasaniccc7cb92014-09-23 11:32:34 -070056import android.provider.Settings.Secure;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057import android.text.TextUtils;
58import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080059import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070060import android.util.Slog;
61import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063public class SettingsProvider extends ContentProvider {
64 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070065 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066
Christopher Tate0da13572013-10-13 17:34:49 -070067 private static final boolean USER_CHECK_THROWS = true;
68
Christopher Tate06efb532012-08-24 15:29:27 -070069 private static final String TABLE_SYSTEM = "system";
70 private static final String TABLE_SECURE = "secure";
71 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TABLE_FAVORITES = "favorites";
73 private static final String TABLE_OLD_FAVORITES = "old_favorites";
74
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080075 private static final String[] COLUMN_VALUE = new String[] { "value" };
76
Christopher Tate06efb532012-08-24 15:29:27 -070077 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080078 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070079 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070080 private static final SparseArray<SettingsCache> sSystemCaches
81 = new SparseArray<SettingsCache>();
82 private static final SparseArray<SettingsCache> sSecureCaches
83 = new SparseArray<SettingsCache>();
84 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070085
86 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070087 // database mutations are currently being handled for this user.
88 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070089 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070090 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
91 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080092
Christopher Tate78d2a662012-09-13 16:19:44 -070093 // Each defined user has their own settings
94 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
95
Amith Yamasani4f7e2e32014-08-14 18:49:48 -070096 // Keep the list of managed profiles synced here
97 private List<UserInfo> mManagedProfiles = null;
98
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080099 // Over this size we don't reject loading or saving settings but
100 // we do consider them broken/malicious and don't keep them in
101 // memory at least:
102 private static final int MAX_CACHE_ENTRY_SIZE = 500;
103
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800104 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
105
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700106 // Used as a sentinel value in an instance equality test when we
107 // want to cache the existence of a key, but not store its value.
108 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
109
Christopher Tate06efb532012-08-24 15:29:27 -0700110 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700111 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700112
113 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700114 * Settings which need to be treated as global/shared in multi-user environments.
115 */
116 static final HashSet<String> sSecureGlobalKeys;
117 static final HashSet<String> sSystemGlobalKeys;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700118
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400119 // Settings that cannot be modified if associated user restrictions are enabled.
120 static final Map<String, String> sRestrictedKeys;
121
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700122 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
123
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700124 static final HashSet<String> sSecureCloneToManagedKeys;
125 static final HashSet<String> sSystemCloneToManagedKeys;
126
Christopher Tate06efb532012-08-24 15:29:27 -0700127 static {
128 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
129 // table, shared across all users
130 // These must match Settings.Secure.MOVED_TO_GLOBAL
131 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700132 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700133
134 // Keys from the 'system' table now moved to 'global'
135 // These must match Settings.System.MOVED_TO_GLOBAL
136 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700137 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400138
139 sRestrictedKeys = new HashMap<String, String>();
140 sRestrictedKeys.put(Settings.Secure.LOCATION_MODE, UserManager.DISALLOW_SHARE_LOCATION);
141 sRestrictedKeys.put(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
142 UserManager.DISALLOW_SHARE_LOCATION);
Julia Reynolds25838502014-07-10 12:29:40 -0400143 sRestrictedKeys.put(Settings.Secure.INSTALL_NON_MARKET_APPS,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400144 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
145 sRestrictedKeys.put(Settings.Global.ADB_ENABLED, UserManager.DISALLOW_DEBUGGING_FEATURES);
146 sRestrictedKeys.put(Settings.Global.PACKAGE_VERIFIER_ENABLE,
147 UserManager.ENSURE_VERIFY_APPS);
148 sRestrictedKeys.put(Settings.Global.PREFERRED_NETWORK_MODE,
149 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700150
151 sSecureCloneToManagedKeys = new HashSet<String>();
152 for (int i = 0; i < Settings.Secure.CLONE_TO_MANAGED_PROFILE.length; i++) {
153 sSecureCloneToManagedKeys.add(Settings.Secure.CLONE_TO_MANAGED_PROFILE[i]);
154 }
155 sSystemCloneToManagedKeys = new HashSet<String>();
156 for (int i = 0; i < Settings.System.CLONE_TO_MANAGED_PROFILE.length; i++) {
157 sSystemCloneToManagedKeys.add(Settings.System.CLONE_TO_MANAGED_PROFILE[i]);
158 }
Christopher Tate06efb532012-08-24 15:29:27 -0700159 }
160
161 private boolean settingMovedToGlobal(final String name) {
162 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
163 }
164
165 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700166 * Decode a content URL into the table, projection, and arguments
167 * used to access the corresponding database rows.
168 */
169 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700171 public final String where;
172 public final String[] args;
173
174 /** Operate on existing rows. */
175 SqlArguments(Uri url, String where, String[] args) {
176 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700177 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700178 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700179 if (!DatabaseHelper.isValidTable(this.table)) {
180 throw new IllegalArgumentException("Bad root path: " + this.table);
181 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700182 this.where = where;
183 this.args = args;
184 } else if (url.getPathSegments().size() != 2) {
185 throw new IllegalArgumentException("Invalid URI: " + url);
186 } else if (!TextUtils.isEmpty(where)) {
187 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
188 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700189 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700190 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700191 if (!DatabaseHelper.isValidTable(this.table)) {
192 throw new IllegalArgumentException("Bad root path: " + this.table);
193 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700194 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
195 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700196 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700197 final String name = url.getPathSegments().get(1);
198 this.args = new String[] { name };
199 // Rewrite the table for known-migrated names
200 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
201 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
202 this.table = TABLE_GLOBAL;
203 }
204 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700205 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700206 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700207 this.where = "_id=" + ContentUris.parseId(url);
208 this.args = null;
209 }
210 }
211 }
212
213 /** Insert new rows (no where clause allowed). */
214 SqlArguments(Uri url) {
215 if (url.getPathSegments().size() == 1) {
216 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700217 if (!DatabaseHelper.isValidTable(this.table)) {
218 throw new IllegalArgumentException("Bad root path: " + this.table);
219 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 this.where = null;
221 this.args = null;
222 } else {
223 throw new IllegalArgumentException("Invalid URI: " + url);
224 }
225 }
226 }
227
228 /**
229 * Get the content URI of a row added to a table.
230 * @param tableUri of the entire table
231 * @param values found in the row
232 * @param rowId of the row
233 * @return the content URI for this particular row
234 */
235 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
236 if (tableUri.getPathSegments().size() != 1) {
237 throw new IllegalArgumentException("Invalid URI: " + tableUri);
238 }
239 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700240 if (TABLE_SYSTEM.equals(table) ||
241 TABLE_SECURE.equals(table) ||
242 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700243 String name = values.getAsString(Settings.NameValueTable.NAME);
244 return Uri.withAppendedPath(tableUri, name);
245 } else {
246 return ContentUris.withAppendedId(tableUri, rowId);
247 }
248 }
249
250 /**
251 * Send a notification when a particular content URI changes.
252 * Modify the system property used to communicate the version of
253 * this table, for tables which have such a property. (The Settings
254 * contract class uses these to provide client-side caches.)
255 * @param uri to send notifications for
256 */
Christopher Tate06efb532012-08-24 15:29:27 -0700257 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 // Update the system property *first*, so if someone is listening for
259 // a notification and then using the contract class to get their data,
260 // the system property will be updated and they'll get the new data.
261
Amith Yamasanid1582142009-07-08 20:04:55 -0700262 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700263 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700264 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700265 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700266 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700267 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700268 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700269 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700270 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700271 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700272 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700273 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700274 }
275
276 if (property != null) {
277 long version = SystemProperties.getLong(property, 0) + 1;
278 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
279 SystemProperties.set(property, Long.toString(version));
280 }
281
-b master501eec92009-07-06 13:53:11 -0700282 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700283 if (backedUpDataChanged) {
284 mBackupManager.dataChanged();
285 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700286 // Now send the notification through the content framework.
287
288 String notify = uri.getQueryParameter("notify");
289 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700290 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700291 final long oldId = Binder.clearCallingIdentity();
292 try {
293 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
294 } finally {
295 Binder.restoreCallingIdentity(oldId);
296 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700297 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700298 } else {
299 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
300 }
301 }
302
303 /**
304 * Make sure the caller has permission to write this data.
305 * @param args supplied by the caller
306 * @throws SecurityException if the caller is forbidden to write.
307 */
308 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700309 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800310 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800311 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
312 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700313 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800314 String.format("Permission denial: writing to secure settings requires %1$s",
315 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700316 }
317 }
318
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400319 private void checkUserRestrictions(String setting, int userId) {
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400320 String userRestriction = sRestrictedKeys.get(setting);
321 if (!TextUtils.isEmpty(userRestriction)
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400322 && mUserManager.hasUserRestriction(userRestriction, new UserHandle(userId))) {
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400323 throw new SecurityException(
324 "Permission denial: user is restricted from changing this setting.");
325 }
326 }
327
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700328 // FileObserver for external modifications to the database file.
329 // Note that this is for platform developers only with
330 // userdebug/eng builds who should be able to tinker with the
331 // sqlite database out from under the SettingsProvider, which is
332 // normally the exclusive owner of the database. But we keep this
333 // enabled all the time to minimize development-vs-user
334 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700335 private static SparseArray<SettingsFileObserver> sObserverInstances
336 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700337 private class SettingsFileObserver extends FileObserver {
338 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700339 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700340 private final String mPath;
341
Christopher Tate06efb532012-08-24 15:29:27 -0700342 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700343 super(path, FileObserver.CLOSE_WRITE |
344 FileObserver.CREATE | FileObserver.DELETE |
345 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700346 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700347 mPath = path;
348 }
349
350 public void onEvent(int event, String path) {
Dianne Hackborn8d051722014-10-01 14:59:58 -0700351 final AtomicInteger mutationCount;
352 synchronized (SettingsProvider.this) {
353 mutationCount = sKnownMutationsInFlight.get(mUserHandle);
354 }
355 if (mutationCount != null && mutationCount.get() > 0) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700356 // our own modification.
357 return;
358 }
Christopher Tate06efb532012-08-24 15:29:27 -0700359 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
360 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700361 if (!mIsDirty.compareAndSet(false, true)) {
362 // already handled. (we get a few update events
363 // during an sqlite write)
364 return;
365 }
Christopher Tate06efb532012-08-24 15:29:27 -0700366 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
367 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700368 mIsDirty.set(false);
369 }
370 }
371
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372 @Override
373 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700374 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700375 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800376
Dianne Hackborn961321f2013-02-05 17:22:41 -0800377 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700378 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700379
Christopher Tate78d2a662012-09-13 16:19:44 -0700380 IntentFilter userFilter = new IntentFilter();
381 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700382 userFilter.addAction(Intent.ACTION_USER_ADDED);
Christopher Tate78d2a662012-09-13 16:19:44 -0700383 getContext().registerReceiver(new BroadcastReceiver() {
384 @Override
385 public void onReceive(Context context, Intent intent) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700386 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
387 UserHandle.USER_OWNER);
Christopher Tate78d2a662012-09-13 16:19:44 -0700388 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700389 onUserRemoved(userHandle);
390 } else if (intent.getAction().equals(Intent.ACTION_USER_ADDED)) {
391 onProfilesChanged();
Christopher Tate06efb532012-08-24 15:29:27 -0700392 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700393 }
394 }, userFilter);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700395
396 onProfilesChanged();
397
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700398 return true;
399 }
400
Christopher Tate06efb532012-08-24 15:29:27 -0700401 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700402 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700403 // the db file itself will be deleted automatically, but we need to tear down
404 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700405 FileObserver observer = sObserverInstances.get(userHandle);
406 if (observer != null) {
407 observer.stopWatching();
408 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700409 }
Christopher Tate06efb532012-08-24 15:29:27 -0700410
411 mOpenHelpers.delete(userHandle);
412 sSystemCaches.delete(userHandle);
413 sSecureCaches.delete(userHandle);
414 sKnownMutationsInFlight.delete(userHandle);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700415 onProfilesChanged();
416 }
417 }
418
419 /**
420 * Updates the list of managed profiles. It assumes that only the primary user
421 * can have managed profiles. Modify this code if that changes in the future.
422 */
423 void onProfilesChanged() {
424 synchronized (this) {
425 mManagedProfiles = mUserManager.getProfiles(UserHandle.USER_OWNER);
426 if (mManagedProfiles != null) {
427 // Remove the primary user from the list
428 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
429 if (mManagedProfiles.get(i).id == UserHandle.USER_OWNER) {
430 mManagedProfiles.remove(i);
431 }
432 }
433 // If there are no managed profiles, reset the variable
434 if (mManagedProfiles.size() == 0) {
435 mManagedProfiles = null;
436 }
437 }
438 if (LOCAL_LOGV) {
439 Slog.d(TAG, "Managed Profiles = " + mManagedProfiles);
440 }
Christopher Tate06efb532012-08-24 15:29:27 -0700441 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700442 }
443
Christopher Tate78d2a662012-09-13 16:19:44 -0700444 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700445 if (LOCAL_LOGV) {
446 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
447 }
448
Christopher Tate78d2a662012-09-13 16:19:44 -0700449 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700450
Christopher Tate78d2a662012-09-13 16:19:44 -0700451 synchronized (this) {
452 dbhelper = mOpenHelpers.get(userHandle);
453 if (dbhelper == null) {
454 dbhelper = new DatabaseHelper(getContext(), userHandle);
455 mOpenHelpers.append(userHandle, dbhelper);
456
457 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
458 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
459 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
460 }
461 }
462
463 // Initialization of the db *outside* the locks. It's possible that racing
464 // threads might wind up here, the second having read the cache entries
465 // written by the first, but that's benign: the SQLite helper implementation
466 // manages concurrency itself, and it's important that we not run the db
467 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700468 SQLiteDatabase db = dbhelper.getWritableDatabase();
469
Christopher Tate78d2a662012-09-13 16:19:44 -0700470 // Watch for external modifications to the database files,
471 // keeping our caches in sync. We synchronize the observer set
472 // separately, and of course it has to run after the db file
473 // itself was set up by the DatabaseHelper.
474 synchronized (sObserverInstances) {
475 if (sObserverInstances.get(userHandle) == null) {
476 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
477 sObserverInstances.append(userHandle, observer);
478 observer.startWatching();
479 }
480 }
Christopher Tate06efb532012-08-24 15:29:27 -0700481
Christopher Tate4dc7a682012-09-11 12:15:49 -0700482 ensureAndroidIdIsSet(userHandle);
483
Christopher Tate06efb532012-08-24 15:29:27 -0700484 startAsyncCachePopulation(userHandle);
485 }
486
487 class CachePrefetchThread extends Thread {
488 private int mUserHandle;
489
490 CachePrefetchThread(int userHandle) {
491 super("populate-settings-caches");
492 mUserHandle = userHandle;
493 }
494
495 @Override
496 public void run() {
497 fullyPopulateCaches(mUserHandle);
498 }
499 }
500
501 private void startAsyncCachePopulation(int userHandle) {
502 new CachePrefetchThread(userHandle).start();
503 }
504
505 private void fullyPopulateCaches(final int userHandle) {
Dianne Hackborn67f175c2014-10-03 12:29:43 -0700506 DatabaseHelper dbHelper;
507 synchronized (this) {
508 dbHelper = mOpenHelpers.get(userHandle);
509 }
510 if (dbHelper == null) {
511 // User is gone.
512 return;
513 }
Christopher Tate06efb532012-08-24 15:29:27 -0700514 // Only populate the globals cache once, for the owning user
515 if (userHandle == UserHandle.USER_OWNER) {
516 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
517 }
518 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
519 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700520 }
521
522 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700523 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
524 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700525 Cursor c = db.query(
526 table,
527 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
528 null, null, null, null, null,
529 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
530 try {
531 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800532 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700533 cache.setFullyMatchesDisk(true); // optimistic
534 int rows = 0;
535 while (c.moveToNext()) {
536 rows++;
537 String name = c.getString(0);
538 String value = c.getString(1);
539 cache.populate(name, value);
540 }
541 if (rows > MAX_CACHE_ENTRIES) {
542 // Somewhat redundant, as removeEldestEntry() will
543 // have already done this, but to be explicit:
544 cache.setFullyMatchesDisk(false);
545 Log.d(TAG, "row count exceeds max cache entries for table " + table);
546 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800547 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
548 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700549 }
550 } finally {
551 c.close();
552 }
553 }
554
Christopher Tate4dc7a682012-09-11 12:15:49 -0700555 private boolean ensureAndroidIdIsSet(int userHandle) {
556 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800557 new String[] { Settings.NameValueTable.VALUE },
558 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700559 new String[] { Settings.Secure.ANDROID_ID }, null,
560 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800561 try {
562 final String value = c.moveToNext() ? c.getString(0) : null;
563 if (value == null) {
Christopher Tate38e7a602013-09-03 16:57:34 -0700564 // sanity-check the user before touching the db
565 final UserInfo user = mUserManager.getUserInfo(userHandle);
566 if (user == null) {
567 // can happen due to races when deleting users; treat as benign
568 return false;
569 }
570
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700571 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800572 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800573 final ContentValues values = new ContentValues();
574 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
575 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700576 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800577 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700578 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800579 return false;
580 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700581 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
582 + "] for user " + userHandle);
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700583 // Write a dropbox entry if it's a restricted profile
Christopher Tate38e7a602013-09-03 16:57:34 -0700584 if (user.isRestricted()) {
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700585 DropBoxManager dbm = (DropBoxManager)
586 getContext().getSystemService(Context.DROPBOX_SERVICE);
587 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
588 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
589 + ",restricted_profile_ssaid,"
590 + newAndroidIdValue + "\n");
591 }
592 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800593 }
594 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800595 } finally {
596 c.close();
597 }
598 }
599
Christopher Tate06efb532012-08-24 15:29:27 -0700600 // Lazy-initialize the settings caches for non-primary users
601 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700602 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
603 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700604 }
605
606 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700607 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate0da13572013-10-13 17:34:49 -0700608 if (callingUser >= Process.SYSTEM_UID) {
609 if (USER_CHECK_THROWS) {
610 throw new IllegalArgumentException("Uid rather than user handle: " + callingUser);
611 } else {
612 Slog.wtf(TAG, "establish db for uid rather than user: " + callingUser);
613 }
614 }
615
Christopher Tate06efb532012-08-24 15:29:27 -0700616 long oldId = Binder.clearCallingIdentity();
617 try {
Dianne Hackborn67f175c2014-10-03 12:29:43 -0700618 DatabaseHelper dbHelper;
619 synchronized (this) {
620 dbHelper = mOpenHelpers.get(callingUser);
621 }
Christopher Tate06efb532012-08-24 15:29:27 -0700622 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700623 establishDbTracking(callingUser);
Dianne Hackborn67f175c2014-10-03 12:29:43 -0700624 synchronized (this) {
625 dbHelper = mOpenHelpers.get(callingUser);
626 }
Christopher Tate06efb532012-08-24 15:29:27 -0700627 }
628 return dbHelper;
629 } finally {
630 Binder.restoreCallingIdentity(oldId);
631 }
632 }
633
634 public SettingsCache cacheForTable(final int callingUser, String tableName) {
635 if (TABLE_SYSTEM.equals(tableName)) {
636 return getOrConstructCache(callingUser, sSystemCaches);
637 }
638 if (TABLE_SECURE.equals(tableName)) {
639 return getOrConstructCache(callingUser, sSecureCaches);
640 }
641 if (TABLE_GLOBAL.equals(tableName)) {
642 return sGlobalCache;
643 }
644 return null;
645 }
646
647 /**
648 * Used for wiping a whole cache on deletes when we're not
649 * sure what exactly was deleted or changed.
650 */
651 public void invalidateCache(final int callingUser, String tableName) {
652 SettingsCache cache = cacheForTable(callingUser, tableName);
653 if (cache == null) {
654 return;
655 }
656 synchronized (cache) {
657 cache.evictAll();
658 cache.mCacheFullyMatchesDisk = false;
659 }
660 }
661
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800662 /**
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700663 * Checks if the calling user is a managed profile of the primary user.
664 * Currently only the primary user (USER_OWNER) can have managed profiles.
665 * @param callingUser the user trying to read/write settings
666 * @return true if it is a managed profile of the primary user
667 */
668 private boolean isManagedProfile(int callingUser) {
669 synchronized (this) {
670 if (mManagedProfiles == null) return false;
671 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
672 if (mManagedProfiles.get(i).id == callingUser) {
673 return true;
674 }
675 }
676 return false;
677 }
678 }
679
680 /**
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800681 * Fast path that avoids the use of chatty remoted Cursors.
682 */
683 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700684 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700685 int callingUser = UserHandle.getCallingUserId();
686 if (args != null) {
687 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
688 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700689 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
690 Binder.getCallingUid(), reqUser, false, true,
691 "get/set setting for user", null);
692 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700693 }
694 }
695
Christopher Tate61695ff2012-10-05 12:05:13 -0700696 // Note: we assume that get/put operations for moved-to-global names have already
697 // been directed to the new location on the caller side (otherwise we'd fix them
698 // up here).
699 DatabaseHelper dbHelper;
700 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700701
Christopher Tate61695ff2012-10-05 12:05:13 -0700702 // Get methods
703 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
704 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700705 // Check if this request should be (re)directed to the primary user's db
Kenny Guya37d0002014-10-01 18:35:37 +0100706 if (callingUser != UserHandle.USER_OWNER
707 && shouldShadowParentProfile(callingUser, sSystemCloneToManagedKeys, request)) {
708 callingUser = UserHandle.USER_OWNER;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700709 }
Kenny Guya37d0002014-10-01 18:35:37 +0100710 dbHelper = getOrEstablishDatabase(callingUser);
Christopher Tate61695ff2012-10-05 12:05:13 -0700711 cache = sSystemCaches.get(callingUser);
712 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
713 }
714 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
715 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700716 // Check if this is a setting to be copied from the primary user
717 if (shouldShadowParentProfile(callingUser, sSecureCloneToManagedKeys, request)) {
718 // If the request if for location providers and there's a restriction, return none
719 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(request)
720 && mUserManager.hasUserRestriction(
721 UserManager.DISALLOW_SHARE_LOCATION, new UserHandle(callingUser))) {
722 return sSecureCaches.get(callingUser).putIfAbsent(request, "");
723 }
Kenny Guya37d0002014-10-01 18:35:37 +0100724 callingUser = UserHandle.USER_OWNER;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700725 }
Kenny Guya37d0002014-10-01 18:35:37 +0100726 dbHelper = getOrEstablishDatabase(callingUser);
Christopher Tate61695ff2012-10-05 12:05:13 -0700727 cache = sSecureCaches.get(callingUser);
728 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
729 }
730 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
731 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
732 // fast path: owner db & cache are immutable after onCreate() so we need not
733 // guard on the attempt to look them up
734 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
735 sGlobalCache, request);
736 }
Christopher Tate06efb532012-08-24 15:29:27 -0700737
Christopher Tate61695ff2012-10-05 12:05:13 -0700738 // Put methods - new value is in the args bundle under the key named by
739 // the Settings.NameValueTable.VALUE static.
740 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800741 ? null : args.getString(Settings.NameValueTable.VALUE);
742
743 // Framework can't do automatic permission checking for calls, so we need
744 // to do it here.
745 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
746 != PackageManager.PERMISSION_GRANTED) {
747 throw new SecurityException(
748 String.format("Permission denial: writing to settings requires %1$s",
749 android.Manifest.permission.WRITE_SETTINGS));
750 }
751
752 // Also need to take care of app op.
753 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700754 getCallingPackage()) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn961321f2013-02-05 17:22:41 -0800755 return null;
756 }
Christopher Tate06efb532012-08-24 15:29:27 -0700757
Christopher Tate61695ff2012-10-05 12:05:13 -0700758 final ContentValues values = new ContentValues();
759 values.put(Settings.NameValueTable.NAME, request);
760 values.put(Settings.NameValueTable.VALUE, newValue);
761 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700762 if (LOCAL_LOGV) {
763 Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for "
764 + callingUser);
765 }
766 // Extra check for USER_OWNER to optimize for the 99%
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700767 if (callingUser != UserHandle.USER_OWNER && shouldShadowParentProfile(callingUser,
768 sSystemCloneToManagedKeys, request)) {
769 // Don't write these settings, as they are cloned from the parent profile
770 return null;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700771 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700772 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700773 // Clone the settings to the managed profiles so that notifications can be sent out
774 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
775 && sSystemCloneToManagedKeys.contains(request)) {
776 final long token = Binder.clearCallingIdentity();
777 try {
778 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
779 if (LOCAL_LOGV) {
780 Slog.v(TAG, "putting to additional user "
781 + mManagedProfiles.get(i).id);
782 }
783 insertForUser(Settings.System.CONTENT_URI, values,
784 mManagedProfiles.get(i).id);
785 }
786 } finally {
787 Binder.restoreCallingIdentity(token);
788 }
789 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700790 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700791 if (LOCAL_LOGV) {
792 Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for "
793 + callingUser);
794 }
795 // Extra check for USER_OWNER to optimize for the 99%
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700796 if (callingUser != UserHandle.USER_OWNER && shouldShadowParentProfile(callingUser,
797 sSecureCloneToManagedKeys, request)) {
798 // Don't write these settings, as they are cloned from the parent profile
799 return null;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700800 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700801 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700802 // Clone the settings to the managed profiles so that notifications can be sent out
803 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
804 && sSecureCloneToManagedKeys.contains(request)) {
805 final long token = Binder.clearCallingIdentity();
806 try {
807 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
808 if (LOCAL_LOGV) {
809 Slog.v(TAG, "putting to additional user "
810 + mManagedProfiles.get(i).id);
811 }
Zoltan Szatmary-Ban35349352014-09-11 11:28:20 +0100812 try {
813 insertForUser(Settings.Secure.CONTENT_URI, values,
814 mManagedProfiles.get(i).id);
815 } catch (SecurityException e) {
816 // Temporary fix, see b/17450158
817 Slog.w(TAG, "Cannot clone request '" + request + "' with value '"
818 + newValue + "' to managed profile (id "
819 + mManagedProfiles.get(i).id + ")", e);
820 }
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700821 }
822 } finally {
823 Binder.restoreCallingIdentity(token);
824 }
825 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700826 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700827 if (LOCAL_LOGV) {
828 Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for "
829 + callingUser);
830 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700831 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
832 } else {
833 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700834 }
835
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800836 return null;
837 }
838
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700839 /**
840 * Check if the user is a managed profile and name is one of the settings to be cloned
841 * from the parent profile.
842 */
843 private boolean shouldShadowParentProfile(int userId, HashSet<String> keys, String name) {
844 return isManagedProfile(userId) && keys.contains(name);
845 }
846
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800847 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
848 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700849 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
850 final SettingsCache cache, String key) {
851 if (cache == null) {
852 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
853 return null;
854 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800855 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800856 Bundle value = cache.get(key);
857 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700858 if (value != TOO_LARGE_TO_CACHE_MARKER) {
859 return value;
860 }
861 // else we fall through and read the value from disk
862 } else if (cache.fullyMatchesDisk()) {
863 // Fast path (very common). Don't even try touch disk
864 // if we know we've slurped it all in. Trying to
865 // touch the disk would mean waiting for yaffs2 to
866 // give us access, which could takes hundreds of
867 // milliseconds. And we're very likely being called
868 // from somebody's UI thread...
869 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800870 }
871 }
872
Christopher Tate06efb532012-08-24 15:29:27 -0700873 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800874 Cursor cursor = null;
875 try {
876 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
877 null, null, null, null);
878 if (cursor != null && cursor.getCount() == 1) {
879 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800880 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800881 }
882 } catch (SQLiteException e) {
883 Log.w(TAG, "settings lookup error", e);
884 return null;
885 } finally {
886 if (cursor != null) cursor.close();
887 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800888 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800889 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800890 }
891
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700892 @Override
893 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700894 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
895 }
896
Christopher Tateb7564452012-09-19 16:21:18 -0700897 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700898 String sort, int forUser) {
899 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700900 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700901 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700902 dbH = getOrEstablishDatabase(
903 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700904 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800906 // The favorites table was moved from this provider to a provider inside Home
907 // Home still need to query this table to upgrade from pre-cupcake builds
908 // However, a cupcake+ build with no data does not contain this table which will
909 // cause an exception in the SQL stack. The following line is a special case to
910 // 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 -0800911 if (TABLE_FAVORITES.equals(args.table)) {
912 return null;
913 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
914 args.table = TABLE_FAVORITES;
915 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
916 if (cursor != null) {
917 boolean exists = cursor.getCount() > 0;
918 cursor.close();
919 if (!exists) return null;
920 } else {
921 return null;
922 }
923 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800924
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700925 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
926 qb.setTables(args.table);
927
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700928 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700929 // the default Cursor interface does not support per-user observation
930 try {
931 AbstractCursor c = (AbstractCursor) ret;
932 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
933 } catch (ClassCastException e) {
934 // details of the concrete Cursor implementation have changed and this code has
935 // not been updated to match -- complain and fail hard.
936 Log.wtf(TAG, "Incompatible cursor derivation!");
937 throw e;
938 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700939 return ret;
940 }
941
942 @Override
943 public String getType(Uri url) {
944 // If SqlArguments supplies a where clause, then it must be an item
945 // (because we aren't supplying our own where clause).
946 SqlArguments args = new SqlArguments(url, null, null);
947 if (TextUtils.isEmpty(args.where)) {
948 return "vnd.android.cursor.dir/" + args.table;
949 } else {
950 return "vnd.android.cursor.item/" + args.table;
951 }
952 }
953
954 @Override
955 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700956 final int callingUser = UserHandle.getCallingUserId();
957 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700958 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 if (TABLE_FAVORITES.equals(args.table)) {
960 return 0;
961 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700962 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700963 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700964
Dianne Hackborn8d051722014-10-01 14:59:58 -0700965 final AtomicInteger mutationCount;
966 synchronized (this) {
967 mutationCount = sKnownMutationsInFlight.get(callingUser);
968 }
969 if (mutationCount != null) {
970 mutationCount.incrementAndGet();
971 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700972 DatabaseHelper dbH = getOrEstablishDatabase(
973 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700974 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700975 db.beginTransaction();
976 try {
977 int numValues = values.length;
978 for (int i = 0; i < numValues; i++) {
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400979 checkUserRestrictions(values[i].getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700980 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800981 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700982 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
983 }
984 db.setTransactionSuccessful();
985 } finally {
986 db.endTransaction();
Dianne Hackborn8d051722014-10-01 14:59:58 -0700987 if (mutationCount != null) {
988 mutationCount.decrementAndGet();
989 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700990 }
991
Christopher Tate06efb532012-08-24 15:29:27 -0700992 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700993 return values.length;
994 }
995
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700996 /*
997 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
998 * This setting contains a list of the currently enabled location providers.
999 * But helper functions in android.providers.Settings can enable or disable
1000 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001001 *
1002 * @returns whether the database needs to be updated or not, also modifying
1003 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001004 */
Maggie Benthalld2726582013-02-04 13:28:19 -05001005 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001006 String value = initialValues.getAsString(Settings.Secure.VALUE);
1007 String newProviders = null;
1008 if (value != null && value.length() > 1) {
1009 char prefix = value.charAt(0);
1010 if (prefix == '+' || prefix == '-') {
1011 // skip prefix
1012 value = value.substring(1);
1013
1014 // read list of enabled providers into "providers"
1015 String providers = "";
1016 String[] columns = {Settings.Secure.VALUE};
1017 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -05001018 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001019 if (cursor != null && cursor.getCount() == 1) {
1020 try {
1021 cursor.moveToFirst();
1022 providers = cursor.getString(0);
1023 } finally {
1024 cursor.close();
1025 }
1026 }
1027
1028 int index = providers.indexOf(value);
1029 int end = index + value.length();
1030 // check for commas to avoid matching on partial string
1031 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
1032 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
1033
1034 if (prefix == '+' && index < 0) {
1035 // append the provider to the list if not present
1036 if (providers.length() == 0) {
1037 newProviders = value;
1038 } else {
1039 newProviders = providers + ',' + value;
1040 }
1041 } else if (prefix == '-' && index >= 0) {
1042 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -04001043 // remove leading or trailing comma
1044 if (index > 0) {
1045 index--;
1046 } else if (end < providers.length()) {
1047 end++;
1048 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001049
1050 newProviders = providers.substring(0, index);
1051 if (end < providers.length()) {
1052 newProviders += providers.substring(end);
1053 }
1054 } else {
1055 // nothing changed, so no need to update the database
1056 return false;
1057 }
1058
1059 if (newProviders != null) {
1060 initialValues.put(Settings.Secure.VALUE, newProviders);
1061 }
1062 }
1063 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001064
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001065 return true;
1066 }
1067
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001068 @Override
1069 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -07001070 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
1071 }
1072
1073 // Settings.put*ForUser() always winds up here, so this is where we apply
1074 // policy around permission to write settings for other users.
1075 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
1076 final int callingUser = UserHandle.getCallingUserId();
1077 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001078 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -07001079 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1080 "Not permitted to access settings for other users");
1081 }
1082
1083 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
1084 + " by " + callingUser);
1085
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001086 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 if (TABLE_FAVORITES.equals(args.table)) {
1088 return null;
1089 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001090
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001091 // Special case LOCATION_PROVIDERS_ALLOWED.
1092 // Support enabling/disabling a single provider (using "+" or "-" prefix)
1093 String name = initialValues.getAsString(Settings.Secure.NAME);
1094 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -05001095 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001096 }
1097
Christopher Tatec221d2b2012-10-03 18:33:52 -07001098 // If this is an insert() of a key that has been migrated to the global store,
1099 // redirect the operation to that store
1100 if (name != null) {
1101 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
1102 if (!TABLE_GLOBAL.equals(args.table)) {
1103 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
1104 }
1105 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
1106 }
1107 }
1108
Christopher Tate34637e52012-10-04 15:00:00 -07001109 // Check write permissions only after determining which table the insert will touch
1110 checkWritePermissions(args);
1111
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001112 checkUserRestrictions(name, desiredUserHandle);
Julia Reynolds5e458dd2014-07-07 16:07:01 -04001113
Christopher Tate06efb532012-08-24 15:29:27 -07001114 // The global table is stored under the owner, always
1115 if (TABLE_GLOBAL.equals(args.table)) {
1116 desiredUserHandle = UserHandle.USER_OWNER;
1117 }
1118
1119 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001120 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
1121 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
1122 return Uri.withAppendedPath(url, name);
1123 }
1124
Dianne Hackborn8d051722014-10-01 14:59:58 -07001125 final AtomicInteger mutationCount;
1126 synchronized (this) {
1127 mutationCount = sKnownMutationsInFlight.get(callingUser);
1128 }
1129 if (mutationCount != null) {
1130 mutationCount.incrementAndGet();
1131 }
Christopher Tate78d2a662012-09-13 16:19:44 -07001132 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001133 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001134 final long rowId = db.insert(args.table, null, initialValues);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001135 if (mutationCount != null) {
1136 mutationCount.decrementAndGet();
1137 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001138 if (rowId <= 0) return null;
1139
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001140 SettingsCache.populate(cache, initialValues); // before we notify
1141
Christopher Tate78d2a662012-09-13 16:19:44 -07001142 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
1143 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001144 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001145 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -07001146 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001147 return url;
1148 }
1149
1150 @Override
1151 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001152 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001153 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001154 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 if (TABLE_FAVORITES.equals(args.table)) {
1156 return 0;
1157 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
1158 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001159 } else if (TABLE_GLOBAL.equals(args.table)) {
1160 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001162 checkWritePermissions(args);
1163
Dianne Hackborn8d051722014-10-01 14:59:58 -07001164 final AtomicInteger mutationCount;
1165 synchronized (this) {
1166 mutationCount = sKnownMutationsInFlight.get(callingUser);
1167 }
1168 if (mutationCount != null) {
1169 mutationCount.incrementAndGet();
1170 }
Christopher Tate78d2a662012-09-13 16:19:44 -07001171 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001172 SQLiteDatabase db = dbH.getWritableDatabase();
1173 int count = db.delete(args.table, args.where, args.args);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001174 if (mutationCount != null) {
1175 mutationCount.decrementAndGet();
1176 }
Christopher Tate06efb532012-08-24 15:29:27 -07001177 if (count > 0) {
1178 invalidateCache(callingUser, args.table); // before we notify
1179 sendNotify(url, callingUser);
1180 }
1181 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001182 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1183 return count;
1184 }
1185
1186 @Override
1187 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001188 // NOTE: update() is never called by the front-end Settings API, and updates that
1189 // wind up affecting rows in Secure that are globally shared will not have the
1190 // intended effect (the update will be invisible to the rest of the system).
1191 // This should have no practical effect, since writes to the Secure db can only
1192 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001193 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001194 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001195 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 if (TABLE_FAVORITES.equals(args.table)) {
1197 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001198 } else if (TABLE_GLOBAL.equals(args.table)) {
1199 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001201 checkWritePermissions(args);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001202 checkUserRestrictions(initialValues.getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001203
Dianne Hackborn8d051722014-10-01 14:59:58 -07001204 final AtomicInteger mutationCount;
1205 synchronized (this) {
1206 mutationCount = sKnownMutationsInFlight.get(callingUser);
1207 }
1208 if (mutationCount != null) {
1209 mutationCount.incrementAndGet();
1210 }
Christopher Tate78d2a662012-09-13 16:19:44 -07001211 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001212 SQLiteDatabase db = dbH.getWritableDatabase();
1213 int count = db.update(args.table, initialValues, args.where, args.args);
Dianne Hackborn8d051722014-10-01 14:59:58 -07001214 if (mutationCount != null) {
1215 mutationCount.decrementAndGet();
1216 }
Christopher Tate06efb532012-08-24 15:29:27 -07001217 if (count > 0) {
1218 invalidateCache(callingUser, args.table); // before we notify
1219 sendNotify(url, callingUser);
1220 }
1221 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001222 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1223 return count;
1224 }
1225
1226 @Override
1227 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Jeff Sharkey3b566b82014-11-12 10:39:56 -08001228 throw new FileNotFoundException("Direct file access no longer supported; "
1229 + "ringtone playback is available through android.media.Ringtone");
Marco Nelissen69f593c2009-07-28 09:55:04 -07001230 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001231
1232 /**
1233 * In-memory LRU Cache of system and secure settings, along with
1234 * associated helper functions to keep cache coherent with the
1235 * database.
1236 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001237 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001238
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001239 private final String mCacheName;
1240 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1241
1242 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001243 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001244 mCacheName = name;
1245 }
1246
1247 /**
1248 * Is the whole database table slurped into this cache?
1249 */
1250 public boolean fullyMatchesDisk() {
1251 synchronized (this) {
1252 return mCacheFullyMatchesDisk;
1253 }
1254 }
1255
1256 public void setFullyMatchesDisk(boolean value) {
1257 synchronized (this) {
1258 mCacheFullyMatchesDisk = value;
1259 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001260 }
1261
1262 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001263 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1264 if (evicted) {
1265 mCacheFullyMatchesDisk = false;
1266 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001267 }
1268
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001269 /**
1270 * Atomic cache population, conditional on size of value and if
1271 * we lost a race.
1272 *
1273 * @returns a Bundle to send back to the client from call(), even
1274 * if we lost the race.
1275 */
1276 public Bundle putIfAbsent(String key, String value) {
1277 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1278 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1279 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001280 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001281 put(key, bundle);
1282 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001283 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001284 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001285 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001286 }
1287
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001288 /**
1289 * Populates a key in a given (possibly-null) cache.
1290 */
1291 public static void populate(SettingsCache cache, ContentValues contentValues) {
1292 if (cache == null) {
1293 return;
1294 }
1295 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1296 if (name == null) {
1297 Log.w(TAG, "null name populating settings cache.");
1298 return;
1299 }
1300 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001301 cache.populate(name, value);
1302 }
1303
1304 public void populate(String name, String value) {
1305 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001306 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001307 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001308 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001309 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001310 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001311 }
1312 }
1313
1314 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001315 * For suppressing duplicate/redundant settings inserts early,
1316 * checking our cache first (but without faulting it in),
1317 * before going to sqlite with the mutation.
1318 */
1319 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1320 if (cache == null) return false;
1321 synchronized (cache) {
1322 Bundle bundle = cache.get(name);
1323 if (bundle == null) return false;
1324 String oldValue = bundle.getPairValue();
1325 if (oldValue == null && value == null) return true;
1326 if ((oldValue == null) != (value == null)) return false;
1327 return oldValue.equals(value);
1328 }
1329 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001330 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001331}