blob: c42272b9af6ff77bb934cc8c8684cbbb93dd4bdb [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;
Christopher Tateafccaa82012-10-03 17:41:51 -070036import android.database.AbstractCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080039import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteQueryBuilder;
41import android.media.RingtoneManager;
42import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070043import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070045import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070046import android.os.ParcelFileDescriptor;
47import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070048import android.os.UserHandle;
49import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.provider.DrmStore;
51import android.provider.MediaStore;
52import android.provider.Settings;
53import android.text.TextUtils;
54import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080055import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070056import android.util.Slog;
57import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059public class SettingsProvider extends ContentProvider {
60 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070061 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062
Christopher Tate06efb532012-08-24 15:29:27 -070063 private static final String TABLE_SYSTEM = "system";
64 private static final String TABLE_SECURE = "secure";
65 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 private static final String TABLE_FAVORITES = "favorites";
67 private static final String TABLE_OLD_FAVORITES = "old_favorites";
68
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080069 private static final String[] COLUMN_VALUE = new String[] { "value" };
70
Christopher Tate06efb532012-08-24 15:29:27 -070071 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080072 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070073 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070074 private static final SparseArray<SettingsCache> sSystemCaches
75 = new SparseArray<SettingsCache>();
76 private static final SparseArray<SettingsCache> sSecureCaches
77 = new SparseArray<SettingsCache>();
78 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070079
80 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070081 // database mutations are currently being handled for this user.
82 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070083 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070084 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
85 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080086
Christopher Tate78d2a662012-09-13 16:19:44 -070087 // Each defined user has their own settings
88 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
89
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080090 // Over this size we don't reject loading or saving settings but
91 // we do consider them broken/malicious and don't keep them in
92 // memory at least:
93 private static final int MAX_CACHE_ENTRY_SIZE = 500;
94
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080095 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
96
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070097 // Used as a sentinel value in an instance equality test when we
98 // want to cache the existence of a key, but not store its value.
99 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
100
Christopher Tate06efb532012-08-24 15:29:27 -0700101 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700102 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700103
104 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700105 * Settings which need to be treated as global/shared in multi-user environments.
106 */
107 static final HashSet<String> sSecureGlobalKeys;
108 static final HashSet<String> sSystemGlobalKeys;
109 static {
110 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
111 // table, shared across all users
112 // These must match Settings.Secure.MOVED_TO_GLOBAL
113 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700114 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700115
116 // Keys from the 'system' table now moved to 'global'
117 // These must match Settings.System.MOVED_TO_GLOBAL
118 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700119 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700120 }
121
122 private boolean settingMovedToGlobal(final String name) {
123 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
124 }
125
126 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700127 * Decode a content URL into the table, projection, and arguments
128 * used to access the corresponding database rows.
129 */
130 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700132 public final String where;
133 public final String[] args;
134
135 /** Operate on existing rows. */
136 SqlArguments(Uri url, String where, String[] args) {
137 if (url.getPathSegments().size() == 1) {
138 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700139 if (!DatabaseHelper.isValidTable(this.table)) {
140 throw new IllegalArgumentException("Bad root path: " + this.table);
141 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142 this.where = where;
143 this.args = args;
144 } else if (url.getPathSegments().size() != 2) {
145 throw new IllegalArgumentException("Invalid URI: " + url);
146 } else if (!TextUtils.isEmpty(where)) {
147 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
148 } else {
149 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700150 if (!DatabaseHelper.isValidTable(this.table)) {
151 throw new IllegalArgumentException("Bad root path: " + this.table);
152 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700153 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
154 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700155 this.where = Settings.NameValueTable.NAME + "=?";
156 this.args = new String[] { url.getPathSegments().get(1) };
157 } else {
158 this.where = "_id=" + ContentUris.parseId(url);
159 this.args = null;
160 }
161 }
162 }
163
164 /** Insert new rows (no where clause allowed). */
165 SqlArguments(Uri url) {
166 if (url.getPathSegments().size() == 1) {
167 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700168 if (!DatabaseHelper.isValidTable(this.table)) {
169 throw new IllegalArgumentException("Bad root path: " + this.table);
170 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700171 this.where = null;
172 this.args = null;
173 } else {
174 throw new IllegalArgumentException("Invalid URI: " + url);
175 }
176 }
177 }
178
179 /**
180 * Get the content URI of a row added to a table.
181 * @param tableUri of the entire table
182 * @param values found in the row
183 * @param rowId of the row
184 * @return the content URI for this particular row
185 */
186 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
187 if (tableUri.getPathSegments().size() != 1) {
188 throw new IllegalArgumentException("Invalid URI: " + tableUri);
189 }
190 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700191 if (TABLE_SYSTEM.equals(table) ||
192 TABLE_SECURE.equals(table) ||
193 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700194 String name = values.getAsString(Settings.NameValueTable.NAME);
195 return Uri.withAppendedPath(tableUri, name);
196 } else {
197 return ContentUris.withAppendedId(tableUri, rowId);
198 }
199 }
200
201 /**
202 * Send a notification when a particular content URI changes.
203 * Modify the system property used to communicate the version of
204 * this table, for tables which have such a property. (The Settings
205 * contract class uses these to provide client-side caches.)
206 * @param uri to send notifications for
207 */
Christopher Tate06efb532012-08-24 15:29:27 -0700208 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700209 // Update the system property *first*, so if someone is listening for
210 // a notification and then using the contract class to get their data,
211 // the system property will be updated and they'll get the new data.
212
Amith Yamasanid1582142009-07-08 20:04:55 -0700213 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700214 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700215 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700216 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700217 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700218 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700219 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700220 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700221 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700222 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700223 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700224 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700225 }
226
227 if (property != null) {
228 long version = SystemProperties.getLong(property, 0) + 1;
229 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
230 SystemProperties.set(property, Long.toString(version));
231 }
232
-b master501eec92009-07-06 13:53:11 -0700233 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700234 if (backedUpDataChanged) {
235 mBackupManager.dataChanged();
236 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700237 // Now send the notification through the content framework.
238
239 String notify = uri.getQueryParameter("notify");
240 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700241 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700242 final long oldId = Binder.clearCallingIdentity();
243 try {
244 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
245 } finally {
246 Binder.restoreCallingIdentity(oldId);
247 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700248 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700249 } else {
250 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
251 }
252 }
253
254 /**
255 * Make sure the caller has permission to write this data.
256 * @param args supplied by the caller
257 * @throws SecurityException if the caller is forbidden to write.
258 */
259 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700260 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800261 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800262 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
263 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700264 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800265 String.format("Permission denial: writing to secure settings requires %1$s",
266 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 }
268 }
269
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700270 // FileObserver for external modifications to the database file.
271 // Note that this is for platform developers only with
272 // userdebug/eng builds who should be able to tinker with the
273 // sqlite database out from under the SettingsProvider, which is
274 // normally the exclusive owner of the database. But we keep this
275 // enabled all the time to minimize development-vs-user
276 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700277 private static SparseArray<SettingsFileObserver> sObserverInstances
278 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700279 private class SettingsFileObserver extends FileObserver {
280 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700281 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700282 private final String mPath;
283
Christopher Tate06efb532012-08-24 15:29:27 -0700284 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700285 super(path, FileObserver.CLOSE_WRITE |
286 FileObserver.CREATE | FileObserver.DELETE |
287 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700288 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700289 mPath = path;
290 }
291
292 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700293 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700294 if (modsInFlight > 0) {
295 // our own modification.
296 return;
297 }
Christopher Tate06efb532012-08-24 15:29:27 -0700298 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
299 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700300 if (!mIsDirty.compareAndSet(false, true)) {
301 // already handled. (we get a few update events
302 // during an sqlite write)
303 return;
304 }
Christopher Tate06efb532012-08-24 15:29:27 -0700305 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
306 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700307 mIsDirty.set(false);
308 }
309 }
310
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311 @Override
312 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700313 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700314 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800315
Christopher Tate78d2a662012-09-13 16:19:44 -0700316 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700317
Christopher Tate78d2a662012-09-13 16:19:44 -0700318 IntentFilter userFilter = new IntentFilter();
319 userFilter.addAction(Intent.ACTION_USER_REMOVED);
320 getContext().registerReceiver(new BroadcastReceiver() {
321 @Override
322 public void onReceive(Context context, Intent intent) {
323 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
324 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
325 UserHandle.USER_OWNER);
326 if (userHandle != UserHandle.USER_OWNER) {
327 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700328 }
329 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700330 }
331 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700332 return true;
333 }
334
Christopher Tate06efb532012-08-24 15:29:27 -0700335 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700336 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700337 // the db file itself will be deleted automatically, but we need to tear down
338 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700339 FileObserver observer = sObserverInstances.get(userHandle);
340 if (observer != null) {
341 observer.stopWatching();
342 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700343 }
Christopher Tate06efb532012-08-24 15:29:27 -0700344
345 mOpenHelpers.delete(userHandle);
346 sSystemCaches.delete(userHandle);
347 sSecureCaches.delete(userHandle);
348 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700349 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700350 }
351
Christopher Tate78d2a662012-09-13 16:19:44 -0700352 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700353 if (LOCAL_LOGV) {
354 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
355 }
356
Christopher Tate78d2a662012-09-13 16:19:44 -0700357 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700358
Christopher Tate78d2a662012-09-13 16:19:44 -0700359 synchronized (this) {
360 dbhelper = mOpenHelpers.get(userHandle);
361 if (dbhelper == null) {
362 dbhelper = new DatabaseHelper(getContext(), userHandle);
363 mOpenHelpers.append(userHandle, dbhelper);
364
365 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
366 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
367 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
368 }
369 }
370
371 // Initialization of the db *outside* the locks. It's possible that racing
372 // threads might wind up here, the second having read the cache entries
373 // written by the first, but that's benign: the SQLite helper implementation
374 // manages concurrency itself, and it's important that we not run the db
375 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700376 SQLiteDatabase db = dbhelper.getWritableDatabase();
377
Christopher Tate78d2a662012-09-13 16:19:44 -0700378 // Watch for external modifications to the database files,
379 // keeping our caches in sync. We synchronize the observer set
380 // separately, and of course it has to run after the db file
381 // itself was set up by the DatabaseHelper.
382 synchronized (sObserverInstances) {
383 if (sObserverInstances.get(userHandle) == null) {
384 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
385 sObserverInstances.append(userHandle, observer);
386 observer.startWatching();
387 }
388 }
Christopher Tate06efb532012-08-24 15:29:27 -0700389
Christopher Tate4dc7a682012-09-11 12:15:49 -0700390 ensureAndroidIdIsSet(userHandle);
391
Christopher Tate06efb532012-08-24 15:29:27 -0700392 startAsyncCachePopulation(userHandle);
393 }
394
395 class CachePrefetchThread extends Thread {
396 private int mUserHandle;
397
398 CachePrefetchThread(int userHandle) {
399 super("populate-settings-caches");
400 mUserHandle = userHandle;
401 }
402
403 @Override
404 public void run() {
405 fullyPopulateCaches(mUserHandle);
406 }
407 }
408
409 private void startAsyncCachePopulation(int userHandle) {
410 new CachePrefetchThread(userHandle).start();
411 }
412
413 private void fullyPopulateCaches(final int userHandle) {
414 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
415 // Only populate the globals cache once, for the owning user
416 if (userHandle == UserHandle.USER_OWNER) {
417 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
418 }
419 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
420 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700421 }
422
423 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700424 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
425 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700426 Cursor c = db.query(
427 table,
428 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
429 null, null, null, null, null,
430 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
431 try {
432 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800433 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700434 cache.setFullyMatchesDisk(true); // optimistic
435 int rows = 0;
436 while (c.moveToNext()) {
437 rows++;
438 String name = c.getString(0);
439 String value = c.getString(1);
440 cache.populate(name, value);
441 }
442 if (rows > MAX_CACHE_ENTRIES) {
443 // Somewhat redundant, as removeEldestEntry() will
444 // have already done this, but to be explicit:
445 cache.setFullyMatchesDisk(false);
446 Log.d(TAG, "row count exceeds max cache entries for table " + table);
447 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700448 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700449 cache.fullyMatchesDisk());
450 }
451 } finally {
452 c.close();
453 }
454 }
455
Christopher Tate4dc7a682012-09-11 12:15:49 -0700456 private boolean ensureAndroidIdIsSet(int userHandle) {
457 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800458 new String[] { Settings.NameValueTable.VALUE },
459 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700460 new String[] { Settings.Secure.ANDROID_ID }, null,
461 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800462 try {
463 final String value = c.moveToNext() ? c.getString(0) : null;
464 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700465 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800466 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800467 final ContentValues values = new ContentValues();
468 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
469 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700470 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800471 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700472 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800473 return false;
474 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700475 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
476 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800477 }
478 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800479 } finally {
480 c.close();
481 }
482 }
483
Christopher Tate06efb532012-08-24 15:29:27 -0700484 // Lazy-initialize the settings caches for non-primary users
485 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700486 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
487 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700488 }
489
490 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700491 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700492 long oldId = Binder.clearCallingIdentity();
493 try {
494 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
495 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700496 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700497 dbHelper = mOpenHelpers.get(callingUser);
498 }
499 return dbHelper;
500 } finally {
501 Binder.restoreCallingIdentity(oldId);
502 }
503 }
504
505 public SettingsCache cacheForTable(final int callingUser, String tableName) {
506 if (TABLE_SYSTEM.equals(tableName)) {
507 return getOrConstructCache(callingUser, sSystemCaches);
508 }
509 if (TABLE_SECURE.equals(tableName)) {
510 return getOrConstructCache(callingUser, sSecureCaches);
511 }
512 if (TABLE_GLOBAL.equals(tableName)) {
513 return sGlobalCache;
514 }
515 return null;
516 }
517
518 /**
519 * Used for wiping a whole cache on deletes when we're not
520 * sure what exactly was deleted or changed.
521 */
522 public void invalidateCache(final int callingUser, String tableName) {
523 SettingsCache cache = cacheForTable(callingUser, tableName);
524 if (cache == null) {
525 return;
526 }
527 synchronized (cache) {
528 cache.evictAll();
529 cache.mCacheFullyMatchesDisk = false;
530 }
531 }
532
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800533 /**
534 * Fast path that avoids the use of chatty remoted Cursors.
535 */
536 @Override
537 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700538 int callingUser = UserHandle.getCallingUserId();
539 if (args != null) {
540 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
541 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700542 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
543 Binder.getCallingUid(), reqUser, false, true,
544 "get/set setting for user", null);
545 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700546 }
547 }
548
Christopher Tateb7564452012-09-19 16:21:18 -0700549 // Okay, permission checks have cleared. Reset to our own identity so we can
550 // manipulate all users' data with impunity.
551 long oldId = Binder.clearCallingIdentity();
552 try {
553 // Note: we assume that get/put operations for moved-to-global names have already
554 // been directed to the new location on the caller side (otherwise we'd fix them
555 // up here).
556 DatabaseHelper dbHelper;
557 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700558
Christopher Tateb7564452012-09-19 16:21:18 -0700559 // Get methods
560 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
561 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
562 dbHelper = getOrEstablishDatabase(callingUser);
563 cache = sSystemCaches.get(callingUser);
564 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
565 }
566 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
567 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
568 dbHelper = getOrEstablishDatabase(callingUser);
569 cache = sSecureCaches.get(callingUser);
570 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
571 }
572 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
573 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
574 // fast path: owner db & cache are immutable after onCreate() so we need not
575 // guard on the attempt to look them up
576 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
577 sGlobalCache, request);
578 }
Christopher Tate06efb532012-08-24 15:29:27 -0700579
Christopher Tateb7564452012-09-19 16:21:18 -0700580 // Put methods - new value is in the args bundle under the key named by
581 // the Settings.NameValueTable.VALUE static.
582 final String newValue = (args == null)
583 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700584
Christopher Tateb7564452012-09-19 16:21:18 -0700585 final ContentValues values = new ContentValues();
586 values.put(Settings.NameValueTable.NAME, request);
587 values.put(Settings.NameValueTable.VALUE, newValue);
588 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
589 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
590 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
591 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
592 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
593 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
594 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
595 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
596 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
597 } else {
598 Slog.w(TAG, "call() with invalid method: " + method);
599 }
600 } finally {
601 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700602 }
603
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800604 return null;
605 }
606
607 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
608 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700609 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
610 final SettingsCache cache, String key) {
611 if (cache == null) {
612 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
613 return null;
614 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800615 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800616 Bundle value = cache.get(key);
617 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700618 if (value != TOO_LARGE_TO_CACHE_MARKER) {
619 return value;
620 }
621 // else we fall through and read the value from disk
622 } else if (cache.fullyMatchesDisk()) {
623 // Fast path (very common). Don't even try touch disk
624 // if we know we've slurped it all in. Trying to
625 // touch the disk would mean waiting for yaffs2 to
626 // give us access, which could takes hundreds of
627 // milliseconds. And we're very likely being called
628 // from somebody's UI thread...
629 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800630 }
631 }
632
Christopher Tate06efb532012-08-24 15:29:27 -0700633 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800634 Cursor cursor = null;
635 try {
636 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
637 null, null, null, null);
638 if (cursor != null && cursor.getCount() == 1) {
639 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800640 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800641 }
642 } catch (SQLiteException e) {
643 Log.w(TAG, "settings lookup error", e);
644 return null;
645 } finally {
646 if (cursor != null) cursor.close();
647 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800648 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800649 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800650 }
651
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700652 @Override
653 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700654 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
655 }
656
Christopher Tateb7564452012-09-19 16:21:18 -0700657 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700658 String sort, int forUser) {
659 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700660 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700661 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700662 dbH = getOrEstablishDatabase(
663 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700664 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800666 // The favorites table was moved from this provider to a provider inside Home
667 // Home still need to query this table to upgrade from pre-cupcake builds
668 // However, a cupcake+ build with no data does not contain this table which will
669 // cause an exception in the SQL stack. The following line is a special case to
670 // 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 -0800671 if (TABLE_FAVORITES.equals(args.table)) {
672 return null;
673 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
674 args.table = TABLE_FAVORITES;
675 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
676 if (cursor != null) {
677 boolean exists = cursor.getCount() > 0;
678 cursor.close();
679 if (!exists) return null;
680 } else {
681 return null;
682 }
683 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800684
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700685 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
686 qb.setTables(args.table);
687
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700688 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700689 // the default Cursor interface does not support per-user observation
690 try {
691 AbstractCursor c = (AbstractCursor) ret;
692 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
693 } catch (ClassCastException e) {
694 // details of the concrete Cursor implementation have changed and this code has
695 // not been updated to match -- complain and fail hard.
696 Log.wtf(TAG, "Incompatible cursor derivation!");
697 throw e;
698 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700699 return ret;
700 }
701
702 @Override
703 public String getType(Uri url) {
704 // If SqlArguments supplies a where clause, then it must be an item
705 // (because we aren't supplying our own where clause).
706 SqlArguments args = new SqlArguments(url, null, null);
707 if (TextUtils.isEmpty(args.where)) {
708 return "vnd.android.cursor.dir/" + args.table;
709 } else {
710 return "vnd.android.cursor.item/" + args.table;
711 }
712 }
713
714 @Override
715 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700716 final int callingUser = UserHandle.getCallingUserId();
717 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700718 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 if (TABLE_FAVORITES.equals(args.table)) {
720 return 0;
721 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700722 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700723 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700724
Christopher Tate06efb532012-08-24 15:29:27 -0700725 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
726 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700727 DatabaseHelper dbH = getOrEstablishDatabase(
728 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700729 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700730 db.beginTransaction();
731 try {
732 int numValues = values.length;
733 for (int i = 0; i < numValues; i++) {
734 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800735 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700736 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
737 }
738 db.setTransactionSuccessful();
739 } finally {
740 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700741 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700742 }
743
Christopher Tate06efb532012-08-24 15:29:27 -0700744 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700745 return values.length;
746 }
747
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700748 /*
749 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
750 * This setting contains a list of the currently enabled location providers.
751 * But helper functions in android.providers.Settings can enable or disable
752 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800753 *
754 * @returns whether the database needs to be updated or not, also modifying
755 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700756 */
757 private boolean parseProviderList(Uri url, ContentValues initialValues) {
758 String value = initialValues.getAsString(Settings.Secure.VALUE);
759 String newProviders = null;
760 if (value != null && value.length() > 1) {
761 char prefix = value.charAt(0);
762 if (prefix == '+' || prefix == '-') {
763 // skip prefix
764 value = value.substring(1);
765
766 // read list of enabled providers into "providers"
767 String providers = "";
768 String[] columns = {Settings.Secure.VALUE};
769 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
770 Cursor cursor = query(url, columns, where, null, null);
771 if (cursor != null && cursor.getCount() == 1) {
772 try {
773 cursor.moveToFirst();
774 providers = cursor.getString(0);
775 } finally {
776 cursor.close();
777 }
778 }
779
780 int index = providers.indexOf(value);
781 int end = index + value.length();
782 // check for commas to avoid matching on partial string
783 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
784 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
785
786 if (prefix == '+' && index < 0) {
787 // append the provider to the list if not present
788 if (providers.length() == 0) {
789 newProviders = value;
790 } else {
791 newProviders = providers + ',' + value;
792 }
793 } else if (prefix == '-' && index >= 0) {
794 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400795 // remove leading or trailing comma
796 if (index > 0) {
797 index--;
798 } else if (end < providers.length()) {
799 end++;
800 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700801
802 newProviders = providers.substring(0, index);
803 if (end < providers.length()) {
804 newProviders += providers.substring(end);
805 }
806 } else {
807 // nothing changed, so no need to update the database
808 return false;
809 }
810
811 if (newProviders != null) {
812 initialValues.put(Settings.Secure.VALUE, newProviders);
813 }
814 }
815 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800816
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700817 return true;
818 }
819
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700820 @Override
821 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700822 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
823 }
824
825 // Settings.put*ForUser() always winds up here, so this is where we apply
826 // policy around permission to write settings for other users.
827 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
828 final int callingUser = UserHandle.getCallingUserId();
829 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700830 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700831 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
832 "Not permitted to access settings for other users");
833 }
834
835 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
836 + " by " + callingUser);
837
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700838 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 if (TABLE_FAVORITES.equals(args.table)) {
840 return null;
841 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700842 checkWritePermissions(args);
843
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700844 // Special case LOCATION_PROVIDERS_ALLOWED.
845 // Support enabling/disabling a single provider (using "+" or "-" prefix)
846 String name = initialValues.getAsString(Settings.Secure.NAME);
847 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
848 if (!parseProviderList(url, initialValues)) return null;
849 }
850
Christopher Tate06efb532012-08-24 15:29:27 -0700851 // The global table is stored under the owner, always
852 if (TABLE_GLOBAL.equals(args.table)) {
853 desiredUserHandle = UserHandle.USER_OWNER;
854 }
855
856 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800857 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
858 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
859 return Uri.withAppendedPath(url, name);
860 }
861
Christopher Tate06efb532012-08-24 15:29:27 -0700862 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
863 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700864 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700865 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700866 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700867 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700868 if (rowId <= 0) return null;
869
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800870 SettingsCache.populate(cache, initialValues); // before we notify
871
Christopher Tate78d2a662012-09-13 16:19:44 -0700872 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
873 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700874 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700875 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700876 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700877 return url;
878 }
879
880 @Override
881 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700882 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700883 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700884 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 if (TABLE_FAVORITES.equals(args.table)) {
886 return 0;
887 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
888 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700889 } else if (TABLE_GLOBAL.equals(args.table)) {
890 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700892 checkWritePermissions(args);
893
Christopher Tate06efb532012-08-24 15:29:27 -0700894 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
895 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700896 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700897 SQLiteDatabase db = dbH.getWritableDatabase();
898 int count = db.delete(args.table, args.where, args.args);
899 mutationCount.decrementAndGet();
900 if (count > 0) {
901 invalidateCache(callingUser, args.table); // before we notify
902 sendNotify(url, callingUser);
903 }
904 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700905 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
906 return count;
907 }
908
909 @Override
910 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700911 // NOTE: update() is never called by the front-end Settings API, and updates that
912 // wind up affecting rows in Secure that are globally shared will not have the
913 // intended effect (the update will be invisible to the rest of the system).
914 // This should have no practical effect, since writes to the Secure db can only
915 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700916 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700917 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700918 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (TABLE_FAVORITES.equals(args.table)) {
920 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700921 } else if (TABLE_GLOBAL.equals(args.table)) {
922 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700924 checkWritePermissions(args);
925
Christopher Tate06efb532012-08-24 15:29:27 -0700926 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
927 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700928 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700929 SQLiteDatabase db = dbH.getWritableDatabase();
930 int count = db.update(args.table, initialValues, args.where, args.args);
931 mutationCount.decrementAndGet();
932 if (count > 0) {
933 invalidateCache(callingUser, args.table); // before we notify
934 sendNotify(url, callingUser);
935 }
936 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700937 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
938 return count;
939 }
940
941 @Override
942 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
943
944 /*
945 * When a client attempts to openFile the default ringtone or
946 * notification setting Uri, we will proxy the call to the current
947 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700948 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700949 int ringtoneType = RingtoneManager.getDefaultType(uri);
950 // Above call returns -1 if the Uri doesn't match a default type
951 if (ringtoneType != -1) {
952 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700953
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700954 // Get the current value for the default sound
955 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700956
Marco Nelissen69f593c2009-07-28 09:55:04 -0700957 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700958 // Only proxy the openFile call to drm or media providers
959 String authority = soundUri.getAuthority();
960 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
961 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
962
963 if (isDrmAuthority) {
964 try {
965 // Check DRM access permission here, since once we
966 // do the below call the DRM will be checking our
967 // permission, not our caller's permission
968 DrmStore.enforceAccessDrmPermission(context);
969 } catch (SecurityException e) {
970 throw new FileNotFoundException(e.getMessage());
971 }
972 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700973
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700974 return context.getContentResolver().openFileDescriptor(soundUri, mode);
975 }
976 }
977 }
978
979 return super.openFile(uri, mode);
980 }
Marco Nelissen69f593c2009-07-28 09:55:04 -0700981
982 @Override
983 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
984
985 /*
986 * When a client attempts to openFile the default ringtone or
987 * notification setting Uri, we will proxy the call to the current
988 * default ringtone's Uri (if it is in the DRM or media provider).
989 */
990 int ringtoneType = RingtoneManager.getDefaultType(uri);
991 // Above call returns -1 if the Uri doesn't match a default type
992 if (ringtoneType != -1) {
993 Context context = getContext();
994
995 // Get the current value for the default sound
996 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
997
998 if (soundUri != null) {
999 // Only proxy the openFile call to drm or media providers
1000 String authority = soundUri.getAuthority();
1001 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1002 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1003
1004 if (isDrmAuthority) {
1005 try {
1006 // Check DRM access permission here, since once we
1007 // do the below call the DRM will be checking our
1008 // permission, not our caller's permission
1009 DrmStore.enforceAccessDrmPermission(context);
1010 } catch (SecurityException e) {
1011 throw new FileNotFoundException(e.getMessage());
1012 }
1013 }
1014
1015 ParcelFileDescriptor pfd = null;
1016 try {
1017 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1018 return new AssetFileDescriptor(pfd, 0, -1);
1019 } catch (FileNotFoundException ex) {
1020 // fall through and open the fallback ringtone below
1021 }
1022 }
1023
1024 try {
1025 return super.openAssetFile(soundUri, mode);
1026 } catch (FileNotFoundException ex) {
1027 // Since a non-null Uri was specified, but couldn't be opened,
1028 // fall back to the built-in ringtone.
1029 return context.getResources().openRawResourceFd(
1030 com.android.internal.R.raw.fallbackring);
1031 }
1032 }
1033 // no need to fall through and have openFile() try again, since we
1034 // already know that will fail.
1035 throw new FileNotFoundException(); // or return null ?
1036 }
1037
1038 // Note that this will end up calling openFile() above.
1039 return super.openAssetFile(uri, mode);
1040 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001041
1042 /**
1043 * In-memory LRU Cache of system and secure settings, along with
1044 * associated helper functions to keep cache coherent with the
1045 * database.
1046 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001047 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001048
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001049 private final String mCacheName;
1050 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1051
1052 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001053 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001054 mCacheName = name;
1055 }
1056
1057 /**
1058 * Is the whole database table slurped into this cache?
1059 */
1060 public boolean fullyMatchesDisk() {
1061 synchronized (this) {
1062 return mCacheFullyMatchesDisk;
1063 }
1064 }
1065
1066 public void setFullyMatchesDisk(boolean value) {
1067 synchronized (this) {
1068 mCacheFullyMatchesDisk = value;
1069 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001070 }
1071
1072 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001073 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1074 if (evicted) {
1075 mCacheFullyMatchesDisk = false;
1076 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001077 }
1078
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001079 /**
1080 * Atomic cache population, conditional on size of value and if
1081 * we lost a race.
1082 *
1083 * @returns a Bundle to send back to the client from call(), even
1084 * if we lost the race.
1085 */
1086 public Bundle putIfAbsent(String key, String value) {
1087 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1088 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1089 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001090 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001091 put(key, bundle);
1092 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001093 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001094 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001095 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001096 }
1097
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001098 /**
1099 * Populates a key in a given (possibly-null) cache.
1100 */
1101 public static void populate(SettingsCache cache, ContentValues contentValues) {
1102 if (cache == null) {
1103 return;
1104 }
1105 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1106 if (name == null) {
1107 Log.w(TAG, "null name populating settings cache.");
1108 return;
1109 }
1110 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001111 cache.populate(name, value);
1112 }
1113
1114 public void populate(String name, String value) {
1115 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001116 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001117 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001118 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001119 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001120 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001121 }
1122 }
1123
1124 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001125 * For suppressing duplicate/redundant settings inserts early,
1126 * checking our cache first (but without faulting it in),
1127 * before going to sqlite with the mutation.
1128 */
1129 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1130 if (cache == null) return false;
1131 synchronized (cache) {
1132 Bundle bundle = cache.get(name);
1133 if (bundle == null) return false;
1134 String oldValue = bundle.getPairValue();
1135 if (oldValue == null && value == null) return true;
1136 if ((oldValue == null) != (value == null)) return false;
1137 return oldValue.equals(value);
1138 }
1139 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001140 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001141}