blob: ad35f7ff12cecc10c8e9dfdb28e5109e23441bed [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;
Christopher Tate06efb532012-08-24 15:29:27 -070021import java.util.HashSet;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070022import java.util.concurrent.atomic.AtomicBoolean;
23import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070024
Christopher Tated5fe1472012-09-10 15:48:38 -070025import android.app.ActivityManager;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070027import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentProvider;
29import android.content.ContentUris;
30import android.content.ContentValues;
31import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070032import android.content.Intent;
33import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.pm.PackageManager;
Marco Nelissen69f593c2009-07-28 09:55:04 -070035import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.Cursor;
37import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080038import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.database.sqlite.SQLiteQueryBuilder;
40import android.media.RingtoneManager;
41import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070044import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.os.ParcelFileDescriptor;
46import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070047import android.os.UserHandle;
48import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.provider.DrmStore;
50import android.provider.MediaStore;
51import android.provider.Settings;
52import android.text.TextUtils;
53import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080054import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.util.Slog;
56import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058public class SettingsProvider extends ContentProvider {
59 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070060 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061
Christopher Tate06efb532012-08-24 15:29:27 -070062 private static final String TABLE_SYSTEM = "system";
63 private static final String TABLE_SECURE = "secure";
64 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 private static final String TABLE_FAVORITES = "favorites";
66 private static final String TABLE_OLD_FAVORITES = "old_favorites";
67
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080068 private static final String[] COLUMN_VALUE = new String[] { "value" };
69
Christopher Tate06efb532012-08-24 15:29:27 -070070 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080071 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070072 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070073 private static final SparseArray<SettingsCache> sSystemCaches
74 = new SparseArray<SettingsCache>();
75 private static final SparseArray<SettingsCache> sSecureCaches
76 = new SparseArray<SettingsCache>();
77 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070078
79 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070080 // database mutations are currently being handled for this user.
81 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070083 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
84 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080085
Christopher Tate78d2a662012-09-13 16:19:44 -070086 // Each defined user has their own settings
87 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
88
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080089 // Over this size we don't reject loading or saving settings but
90 // we do consider them broken/malicious and don't keep them in
91 // memory at least:
92 private static final int MAX_CACHE_ENTRY_SIZE = 500;
93
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080094 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
95
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070096 // Used as a sentinel value in an instance equality test when we
97 // want to cache the existence of a key, but not store its value.
98 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
99
Christopher Tate06efb532012-08-24 15:29:27 -0700100 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700101 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102
103 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700104 * Settings which need to be treated as global/shared in multi-user environments.
105 */
106 static final HashSet<String> sSecureGlobalKeys;
107 static final HashSet<String> sSystemGlobalKeys;
108 static {
109 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
110 // table, shared across all users
111 // These must match Settings.Secure.MOVED_TO_GLOBAL
112 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700113 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700114
115 // Keys from the 'system' table now moved to 'global'
116 // These must match Settings.System.MOVED_TO_GLOBAL
117 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700118 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700119 }
120
121 private boolean settingMovedToGlobal(final String name) {
122 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
123 }
124
125 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700126 * Decode a content URL into the table, projection, and arguments
127 * used to access the corresponding database rows.
128 */
129 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700131 public final String where;
132 public final String[] args;
133
134 /** Operate on existing rows. */
135 SqlArguments(Uri url, String where, String[] args) {
136 if (url.getPathSegments().size() == 1) {
137 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700138 if (!DatabaseHelper.isValidTable(this.table)) {
139 throw new IllegalArgumentException("Bad root path: " + this.table);
140 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141 this.where = where;
142 this.args = args;
143 } else if (url.getPathSegments().size() != 2) {
144 throw new IllegalArgumentException("Invalid URI: " + url);
145 } else if (!TextUtils.isEmpty(where)) {
146 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
147 } else {
148 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700149 if (!DatabaseHelper.isValidTable(this.table)) {
150 throw new IllegalArgumentException("Bad root path: " + this.table);
151 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700152 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
153 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700154 this.where = Settings.NameValueTable.NAME + "=?";
155 this.args = new String[] { url.getPathSegments().get(1) };
156 } else {
157 this.where = "_id=" + ContentUris.parseId(url);
158 this.args = null;
159 }
160 }
161 }
162
163 /** Insert new rows (no where clause allowed). */
164 SqlArguments(Uri url) {
165 if (url.getPathSegments().size() == 1) {
166 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700167 if (!DatabaseHelper.isValidTable(this.table)) {
168 throw new IllegalArgumentException("Bad root path: " + this.table);
169 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700170 this.where = null;
171 this.args = null;
172 } else {
173 throw new IllegalArgumentException("Invalid URI: " + url);
174 }
175 }
176 }
177
178 /**
179 * Get the content URI of a row added to a table.
180 * @param tableUri of the entire table
181 * @param values found in the row
182 * @param rowId of the row
183 * @return the content URI for this particular row
184 */
185 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
186 if (tableUri.getPathSegments().size() != 1) {
187 throw new IllegalArgumentException("Invalid URI: " + tableUri);
188 }
189 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700190 if (TABLE_SYSTEM.equals(table) ||
191 TABLE_SECURE.equals(table) ||
192 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700193 String name = values.getAsString(Settings.NameValueTable.NAME);
194 return Uri.withAppendedPath(tableUri, name);
195 } else {
196 return ContentUris.withAppendedId(tableUri, rowId);
197 }
198 }
199
200 /**
201 * Send a notification when a particular content URI changes.
202 * Modify the system property used to communicate the version of
203 * this table, for tables which have such a property. (The Settings
204 * contract class uses these to provide client-side caches.)
205 * @param uri to send notifications for
206 */
Christopher Tate06efb532012-08-24 15:29:27 -0700207 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700208 // Update the system property *first*, so if someone is listening for
209 // a notification and then using the contract class to get their data,
210 // the system property will be updated and they'll get the new data.
211
Amith Yamasanid1582142009-07-08 20:04:55 -0700212 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700213 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700214 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700215 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700216 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700217 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700218 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700219 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700220 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700221 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700222 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700223 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700224 }
225
226 if (property != null) {
227 long version = SystemProperties.getLong(property, 0) + 1;
228 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
229 SystemProperties.set(property, Long.toString(version));
230 }
231
-b master501eec92009-07-06 13:53:11 -0700232 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700233 if (backedUpDataChanged) {
234 mBackupManager.dataChanged();
235 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700236 // Now send the notification through the content framework.
237
238 String notify = uri.getQueryParameter("notify");
239 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700240 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700241 final long oldId = Binder.clearCallingIdentity();
242 try {
243 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
244 } finally {
245 Binder.restoreCallingIdentity(oldId);
246 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700247 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 } else {
249 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
250 }
251 }
252
253 /**
254 * Make sure the caller has permission to write this data.
255 * @param args supplied by the caller
256 * @throws SecurityException if the caller is forbidden to write.
257 */
258 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700259 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800260 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800261 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
262 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700263 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800264 String.format("Permission denial: writing to secure settings requires %1$s",
265 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700266 }
267 }
268
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700269 // FileObserver for external modifications to the database file.
270 // Note that this is for platform developers only with
271 // userdebug/eng builds who should be able to tinker with the
272 // sqlite database out from under the SettingsProvider, which is
273 // normally the exclusive owner of the database. But we keep this
274 // enabled all the time to minimize development-vs-user
275 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700276 private static SparseArray<SettingsFileObserver> sObserverInstances
277 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700278 private class SettingsFileObserver extends FileObserver {
279 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700280 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700281 private final String mPath;
282
Christopher Tate06efb532012-08-24 15:29:27 -0700283 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700284 super(path, FileObserver.CLOSE_WRITE |
285 FileObserver.CREATE | FileObserver.DELETE |
286 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700287 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700288 mPath = path;
289 }
290
291 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700292 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700293 if (modsInFlight > 0) {
294 // our own modification.
295 return;
296 }
Christopher Tate06efb532012-08-24 15:29:27 -0700297 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
298 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700299 if (!mIsDirty.compareAndSet(false, true)) {
300 // already handled. (we get a few update events
301 // during an sqlite write)
302 return;
303 }
Christopher Tate06efb532012-08-24 15:29:27 -0700304 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
305 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700306 mIsDirty.set(false);
307 }
308 }
309
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 @Override
311 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700312 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700313 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800314
Christopher Tate78d2a662012-09-13 16:19:44 -0700315 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700316
Christopher Tate78d2a662012-09-13 16:19:44 -0700317 IntentFilter userFilter = new IntentFilter();
318 userFilter.addAction(Intent.ACTION_USER_REMOVED);
319 getContext().registerReceiver(new BroadcastReceiver() {
320 @Override
321 public void onReceive(Context context, Intent intent) {
322 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
323 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
324 UserHandle.USER_OWNER);
325 if (userHandle != UserHandle.USER_OWNER) {
326 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700327 }
328 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700329 }
330 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700331 return true;
332 }
333
Christopher Tate06efb532012-08-24 15:29:27 -0700334 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700335 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700336 // the db file itself will be deleted automatically, but we need to tear down
337 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700338 FileObserver observer = sObserverInstances.get(userHandle);
339 if (observer != null) {
340 observer.stopWatching();
341 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700342 }
Christopher Tate06efb532012-08-24 15:29:27 -0700343
344 mOpenHelpers.delete(userHandle);
345 sSystemCaches.delete(userHandle);
346 sSecureCaches.delete(userHandle);
347 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700348 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700349 }
350
Christopher Tate78d2a662012-09-13 16:19:44 -0700351 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700352 if (LOCAL_LOGV) {
353 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
354 }
355
Christopher Tate78d2a662012-09-13 16:19:44 -0700356 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700357
Christopher Tate78d2a662012-09-13 16:19:44 -0700358 synchronized (this) {
359 dbhelper = mOpenHelpers.get(userHandle);
360 if (dbhelper == null) {
361 dbhelper = new DatabaseHelper(getContext(), userHandle);
362 mOpenHelpers.append(userHandle, dbhelper);
363
364 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
365 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
366 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
367 }
368 }
369
370 // Initialization of the db *outside* the locks. It's possible that racing
371 // threads might wind up here, the second having read the cache entries
372 // written by the first, but that's benign: the SQLite helper implementation
373 // manages concurrency itself, and it's important that we not run the db
374 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700375 SQLiteDatabase db = dbhelper.getWritableDatabase();
376
Christopher Tate78d2a662012-09-13 16:19:44 -0700377 // Watch for external modifications to the database files,
378 // keeping our caches in sync. We synchronize the observer set
379 // separately, and of course it has to run after the db file
380 // itself was set up by the DatabaseHelper.
381 synchronized (sObserverInstances) {
382 if (sObserverInstances.get(userHandle) == null) {
383 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
384 sObserverInstances.append(userHandle, observer);
385 observer.startWatching();
386 }
387 }
Christopher Tate06efb532012-08-24 15:29:27 -0700388
Christopher Tate4dc7a682012-09-11 12:15:49 -0700389 ensureAndroidIdIsSet(userHandle);
390
Christopher Tate06efb532012-08-24 15:29:27 -0700391 startAsyncCachePopulation(userHandle);
392 }
393
394 class CachePrefetchThread extends Thread {
395 private int mUserHandle;
396
397 CachePrefetchThread(int userHandle) {
398 super("populate-settings-caches");
399 mUserHandle = userHandle;
400 }
401
402 @Override
403 public void run() {
404 fullyPopulateCaches(mUserHandle);
405 }
406 }
407
408 private void startAsyncCachePopulation(int userHandle) {
409 new CachePrefetchThread(userHandle).start();
410 }
411
412 private void fullyPopulateCaches(final int userHandle) {
413 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
414 // Only populate the globals cache once, for the owning user
415 if (userHandle == UserHandle.USER_OWNER) {
416 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
417 }
418 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
419 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700420 }
421
422 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700423 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
424 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700425 Cursor c = db.query(
426 table,
427 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
428 null, null, null, null, null,
429 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
430 try {
431 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800432 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700433 cache.setFullyMatchesDisk(true); // optimistic
434 int rows = 0;
435 while (c.moveToNext()) {
436 rows++;
437 String name = c.getString(0);
438 String value = c.getString(1);
439 cache.populate(name, value);
440 }
441 if (rows > MAX_CACHE_ENTRIES) {
442 // Somewhat redundant, as removeEldestEntry() will
443 // have already done this, but to be explicit:
444 cache.setFullyMatchesDisk(false);
445 Log.d(TAG, "row count exceeds max cache entries for table " + table);
446 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700447 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700448 cache.fullyMatchesDisk());
449 }
450 } finally {
451 c.close();
452 }
453 }
454
Christopher Tate4dc7a682012-09-11 12:15:49 -0700455 private boolean ensureAndroidIdIsSet(int userHandle) {
456 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800457 new String[] { Settings.NameValueTable.VALUE },
458 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700459 new String[] { Settings.Secure.ANDROID_ID }, null,
460 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800461 try {
462 final String value = c.moveToNext() ? c.getString(0) : null;
463 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700464 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800465 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800466 final ContentValues values = new ContentValues();
467 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
468 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700469 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800470 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700471 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800472 return false;
473 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700474 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
475 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800476 }
477 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800478 } finally {
479 c.close();
480 }
481 }
482
Christopher Tate06efb532012-08-24 15:29:27 -0700483 // Lazy-initialize the settings caches for non-primary users
484 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700485 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
486 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700487 }
488
489 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700490 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700491 long oldId = Binder.clearCallingIdentity();
492 try {
493 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
494 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700495 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700496 dbHelper = mOpenHelpers.get(callingUser);
497 }
498 return dbHelper;
499 } finally {
500 Binder.restoreCallingIdentity(oldId);
501 }
502 }
503
504 public SettingsCache cacheForTable(final int callingUser, String tableName) {
505 if (TABLE_SYSTEM.equals(tableName)) {
506 return getOrConstructCache(callingUser, sSystemCaches);
507 }
508 if (TABLE_SECURE.equals(tableName)) {
509 return getOrConstructCache(callingUser, sSecureCaches);
510 }
511 if (TABLE_GLOBAL.equals(tableName)) {
512 return sGlobalCache;
513 }
514 return null;
515 }
516
517 /**
518 * Used for wiping a whole cache on deletes when we're not
519 * sure what exactly was deleted or changed.
520 */
521 public void invalidateCache(final int callingUser, String tableName) {
522 SettingsCache cache = cacheForTable(callingUser, tableName);
523 if (cache == null) {
524 return;
525 }
526 synchronized (cache) {
527 cache.evictAll();
528 cache.mCacheFullyMatchesDisk = false;
529 }
530 }
531
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800532 /**
533 * Fast path that avoids the use of chatty remoted Cursors.
534 */
535 @Override
536 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700537 int callingUser = UserHandle.getCallingUserId();
538 if (args != null) {
539 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
540 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700541 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
542 Binder.getCallingUid(), reqUser, false, true,
543 "get/set setting for user", null);
544 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700545 }
546 }
547
Christopher Tateb7564452012-09-19 16:21:18 -0700548 // Okay, permission checks have cleared. Reset to our own identity so we can
549 // manipulate all users' data with impunity.
550 long oldId = Binder.clearCallingIdentity();
551 try {
552 // Note: we assume that get/put operations for moved-to-global names have already
553 // been directed to the new location on the caller side (otherwise we'd fix them
554 // up here).
555 DatabaseHelper dbHelper;
556 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700557
Christopher Tateb7564452012-09-19 16:21:18 -0700558 // Get methods
559 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
560 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
561 dbHelper = getOrEstablishDatabase(callingUser);
562 cache = sSystemCaches.get(callingUser);
563 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
564 }
565 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
566 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
567 dbHelper = getOrEstablishDatabase(callingUser);
568 cache = sSecureCaches.get(callingUser);
569 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
570 }
571 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
572 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
573 // fast path: owner db & cache are immutable after onCreate() so we need not
574 // guard on the attempt to look them up
575 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
576 sGlobalCache, request);
577 }
Christopher Tate06efb532012-08-24 15:29:27 -0700578
Christopher Tateb7564452012-09-19 16:21:18 -0700579 // Put methods - new value is in the args bundle under the key named by
580 // the Settings.NameValueTable.VALUE static.
581 final String newValue = (args == null)
582 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700583
Christopher Tateb7564452012-09-19 16:21:18 -0700584 final ContentValues values = new ContentValues();
585 values.put(Settings.NameValueTable.NAME, request);
586 values.put(Settings.NameValueTable.VALUE, newValue);
587 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
588 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
589 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
590 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
591 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
592 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
593 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
594 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
595 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
596 } else {
597 Slog.w(TAG, "call() with invalid method: " + method);
598 }
599 } finally {
600 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700601 }
602
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800603 return null;
604 }
605
606 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
607 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700608 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
609 final SettingsCache cache, String key) {
610 if (cache == null) {
611 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
612 return null;
613 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800614 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800615 Bundle value = cache.get(key);
616 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700617 if (value != TOO_LARGE_TO_CACHE_MARKER) {
618 return value;
619 }
620 // else we fall through and read the value from disk
621 } else if (cache.fullyMatchesDisk()) {
622 // Fast path (very common). Don't even try touch disk
623 // if we know we've slurped it all in. Trying to
624 // touch the disk would mean waiting for yaffs2 to
625 // give us access, which could takes hundreds of
626 // milliseconds. And we're very likely being called
627 // from somebody's UI thread...
628 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800629 }
630 }
631
Christopher Tate06efb532012-08-24 15:29:27 -0700632 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800633 Cursor cursor = null;
634 try {
635 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
636 null, null, null, null);
637 if (cursor != null && cursor.getCount() == 1) {
638 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800639 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800640 }
641 } catch (SQLiteException e) {
642 Log.w(TAG, "settings lookup error", e);
643 return null;
644 } finally {
645 if (cursor != null) cursor.close();
646 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800647 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800648 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800649 }
650
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700651 @Override
652 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700653 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
654 }
655
Christopher Tateb7564452012-09-19 16:21:18 -0700656 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700657 String sort, int forUser) {
658 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700659 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700660 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700661 dbH = getOrEstablishDatabase(
662 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700663 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800665 // The favorites table was moved from this provider to a provider inside Home
666 // Home still need to query this table to upgrade from pre-cupcake builds
667 // However, a cupcake+ build with no data does not contain this table which will
668 // cause an exception in the SQL stack. The following line is a special case to
669 // 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 -0800670 if (TABLE_FAVORITES.equals(args.table)) {
671 return null;
672 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
673 args.table = TABLE_FAVORITES;
674 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
675 if (cursor != null) {
676 boolean exists = cursor.getCount() > 0;
677 cursor.close();
678 if (!exists) return null;
679 } else {
680 return null;
681 }
682 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800683
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700684 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
685 qb.setTables(args.table);
686
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700687 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
688 ret.setNotificationUri(getContext().getContentResolver(), url);
689 return ret;
690 }
691
692 @Override
693 public String getType(Uri url) {
694 // If SqlArguments supplies a where clause, then it must be an item
695 // (because we aren't supplying our own where clause).
696 SqlArguments args = new SqlArguments(url, null, null);
697 if (TextUtils.isEmpty(args.where)) {
698 return "vnd.android.cursor.dir/" + args.table;
699 } else {
700 return "vnd.android.cursor.item/" + args.table;
701 }
702 }
703
704 @Override
705 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700706 final int callingUser = UserHandle.getCallingUserId();
707 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700708 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 if (TABLE_FAVORITES.equals(args.table)) {
710 return 0;
711 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700712 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700713 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714
Christopher Tate06efb532012-08-24 15:29:27 -0700715 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
716 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700717 DatabaseHelper dbH = getOrEstablishDatabase(
718 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700719 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700720 db.beginTransaction();
721 try {
722 int numValues = values.length;
723 for (int i = 0; i < numValues; i++) {
724 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800725 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700726 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
727 }
728 db.setTransactionSuccessful();
729 } finally {
730 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700731 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700732 }
733
Christopher Tate06efb532012-08-24 15:29:27 -0700734 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700735 return values.length;
736 }
737
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700738 /*
739 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
740 * This setting contains a list of the currently enabled location providers.
741 * But helper functions in android.providers.Settings can enable or disable
742 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800743 *
744 * @returns whether the database needs to be updated or not, also modifying
745 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700746 */
747 private boolean parseProviderList(Uri url, ContentValues initialValues) {
748 String value = initialValues.getAsString(Settings.Secure.VALUE);
749 String newProviders = null;
750 if (value != null && value.length() > 1) {
751 char prefix = value.charAt(0);
752 if (prefix == '+' || prefix == '-') {
753 // skip prefix
754 value = value.substring(1);
755
756 // read list of enabled providers into "providers"
757 String providers = "";
758 String[] columns = {Settings.Secure.VALUE};
759 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
760 Cursor cursor = query(url, columns, where, null, null);
761 if (cursor != null && cursor.getCount() == 1) {
762 try {
763 cursor.moveToFirst();
764 providers = cursor.getString(0);
765 } finally {
766 cursor.close();
767 }
768 }
769
770 int index = providers.indexOf(value);
771 int end = index + value.length();
772 // check for commas to avoid matching on partial string
773 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
774 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
775
776 if (prefix == '+' && index < 0) {
777 // append the provider to the list if not present
778 if (providers.length() == 0) {
779 newProviders = value;
780 } else {
781 newProviders = providers + ',' + value;
782 }
783 } else if (prefix == '-' && index >= 0) {
784 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400785 // remove leading or trailing comma
786 if (index > 0) {
787 index--;
788 } else if (end < providers.length()) {
789 end++;
790 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700791
792 newProviders = providers.substring(0, index);
793 if (end < providers.length()) {
794 newProviders += providers.substring(end);
795 }
796 } else {
797 // nothing changed, so no need to update the database
798 return false;
799 }
800
801 if (newProviders != null) {
802 initialValues.put(Settings.Secure.VALUE, newProviders);
803 }
804 }
805 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800806
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700807 return true;
808 }
809
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700810 @Override
811 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700812 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
813 }
814
815 // Settings.put*ForUser() always winds up here, so this is where we apply
816 // policy around permission to write settings for other users.
817 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
818 final int callingUser = UserHandle.getCallingUserId();
819 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700820 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700821 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
822 "Not permitted to access settings for other users");
823 }
824
825 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
826 + " by " + callingUser);
827
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700828 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 if (TABLE_FAVORITES.equals(args.table)) {
830 return null;
831 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700832 checkWritePermissions(args);
833
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700834 // Special case LOCATION_PROVIDERS_ALLOWED.
835 // Support enabling/disabling a single provider (using "+" or "-" prefix)
836 String name = initialValues.getAsString(Settings.Secure.NAME);
837 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
838 if (!parseProviderList(url, initialValues)) return null;
839 }
840
Christopher Tate06efb532012-08-24 15:29:27 -0700841 // The global table is stored under the owner, always
842 if (TABLE_GLOBAL.equals(args.table)) {
843 desiredUserHandle = UserHandle.USER_OWNER;
844 }
845
846 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800847 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
848 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
849 return Uri.withAppendedPath(url, name);
850 }
851
Christopher Tate06efb532012-08-24 15:29:27 -0700852 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
853 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700854 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700855 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700856 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700857 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700858 if (rowId <= 0) return null;
859
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800860 SettingsCache.populate(cache, initialValues); // before we notify
861
Christopher Tate78d2a662012-09-13 16:19:44 -0700862 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
863 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700864 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700865 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700866 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700867 return url;
868 }
869
870 @Override
871 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700872 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700873 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700874 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 if (TABLE_FAVORITES.equals(args.table)) {
876 return 0;
877 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
878 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700879 } else if (TABLE_GLOBAL.equals(args.table)) {
880 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700882 checkWritePermissions(args);
883
Christopher Tate06efb532012-08-24 15:29:27 -0700884 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
885 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700886 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700887 SQLiteDatabase db = dbH.getWritableDatabase();
888 int count = db.delete(args.table, args.where, args.args);
889 mutationCount.decrementAndGet();
890 if (count > 0) {
891 invalidateCache(callingUser, args.table); // before we notify
892 sendNotify(url, callingUser);
893 }
894 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700895 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
896 return count;
897 }
898
899 @Override
900 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700901 // NOTE: update() is never called by the front-end Settings API, and updates that
902 // wind up affecting rows in Secure that are globally shared will not have the
903 // intended effect (the update will be invisible to the rest of the system).
904 // This should have no practical effect, since writes to the Secure db can only
905 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700906 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700907 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700908 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 if (TABLE_FAVORITES.equals(args.table)) {
910 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700911 } else if (TABLE_GLOBAL.equals(args.table)) {
912 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700914 checkWritePermissions(args);
915
Christopher Tate06efb532012-08-24 15:29:27 -0700916 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
917 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700918 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700919 SQLiteDatabase db = dbH.getWritableDatabase();
920 int count = db.update(args.table, initialValues, args.where, args.args);
921 mutationCount.decrementAndGet();
922 if (count > 0) {
923 invalidateCache(callingUser, args.table); // before we notify
924 sendNotify(url, callingUser);
925 }
926 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700927 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
928 return count;
929 }
930
931 @Override
932 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
933
934 /*
935 * When a client attempts to openFile the default ringtone or
936 * notification setting Uri, we will proxy the call to the current
937 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700938 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700939 int ringtoneType = RingtoneManager.getDefaultType(uri);
940 // Above call returns -1 if the Uri doesn't match a default type
941 if (ringtoneType != -1) {
942 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700943
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700944 // Get the current value for the default sound
945 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700946
Marco Nelissen69f593c2009-07-28 09:55:04 -0700947 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700948 // Only proxy the openFile call to drm or media providers
949 String authority = soundUri.getAuthority();
950 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
951 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
952
953 if (isDrmAuthority) {
954 try {
955 // Check DRM access permission here, since once we
956 // do the below call the DRM will be checking our
957 // permission, not our caller's permission
958 DrmStore.enforceAccessDrmPermission(context);
959 } catch (SecurityException e) {
960 throw new FileNotFoundException(e.getMessage());
961 }
962 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700963
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700964 return context.getContentResolver().openFileDescriptor(soundUri, mode);
965 }
966 }
967 }
968
969 return super.openFile(uri, mode);
970 }
Marco Nelissen69f593c2009-07-28 09:55:04 -0700971
972 @Override
973 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
974
975 /*
976 * When a client attempts to openFile the default ringtone or
977 * notification setting Uri, we will proxy the call to the current
978 * default ringtone's Uri (if it is in the DRM or media provider).
979 */
980 int ringtoneType = RingtoneManager.getDefaultType(uri);
981 // Above call returns -1 if the Uri doesn't match a default type
982 if (ringtoneType != -1) {
983 Context context = getContext();
984
985 // Get the current value for the default sound
986 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
987
988 if (soundUri != null) {
989 // Only proxy the openFile call to drm or media providers
990 String authority = soundUri.getAuthority();
991 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
992 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
993
994 if (isDrmAuthority) {
995 try {
996 // Check DRM access permission here, since once we
997 // do the below call the DRM will be checking our
998 // permission, not our caller's permission
999 DrmStore.enforceAccessDrmPermission(context);
1000 } catch (SecurityException e) {
1001 throw new FileNotFoundException(e.getMessage());
1002 }
1003 }
1004
1005 ParcelFileDescriptor pfd = null;
1006 try {
1007 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1008 return new AssetFileDescriptor(pfd, 0, -1);
1009 } catch (FileNotFoundException ex) {
1010 // fall through and open the fallback ringtone below
1011 }
1012 }
1013
1014 try {
1015 return super.openAssetFile(soundUri, mode);
1016 } catch (FileNotFoundException ex) {
1017 // Since a non-null Uri was specified, but couldn't be opened,
1018 // fall back to the built-in ringtone.
1019 return context.getResources().openRawResourceFd(
1020 com.android.internal.R.raw.fallbackring);
1021 }
1022 }
1023 // no need to fall through and have openFile() try again, since we
1024 // already know that will fail.
1025 throw new FileNotFoundException(); // or return null ?
1026 }
1027
1028 // Note that this will end up calling openFile() above.
1029 return super.openAssetFile(uri, mode);
1030 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001031
1032 /**
1033 * In-memory LRU Cache of system and secure settings, along with
1034 * associated helper functions to keep cache coherent with the
1035 * database.
1036 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001037 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001038
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001039 private final String mCacheName;
1040 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1041
1042 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001043 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001044 mCacheName = name;
1045 }
1046
1047 /**
1048 * Is the whole database table slurped into this cache?
1049 */
1050 public boolean fullyMatchesDisk() {
1051 synchronized (this) {
1052 return mCacheFullyMatchesDisk;
1053 }
1054 }
1055
1056 public void setFullyMatchesDisk(boolean value) {
1057 synchronized (this) {
1058 mCacheFullyMatchesDisk = value;
1059 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001060 }
1061
1062 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001063 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1064 if (evicted) {
1065 mCacheFullyMatchesDisk = false;
1066 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001067 }
1068
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001069 /**
1070 * Atomic cache population, conditional on size of value and if
1071 * we lost a race.
1072 *
1073 * @returns a Bundle to send back to the client from call(), even
1074 * if we lost the race.
1075 */
1076 public Bundle putIfAbsent(String key, String value) {
1077 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1078 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1079 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001080 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001081 put(key, bundle);
1082 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001083 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001084 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001085 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001086 }
1087
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001088 /**
1089 * Populates a key in a given (possibly-null) cache.
1090 */
1091 public static void populate(SettingsCache cache, ContentValues contentValues) {
1092 if (cache == null) {
1093 return;
1094 }
1095 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1096 if (name == null) {
1097 Log.w(TAG, "null name populating settings cache.");
1098 return;
1099 }
1100 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001101 cache.populate(name, value);
1102 }
1103
1104 public void populate(String name, String value) {
1105 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001106 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001107 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001108 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001109 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001110 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001111 }
1112 }
1113
1114 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001115 * For suppressing duplicate/redundant settings inserts early,
1116 * checking our cache first (but without faulting it in),
1117 * before going to sqlite with the mutation.
1118 */
1119 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1120 if (cache == null) return false;
1121 synchronized (cache) {
1122 Bundle bundle = cache.get(name);
1123 if (bundle == null) return false;
1124 String oldValue = bundle.getPairValue();
1125 if (oldValue == null && value == null) return true;
1126 if ((oldValue == null) != (value == null)) return false;
1127 return oldValue.equals(value);
1128 }
1129 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001130 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001131}