blob: ba5d11df3eb2ede0457121e48daf858fd566f3c0 [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) {
Christopher Tate06efb532012-08-24 15:29:27 -0700354 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700355 if (modsInFlight > 0) {
356 // 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) {
506 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
507 // Only populate the globals cache once, for the owning user
508 if (userHandle == UserHandle.USER_OWNER) {
509 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
510 }
511 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
512 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700513 }
514
515 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700516 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
517 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700518 Cursor c = db.query(
519 table,
520 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
521 null, null, null, null, null,
522 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
523 try {
524 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800525 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700526 cache.setFullyMatchesDisk(true); // optimistic
527 int rows = 0;
528 while (c.moveToNext()) {
529 rows++;
530 String name = c.getString(0);
531 String value = c.getString(1);
532 cache.populate(name, value);
533 }
534 if (rows > MAX_CACHE_ENTRIES) {
535 // Somewhat redundant, as removeEldestEntry() will
536 // have already done this, but to be explicit:
537 cache.setFullyMatchesDisk(false);
538 Log.d(TAG, "row count exceeds max cache entries for table " + table);
539 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800540 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
541 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700542 }
543 } finally {
544 c.close();
545 }
546 }
547
Christopher Tate4dc7a682012-09-11 12:15:49 -0700548 private boolean ensureAndroidIdIsSet(int userHandle) {
549 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800550 new String[] { Settings.NameValueTable.VALUE },
551 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700552 new String[] { Settings.Secure.ANDROID_ID }, null,
553 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800554 try {
555 final String value = c.moveToNext() ? c.getString(0) : null;
556 if (value == null) {
Christopher Tate38e7a602013-09-03 16:57:34 -0700557 // sanity-check the user before touching the db
558 final UserInfo user = mUserManager.getUserInfo(userHandle);
559 if (user == null) {
560 // can happen due to races when deleting users; treat as benign
561 return false;
562 }
563
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700564 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800565 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800566 final ContentValues values = new ContentValues();
567 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
568 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700569 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800570 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700571 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800572 return false;
573 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700574 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
575 + "] for user " + userHandle);
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700576 // Write a dropbox entry if it's a restricted profile
Christopher Tate38e7a602013-09-03 16:57:34 -0700577 if (user.isRestricted()) {
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700578 DropBoxManager dbm = (DropBoxManager)
579 getContext().getSystemService(Context.DROPBOX_SERVICE);
580 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
581 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
582 + ",restricted_profile_ssaid,"
583 + newAndroidIdValue + "\n");
584 }
585 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800586 }
587 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800588 } finally {
589 c.close();
590 }
591 }
592
Christopher Tate06efb532012-08-24 15:29:27 -0700593 // Lazy-initialize the settings caches for non-primary users
594 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700595 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
596 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700597 }
598
599 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700600 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate0da13572013-10-13 17:34:49 -0700601 if (callingUser >= Process.SYSTEM_UID) {
602 if (USER_CHECK_THROWS) {
603 throw new IllegalArgumentException("Uid rather than user handle: " + callingUser);
604 } else {
605 Slog.wtf(TAG, "establish db for uid rather than user: " + callingUser);
606 }
607 }
608
Christopher Tate06efb532012-08-24 15:29:27 -0700609 long oldId = Binder.clearCallingIdentity();
610 try {
611 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
612 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700613 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700614 dbHelper = mOpenHelpers.get(callingUser);
615 }
616 return dbHelper;
617 } finally {
618 Binder.restoreCallingIdentity(oldId);
619 }
620 }
621
622 public SettingsCache cacheForTable(final int callingUser, String tableName) {
623 if (TABLE_SYSTEM.equals(tableName)) {
624 return getOrConstructCache(callingUser, sSystemCaches);
625 }
626 if (TABLE_SECURE.equals(tableName)) {
627 return getOrConstructCache(callingUser, sSecureCaches);
628 }
629 if (TABLE_GLOBAL.equals(tableName)) {
630 return sGlobalCache;
631 }
632 return null;
633 }
634
635 /**
636 * Used for wiping a whole cache on deletes when we're not
637 * sure what exactly was deleted or changed.
638 */
639 public void invalidateCache(final int callingUser, String tableName) {
640 SettingsCache cache = cacheForTable(callingUser, tableName);
641 if (cache == null) {
642 return;
643 }
644 synchronized (cache) {
645 cache.evictAll();
646 cache.mCacheFullyMatchesDisk = false;
647 }
648 }
649
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800650 /**
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700651 * Checks if the calling user is a managed profile of the primary user.
652 * Currently only the primary user (USER_OWNER) can have managed profiles.
653 * @param callingUser the user trying to read/write settings
654 * @return true if it is a managed profile of the primary user
655 */
656 private boolean isManagedProfile(int callingUser) {
657 synchronized (this) {
658 if (mManagedProfiles == null) return false;
659 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
660 if (mManagedProfiles.get(i).id == callingUser) {
661 return true;
662 }
663 }
664 return false;
665 }
666 }
667
668 /**
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800669 * Fast path that avoids the use of chatty remoted Cursors.
670 */
671 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700672 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700673 int callingUser = UserHandle.getCallingUserId();
674 if (args != null) {
675 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
676 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700677 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
678 Binder.getCallingUid(), reqUser, false, true,
679 "get/set setting for user", null);
680 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700681 }
682 }
683
Christopher Tate61695ff2012-10-05 12:05:13 -0700684 // Note: we assume that get/put operations for moved-to-global names have already
685 // been directed to the new location on the caller side (otherwise we'd fix them
686 // up here).
687 DatabaseHelper dbHelper;
688 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700689
Christopher Tate61695ff2012-10-05 12:05:13 -0700690 // Get methods
691 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
692 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700693 // Check if this request should be (re)directed to the primary user's db
694 if (callingUser == UserHandle.USER_OWNER
695 || shouldShadowParentProfile(callingUser, sSystemCloneToManagedKeys, request)) {
696 dbHelper = getOrEstablishDatabase(UserHandle.USER_OWNER);
697 } else {
698 dbHelper = getOrEstablishDatabase(callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700699 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700700 cache = sSystemCaches.get(callingUser);
701 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
702 }
703 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
704 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700705 // Check if this is a setting to be copied from the primary user
706 if (shouldShadowParentProfile(callingUser, sSecureCloneToManagedKeys, request)) {
707 // If the request if for location providers and there's a restriction, return none
708 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(request)
709 && mUserManager.hasUserRestriction(
710 UserManager.DISALLOW_SHARE_LOCATION, new UserHandle(callingUser))) {
711 return sSecureCaches.get(callingUser).putIfAbsent(request, "");
712 }
713 dbHelper = getOrEstablishDatabase(UserHandle.USER_OWNER);
714 } else {
715 dbHelper = getOrEstablishDatabase(callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700716 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700717 cache = sSecureCaches.get(callingUser);
718 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
719 }
720 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
721 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
722 // fast path: owner db & cache are immutable after onCreate() so we need not
723 // guard on the attempt to look them up
724 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
725 sGlobalCache, request);
726 }
Christopher Tate06efb532012-08-24 15:29:27 -0700727
Christopher Tate61695ff2012-10-05 12:05:13 -0700728 // Put methods - new value is in the args bundle under the key named by
729 // the Settings.NameValueTable.VALUE static.
730 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800731 ? null : args.getString(Settings.NameValueTable.VALUE);
732
733 // Framework can't do automatic permission checking for calls, so we need
734 // to do it here.
735 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
736 != PackageManager.PERMISSION_GRANTED) {
737 throw new SecurityException(
738 String.format("Permission denial: writing to settings requires %1$s",
739 android.Manifest.permission.WRITE_SETTINGS));
740 }
741
742 // Also need to take care of app op.
743 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700744 getCallingPackage()) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn961321f2013-02-05 17:22:41 -0800745 return null;
746 }
Christopher Tate06efb532012-08-24 15:29:27 -0700747
Christopher Tate61695ff2012-10-05 12:05:13 -0700748 final ContentValues values = new ContentValues();
749 values.put(Settings.NameValueTable.NAME, request);
750 values.put(Settings.NameValueTable.VALUE, newValue);
751 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700752 if (LOCAL_LOGV) {
753 Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for "
754 + callingUser);
755 }
756 // Extra check for USER_OWNER to optimize for the 99%
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700757 if (callingUser != UserHandle.USER_OWNER && shouldShadowParentProfile(callingUser,
758 sSystemCloneToManagedKeys, request)) {
759 // Don't write these settings, as they are cloned from the parent profile
760 return null;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700761 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700762 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700763 // Clone the settings to the managed profiles so that notifications can be sent out
764 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
765 && sSystemCloneToManagedKeys.contains(request)) {
766 final long token = Binder.clearCallingIdentity();
767 try {
768 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
769 if (LOCAL_LOGV) {
770 Slog.v(TAG, "putting to additional user "
771 + mManagedProfiles.get(i).id);
772 }
773 insertForUser(Settings.System.CONTENT_URI, values,
774 mManagedProfiles.get(i).id);
775 }
776 } finally {
777 Binder.restoreCallingIdentity(token);
778 }
779 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700780 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700781 if (LOCAL_LOGV) {
782 Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for "
783 + callingUser);
784 }
785 // Extra check for USER_OWNER to optimize for the 99%
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700786 if (callingUser != UserHandle.USER_OWNER && shouldShadowParentProfile(callingUser,
787 sSecureCloneToManagedKeys, request)) {
788 // Don't write these settings, as they are cloned from the parent profile
789 return null;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700790 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700791 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700792 // Clone the settings to the managed profiles so that notifications can be sent out
793 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
794 && sSecureCloneToManagedKeys.contains(request)) {
795 final long token = Binder.clearCallingIdentity();
796 try {
797 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
798 if (LOCAL_LOGV) {
799 Slog.v(TAG, "putting to additional user "
800 + mManagedProfiles.get(i).id);
801 }
Zoltan Szatmary-Ban35349352014-09-11 11:28:20 +0100802 try {
803 insertForUser(Settings.Secure.CONTENT_URI, values,
804 mManagedProfiles.get(i).id);
805 } catch (SecurityException e) {
806 // Temporary fix, see b/17450158
807 Slog.w(TAG, "Cannot clone request '" + request + "' with value '"
808 + newValue + "' to managed profile (id "
809 + mManagedProfiles.get(i).id + ")", e);
810 }
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700811 }
812 } finally {
813 Binder.restoreCallingIdentity(token);
814 }
815 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700816 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700817 if (LOCAL_LOGV) {
818 Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for "
819 + callingUser);
820 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700821 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
822 } else {
823 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700824 }
825
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800826 return null;
827 }
828
Amith Yamasaniccc7cb92014-09-23 11:32:34 -0700829 /**
830 * Check if the user is a managed profile and name is one of the settings to be cloned
831 * from the parent profile.
832 */
833 private boolean shouldShadowParentProfile(int userId, HashSet<String> keys, String name) {
834 return isManagedProfile(userId) && keys.contains(name);
835 }
836
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800837 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
838 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700839 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
840 final SettingsCache cache, String key) {
841 if (cache == null) {
842 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
843 return null;
844 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800845 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800846 Bundle value = cache.get(key);
847 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700848 if (value != TOO_LARGE_TO_CACHE_MARKER) {
849 return value;
850 }
851 // else we fall through and read the value from disk
852 } else if (cache.fullyMatchesDisk()) {
853 // Fast path (very common). Don't even try touch disk
854 // if we know we've slurped it all in. Trying to
855 // touch the disk would mean waiting for yaffs2 to
856 // give us access, which could takes hundreds of
857 // milliseconds. And we're very likely being called
858 // from somebody's UI thread...
859 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800860 }
861 }
862
Christopher Tate06efb532012-08-24 15:29:27 -0700863 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800864 Cursor cursor = null;
865 try {
866 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
867 null, null, null, null);
868 if (cursor != null && cursor.getCount() == 1) {
869 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800870 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800871 }
872 } catch (SQLiteException e) {
873 Log.w(TAG, "settings lookup error", e);
874 return null;
875 } finally {
876 if (cursor != null) cursor.close();
877 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800878 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800879 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800880 }
881
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700882 @Override
883 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700884 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
885 }
886
Christopher Tateb7564452012-09-19 16:21:18 -0700887 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700888 String sort, int forUser) {
889 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700890 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700891 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700892 dbH = getOrEstablishDatabase(
893 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700894 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800896 // The favorites table was moved from this provider to a provider inside Home
897 // Home still need to query this table to upgrade from pre-cupcake builds
898 // However, a cupcake+ build with no data does not contain this table which will
899 // cause an exception in the SQL stack. The following line is a special case to
900 // 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 -0800901 if (TABLE_FAVORITES.equals(args.table)) {
902 return null;
903 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
904 args.table = TABLE_FAVORITES;
905 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
906 if (cursor != null) {
907 boolean exists = cursor.getCount() > 0;
908 cursor.close();
909 if (!exists) return null;
910 } else {
911 return null;
912 }
913 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800914
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700915 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
916 qb.setTables(args.table);
917
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700918 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700919 // the default Cursor interface does not support per-user observation
920 try {
921 AbstractCursor c = (AbstractCursor) ret;
922 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
923 } catch (ClassCastException e) {
924 // details of the concrete Cursor implementation have changed and this code has
925 // not been updated to match -- complain and fail hard.
926 Log.wtf(TAG, "Incompatible cursor derivation!");
927 throw e;
928 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700929 return ret;
930 }
931
932 @Override
933 public String getType(Uri url) {
934 // If SqlArguments supplies a where clause, then it must be an item
935 // (because we aren't supplying our own where clause).
936 SqlArguments args = new SqlArguments(url, null, null);
937 if (TextUtils.isEmpty(args.where)) {
938 return "vnd.android.cursor.dir/" + args.table;
939 } else {
940 return "vnd.android.cursor.item/" + args.table;
941 }
942 }
943
944 @Override
945 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700946 final int callingUser = UserHandle.getCallingUserId();
947 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700948 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 if (TABLE_FAVORITES.equals(args.table)) {
950 return 0;
951 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700952 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700953 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700954
Christopher Tate06efb532012-08-24 15:29:27 -0700955 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
956 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700957 DatabaseHelper dbH = getOrEstablishDatabase(
958 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700959 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700960 db.beginTransaction();
961 try {
962 int numValues = values.length;
963 for (int i = 0; i < numValues; i++) {
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400964 checkUserRestrictions(values[i].getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800966 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700967 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
968 }
969 db.setTransactionSuccessful();
970 } finally {
971 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700972 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700973 }
974
Christopher Tate06efb532012-08-24 15:29:27 -0700975 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700976 return values.length;
977 }
978
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700979 /*
980 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
981 * This setting contains a list of the currently enabled location providers.
982 * But helper functions in android.providers.Settings can enable or disable
983 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800984 *
985 * @returns whether the database needs to be updated or not, also modifying
986 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700987 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500988 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700989 String value = initialValues.getAsString(Settings.Secure.VALUE);
990 String newProviders = null;
991 if (value != null && value.length() > 1) {
992 char prefix = value.charAt(0);
993 if (prefix == '+' || prefix == '-') {
994 // skip prefix
995 value = value.substring(1);
996
997 // read list of enabled providers into "providers"
998 String providers = "";
999 String[] columns = {Settings.Secure.VALUE};
1000 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -05001001 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001002 if (cursor != null && cursor.getCount() == 1) {
1003 try {
1004 cursor.moveToFirst();
1005 providers = cursor.getString(0);
1006 } finally {
1007 cursor.close();
1008 }
1009 }
1010
1011 int index = providers.indexOf(value);
1012 int end = index + value.length();
1013 // check for commas to avoid matching on partial string
1014 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
1015 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
1016
1017 if (prefix == '+' && index < 0) {
1018 // append the provider to the list if not present
1019 if (providers.length() == 0) {
1020 newProviders = value;
1021 } else {
1022 newProviders = providers + ',' + value;
1023 }
1024 } else if (prefix == '-' && index >= 0) {
1025 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -04001026 // remove leading or trailing comma
1027 if (index > 0) {
1028 index--;
1029 } else if (end < providers.length()) {
1030 end++;
1031 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001032
1033 newProviders = providers.substring(0, index);
1034 if (end < providers.length()) {
1035 newProviders += providers.substring(end);
1036 }
1037 } else {
1038 // nothing changed, so no need to update the database
1039 return false;
1040 }
1041
1042 if (newProviders != null) {
1043 initialValues.put(Settings.Secure.VALUE, newProviders);
1044 }
1045 }
1046 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001047
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001048 return true;
1049 }
1050
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001051 @Override
1052 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -07001053 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
1054 }
1055
1056 // Settings.put*ForUser() always winds up here, so this is where we apply
1057 // policy around permission to write settings for other users.
1058 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
1059 final int callingUser = UserHandle.getCallingUserId();
1060 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001061 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -07001062 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1063 "Not permitted to access settings for other users");
1064 }
1065
1066 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
1067 + " by " + callingUser);
1068
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001069 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 if (TABLE_FAVORITES.equals(args.table)) {
1071 return null;
1072 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001073
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001074 // Special case LOCATION_PROVIDERS_ALLOWED.
1075 // Support enabling/disabling a single provider (using "+" or "-" prefix)
1076 String name = initialValues.getAsString(Settings.Secure.NAME);
1077 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -05001078 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001079 }
1080
Christopher Tatec221d2b2012-10-03 18:33:52 -07001081 // If this is an insert() of a key that has been migrated to the global store,
1082 // redirect the operation to that store
1083 if (name != null) {
1084 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
1085 if (!TABLE_GLOBAL.equals(args.table)) {
1086 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
1087 }
1088 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
1089 }
1090 }
1091
Christopher Tate34637e52012-10-04 15:00:00 -07001092 // Check write permissions only after determining which table the insert will touch
1093 checkWritePermissions(args);
1094
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001095 checkUserRestrictions(name, desiredUserHandle);
Julia Reynolds5e458dd2014-07-07 16:07:01 -04001096
Christopher Tate06efb532012-08-24 15:29:27 -07001097 // The global table is stored under the owner, always
1098 if (TABLE_GLOBAL.equals(args.table)) {
1099 desiredUserHandle = UserHandle.USER_OWNER;
1100 }
1101
1102 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001103 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
1104 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
1105 return Uri.withAppendedPath(url, name);
1106 }
1107
Christopher Tate06efb532012-08-24 15:29:27 -07001108 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
1109 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001110 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001111 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001112 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -07001113 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001114 if (rowId <= 0) return null;
1115
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001116 SettingsCache.populate(cache, initialValues); // before we notify
1117
Christopher Tate78d2a662012-09-13 16:19:44 -07001118 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
1119 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001120 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001121 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -07001122 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001123 return url;
1124 }
1125
1126 @Override
1127 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001128 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001129 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001130 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 if (TABLE_FAVORITES.equals(args.table)) {
1132 return 0;
1133 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
1134 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001135 } else if (TABLE_GLOBAL.equals(args.table)) {
1136 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001138 checkWritePermissions(args);
1139
Christopher Tate06efb532012-08-24 15:29:27 -07001140 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1141 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001142 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001143 SQLiteDatabase db = dbH.getWritableDatabase();
1144 int count = db.delete(args.table, args.where, args.args);
1145 mutationCount.decrementAndGet();
1146 if (count > 0) {
1147 invalidateCache(callingUser, args.table); // before we notify
1148 sendNotify(url, callingUser);
1149 }
1150 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001151 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1152 return count;
1153 }
1154
1155 @Override
1156 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001157 // NOTE: update() is never called by the front-end Settings API, and updates that
1158 // wind up affecting rows in Secure that are globally shared will not have the
1159 // intended effect (the update will be invisible to the rest of the system).
1160 // This should have no practical effect, since writes to the Secure db can only
1161 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001162 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001163 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001164 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 if (TABLE_FAVORITES.equals(args.table)) {
1166 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001167 } else if (TABLE_GLOBAL.equals(args.table)) {
1168 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001170 checkWritePermissions(args);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001171 checkUserRestrictions(initialValues.getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001172
Christopher Tate06efb532012-08-24 15:29:27 -07001173 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1174 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001175 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001176 SQLiteDatabase db = dbH.getWritableDatabase();
1177 int count = db.update(args.table, initialValues, args.where, args.args);
1178 mutationCount.decrementAndGet();
1179 if (count > 0) {
1180 invalidateCache(callingUser, args.table); // before we notify
1181 sendNotify(url, callingUser);
1182 }
1183 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001184 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1185 return count;
1186 }
1187
1188 @Override
1189 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1190
1191 /*
1192 * When a client attempts to openFile the default ringtone or
1193 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001194 * default ringtone's Uri (if it is in the media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001195 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001196 int ringtoneType = RingtoneManager.getDefaultType(uri);
1197 // Above call returns -1 if the Uri doesn't match a default type
1198 if (ringtoneType != -1) {
1199 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001200
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001201 // Get the current value for the default sound
1202 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001203
Marco Nelissen69f593c2009-07-28 09:55:04 -07001204 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001205 // Proxy the openFile call to media provider
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001206 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001207 if (authority.equals(MediaStore.AUTHORITY)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001208 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1209 }
1210 }
1211 }
1212
1213 return super.openFile(uri, mode);
1214 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001215
1216 @Override
1217 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1218
1219 /*
1220 * When a client attempts to openFile the default ringtone or
1221 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001222 * default ringtone's Uri (if it is in the media provider).
Marco Nelissen69f593c2009-07-28 09:55:04 -07001223 */
1224 int ringtoneType = RingtoneManager.getDefaultType(uri);
1225 // Above call returns -1 if the Uri doesn't match a default type
1226 if (ringtoneType != -1) {
1227 Context context = getContext();
1228
1229 // Get the current value for the default sound
1230 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1231
1232 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001233 // Proxy the openFile call to media provider
Marco Nelissen69f593c2009-07-28 09:55:04 -07001234 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001235 if (authority.equals(MediaStore.AUTHORITY)) {
Marco Nelissen69f593c2009-07-28 09:55:04 -07001236 ParcelFileDescriptor pfd = null;
1237 try {
1238 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1239 return new AssetFileDescriptor(pfd, 0, -1);
1240 } catch (FileNotFoundException ex) {
1241 // fall through and open the fallback ringtone below
1242 }
1243 }
1244
1245 try {
1246 return super.openAssetFile(soundUri, mode);
1247 } catch (FileNotFoundException ex) {
1248 // Since a non-null Uri was specified, but couldn't be opened,
1249 // fall back to the built-in ringtone.
1250 return context.getResources().openRawResourceFd(
1251 com.android.internal.R.raw.fallbackring);
1252 }
1253 }
1254 // no need to fall through and have openFile() try again, since we
1255 // already know that will fail.
1256 throw new FileNotFoundException(); // or return null ?
1257 }
1258
1259 // Note that this will end up calling openFile() above.
1260 return super.openAssetFile(uri, mode);
1261 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001262
1263 /**
1264 * In-memory LRU Cache of system and secure settings, along with
1265 * associated helper functions to keep cache coherent with the
1266 * database.
1267 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001268 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001269
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001270 private final String mCacheName;
1271 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1272
1273 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001274 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001275 mCacheName = name;
1276 }
1277
1278 /**
1279 * Is the whole database table slurped into this cache?
1280 */
1281 public boolean fullyMatchesDisk() {
1282 synchronized (this) {
1283 return mCacheFullyMatchesDisk;
1284 }
1285 }
1286
1287 public void setFullyMatchesDisk(boolean value) {
1288 synchronized (this) {
1289 mCacheFullyMatchesDisk = value;
1290 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001291 }
1292
1293 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001294 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1295 if (evicted) {
1296 mCacheFullyMatchesDisk = false;
1297 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001298 }
1299
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001300 /**
1301 * Atomic cache population, conditional on size of value and if
1302 * we lost a race.
1303 *
1304 * @returns a Bundle to send back to the client from call(), even
1305 * if we lost the race.
1306 */
1307 public Bundle putIfAbsent(String key, String value) {
1308 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1309 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1310 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001311 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001312 put(key, bundle);
1313 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001314 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001315 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001316 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001317 }
1318
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001319 /**
1320 * Populates a key in a given (possibly-null) cache.
1321 */
1322 public static void populate(SettingsCache cache, ContentValues contentValues) {
1323 if (cache == null) {
1324 return;
1325 }
1326 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1327 if (name == null) {
1328 Log.w(TAG, "null name populating settings cache.");
1329 return;
1330 }
1331 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001332 cache.populate(name, value);
1333 }
1334
1335 public void populate(String name, String value) {
1336 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001337 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001338 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001339 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001340 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001341 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001342 }
1343 }
1344
1345 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001346 * For suppressing duplicate/redundant settings inserts early,
1347 * checking our cache first (but without faulting it in),
1348 * before going to sqlite with the mutation.
1349 */
1350 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1351 if (cache == null) return false;
1352 synchronized (cache) {
1353 Bundle bundle = cache.get(name);
1354 if (bundle == null) return false;
1355 String oldValue = bundle.getPairValue();
1356 if (oldValue == null && value == null) return true;
1357 if ((oldValue == null) != (value == null)) return false;
1358 return oldValue.equals(value);
1359 }
1360 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001361 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001362}