blob: 76a5022379897655a25bf3ce68d555490b489f5c [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) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700138 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700140 if (!DatabaseHelper.isValidTable(this.table)) {
141 throw new IllegalArgumentException("Bad root path: " + this.table);
142 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143 this.where = where;
144 this.args = args;
145 } else if (url.getPathSegments().size() != 2) {
146 throw new IllegalArgumentException("Invalid URI: " + url);
147 } else if (!TextUtils.isEmpty(where)) {
148 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
149 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700150 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700152 if (!DatabaseHelper.isValidTable(this.table)) {
153 throw new IllegalArgumentException("Bad root path: " + this.table);
154 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700155 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
156 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700157 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700158 final String name = url.getPathSegments().get(1);
159 this.args = new String[] { name };
160 // Rewrite the table for known-migrated names
161 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
162 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
163 this.table = TABLE_GLOBAL;
164 }
165 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700166 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700167 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168 this.where = "_id=" + ContentUris.parseId(url);
169 this.args = null;
170 }
171 }
172 }
173
174 /** Insert new rows (no where clause allowed). */
175 SqlArguments(Uri url) {
176 if (url.getPathSegments().size() == 1) {
177 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700178 if (!DatabaseHelper.isValidTable(this.table)) {
179 throw new IllegalArgumentException("Bad root path: " + this.table);
180 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700181 this.where = null;
182 this.args = null;
183 } else {
184 throw new IllegalArgumentException("Invalid URI: " + url);
185 }
186 }
187 }
188
189 /**
190 * Get the content URI of a row added to a table.
191 * @param tableUri of the entire table
192 * @param values found in the row
193 * @param rowId of the row
194 * @return the content URI for this particular row
195 */
196 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
197 if (tableUri.getPathSegments().size() != 1) {
198 throw new IllegalArgumentException("Invalid URI: " + tableUri);
199 }
200 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700201 if (TABLE_SYSTEM.equals(table) ||
202 TABLE_SECURE.equals(table) ||
203 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700204 String name = values.getAsString(Settings.NameValueTable.NAME);
205 return Uri.withAppendedPath(tableUri, name);
206 } else {
207 return ContentUris.withAppendedId(tableUri, rowId);
208 }
209 }
210
211 /**
212 * Send a notification when a particular content URI changes.
213 * Modify the system property used to communicate the version of
214 * this table, for tables which have such a property. (The Settings
215 * contract class uses these to provide client-side caches.)
216 * @param uri to send notifications for
217 */
Christopher Tate06efb532012-08-24 15:29:27 -0700218 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700219 // Update the system property *first*, so if someone is listening for
220 // a notification and then using the contract class to get their data,
221 // the system property will be updated and they'll get the new data.
222
Amith Yamasanid1582142009-07-08 20:04:55 -0700223 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700224 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700225 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700226 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700227 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700228 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700229 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700230 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700231 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700232 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700233 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700234 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700235 }
236
237 if (property != null) {
238 long version = SystemProperties.getLong(property, 0) + 1;
239 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
240 SystemProperties.set(property, Long.toString(version));
241 }
242
-b master501eec92009-07-06 13:53:11 -0700243 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700244 if (backedUpDataChanged) {
245 mBackupManager.dataChanged();
246 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247 // Now send the notification through the content framework.
248
249 String notify = uri.getQueryParameter("notify");
250 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700251 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700252 final long oldId = Binder.clearCallingIdentity();
253 try {
254 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
255 } finally {
256 Binder.restoreCallingIdentity(oldId);
257 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700258 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700259 } else {
260 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
261 }
262 }
263
264 /**
265 * Make sure the caller has permission to write this data.
266 * @param args supplied by the caller
267 * @throws SecurityException if the caller is forbidden to write.
268 */
269 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700270 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800271 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800272 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
273 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700274 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800275 String.format("Permission denial: writing to secure settings requires %1$s",
276 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700277 }
278 }
279
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700280 // FileObserver for external modifications to the database file.
281 // Note that this is for platform developers only with
282 // userdebug/eng builds who should be able to tinker with the
283 // sqlite database out from under the SettingsProvider, which is
284 // normally the exclusive owner of the database. But we keep this
285 // enabled all the time to minimize development-vs-user
286 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700287 private static SparseArray<SettingsFileObserver> sObserverInstances
288 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700289 private class SettingsFileObserver extends FileObserver {
290 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700291 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700292 private final String mPath;
293
Christopher Tate06efb532012-08-24 15:29:27 -0700294 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700295 super(path, FileObserver.CLOSE_WRITE |
296 FileObserver.CREATE | FileObserver.DELETE |
297 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700298 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700299 mPath = path;
300 }
301
302 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700303 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700304 if (modsInFlight > 0) {
305 // our own modification.
306 return;
307 }
Christopher Tate06efb532012-08-24 15:29:27 -0700308 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
309 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700310 if (!mIsDirty.compareAndSet(false, true)) {
311 // already handled. (we get a few update events
312 // during an sqlite write)
313 return;
314 }
Christopher Tate06efb532012-08-24 15:29:27 -0700315 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
316 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700317 mIsDirty.set(false);
318 }
319 }
320
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 @Override
322 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700323 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700324 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800325
Christopher Tate78d2a662012-09-13 16:19:44 -0700326 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700327
Christopher Tate78d2a662012-09-13 16:19:44 -0700328 IntentFilter userFilter = new IntentFilter();
329 userFilter.addAction(Intent.ACTION_USER_REMOVED);
330 getContext().registerReceiver(new BroadcastReceiver() {
331 @Override
332 public void onReceive(Context context, Intent intent) {
333 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
334 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
335 UserHandle.USER_OWNER);
336 if (userHandle != UserHandle.USER_OWNER) {
337 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700338 }
339 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700340 }
341 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700342 return true;
343 }
344
Christopher Tate06efb532012-08-24 15:29:27 -0700345 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700346 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700347 // the db file itself will be deleted automatically, but we need to tear down
348 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700349 FileObserver observer = sObserverInstances.get(userHandle);
350 if (observer != null) {
351 observer.stopWatching();
352 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700353 }
Christopher Tate06efb532012-08-24 15:29:27 -0700354
355 mOpenHelpers.delete(userHandle);
356 sSystemCaches.delete(userHandle);
357 sSecureCaches.delete(userHandle);
358 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700359 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700360 }
361
Christopher Tate78d2a662012-09-13 16:19:44 -0700362 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700363 if (LOCAL_LOGV) {
364 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
365 }
366
Christopher Tate78d2a662012-09-13 16:19:44 -0700367 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700368
Christopher Tate78d2a662012-09-13 16:19:44 -0700369 synchronized (this) {
370 dbhelper = mOpenHelpers.get(userHandle);
371 if (dbhelper == null) {
372 dbhelper = new DatabaseHelper(getContext(), userHandle);
373 mOpenHelpers.append(userHandle, dbhelper);
374
375 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
376 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
377 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
378 }
379 }
380
381 // Initialization of the db *outside* the locks. It's possible that racing
382 // threads might wind up here, the second having read the cache entries
383 // written by the first, but that's benign: the SQLite helper implementation
384 // manages concurrency itself, and it's important that we not run the db
385 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700386 SQLiteDatabase db = dbhelper.getWritableDatabase();
387
Christopher Tate78d2a662012-09-13 16:19:44 -0700388 // Watch for external modifications to the database files,
389 // keeping our caches in sync. We synchronize the observer set
390 // separately, and of course it has to run after the db file
391 // itself was set up by the DatabaseHelper.
392 synchronized (sObserverInstances) {
393 if (sObserverInstances.get(userHandle) == null) {
394 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
395 sObserverInstances.append(userHandle, observer);
396 observer.startWatching();
397 }
398 }
Christopher Tate06efb532012-08-24 15:29:27 -0700399
Christopher Tate4dc7a682012-09-11 12:15:49 -0700400 ensureAndroidIdIsSet(userHandle);
401
Christopher Tate06efb532012-08-24 15:29:27 -0700402 startAsyncCachePopulation(userHandle);
403 }
404
405 class CachePrefetchThread extends Thread {
406 private int mUserHandle;
407
408 CachePrefetchThread(int userHandle) {
409 super("populate-settings-caches");
410 mUserHandle = userHandle;
411 }
412
413 @Override
414 public void run() {
415 fullyPopulateCaches(mUserHandle);
416 }
417 }
418
419 private void startAsyncCachePopulation(int userHandle) {
420 new CachePrefetchThread(userHandle).start();
421 }
422
423 private void fullyPopulateCaches(final int userHandle) {
424 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
425 // Only populate the globals cache once, for the owning user
426 if (userHandle == UserHandle.USER_OWNER) {
427 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
428 }
429 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
430 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700431 }
432
433 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700434 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
435 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700436 Cursor c = db.query(
437 table,
438 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
439 null, null, null, null, null,
440 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
441 try {
442 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800443 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700444 cache.setFullyMatchesDisk(true); // optimistic
445 int rows = 0;
446 while (c.moveToNext()) {
447 rows++;
448 String name = c.getString(0);
449 String value = c.getString(1);
450 cache.populate(name, value);
451 }
452 if (rows > MAX_CACHE_ENTRIES) {
453 // Somewhat redundant, as removeEldestEntry() will
454 // have already done this, but to be explicit:
455 cache.setFullyMatchesDisk(false);
456 Log.d(TAG, "row count exceeds max cache entries for table " + table);
457 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700458 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700459 cache.fullyMatchesDisk());
460 }
461 } finally {
462 c.close();
463 }
464 }
465
Christopher Tate4dc7a682012-09-11 12:15:49 -0700466 private boolean ensureAndroidIdIsSet(int userHandle) {
467 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800468 new String[] { Settings.NameValueTable.VALUE },
469 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700470 new String[] { Settings.Secure.ANDROID_ID }, null,
471 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800472 try {
473 final String value = c.moveToNext() ? c.getString(0) : null;
474 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700475 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800476 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800477 final ContentValues values = new ContentValues();
478 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
479 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700480 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800481 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700482 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800483 return false;
484 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700485 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
486 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800487 }
488 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800489 } finally {
490 c.close();
491 }
492 }
493
Christopher Tate06efb532012-08-24 15:29:27 -0700494 // Lazy-initialize the settings caches for non-primary users
495 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700496 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
497 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700498 }
499
500 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700501 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700502 long oldId = Binder.clearCallingIdentity();
503 try {
504 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
505 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700506 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700507 dbHelper = mOpenHelpers.get(callingUser);
508 }
509 return dbHelper;
510 } finally {
511 Binder.restoreCallingIdentity(oldId);
512 }
513 }
514
515 public SettingsCache cacheForTable(final int callingUser, String tableName) {
516 if (TABLE_SYSTEM.equals(tableName)) {
517 return getOrConstructCache(callingUser, sSystemCaches);
518 }
519 if (TABLE_SECURE.equals(tableName)) {
520 return getOrConstructCache(callingUser, sSecureCaches);
521 }
522 if (TABLE_GLOBAL.equals(tableName)) {
523 return sGlobalCache;
524 }
525 return null;
526 }
527
528 /**
529 * Used for wiping a whole cache on deletes when we're not
530 * sure what exactly was deleted or changed.
531 */
532 public void invalidateCache(final int callingUser, String tableName) {
533 SettingsCache cache = cacheForTable(callingUser, tableName);
534 if (cache == null) {
535 return;
536 }
537 synchronized (cache) {
538 cache.evictAll();
539 cache.mCacheFullyMatchesDisk = false;
540 }
541 }
542
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800543 /**
544 * Fast path that avoids the use of chatty remoted Cursors.
545 */
546 @Override
547 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700548 int callingUser = UserHandle.getCallingUserId();
549 if (args != null) {
550 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
551 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700552 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
553 Binder.getCallingUid(), reqUser, false, true,
554 "get/set setting for user", null);
555 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700556 }
557 }
558
Christopher Tateb7564452012-09-19 16:21:18 -0700559 // Okay, permission checks have cleared. Reset to our own identity so we can
560 // manipulate all users' data with impunity.
561 long oldId = Binder.clearCallingIdentity();
562 try {
563 // Note: we assume that get/put operations for moved-to-global names have already
564 // been directed to the new location on the caller side (otherwise we'd fix them
565 // up here).
566 DatabaseHelper dbHelper;
567 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700568
Christopher Tateb7564452012-09-19 16:21:18 -0700569 // Get methods
570 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
571 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
572 dbHelper = getOrEstablishDatabase(callingUser);
573 cache = sSystemCaches.get(callingUser);
574 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
575 }
576 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
577 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
578 dbHelper = getOrEstablishDatabase(callingUser);
579 cache = sSecureCaches.get(callingUser);
580 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
581 }
582 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
583 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
584 // fast path: owner db & cache are immutable after onCreate() so we need not
585 // guard on the attempt to look them up
586 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
587 sGlobalCache, request);
588 }
Christopher Tate06efb532012-08-24 15:29:27 -0700589
Christopher Tateb7564452012-09-19 16:21:18 -0700590 // Put methods - new value is in the args bundle under the key named by
591 // the Settings.NameValueTable.VALUE static.
592 final String newValue = (args == null)
593 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700594
Christopher Tateb7564452012-09-19 16:21:18 -0700595 final ContentValues values = new ContentValues();
596 values.put(Settings.NameValueTable.NAME, request);
597 values.put(Settings.NameValueTable.VALUE, newValue);
598 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
599 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
600 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
601 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
602 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
603 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
604 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
605 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
606 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
607 } else {
608 Slog.w(TAG, "call() with invalid method: " + method);
609 }
610 } finally {
611 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700612 }
613
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800614 return null;
615 }
616
617 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
618 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700619 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
620 final SettingsCache cache, String key) {
621 if (cache == null) {
622 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
623 return null;
624 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800625 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800626 Bundle value = cache.get(key);
627 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700628 if (value != TOO_LARGE_TO_CACHE_MARKER) {
629 return value;
630 }
631 // else we fall through and read the value from disk
632 } else if (cache.fullyMatchesDisk()) {
633 // Fast path (very common). Don't even try touch disk
634 // if we know we've slurped it all in. Trying to
635 // touch the disk would mean waiting for yaffs2 to
636 // give us access, which could takes hundreds of
637 // milliseconds. And we're very likely being called
638 // from somebody's UI thread...
639 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800640 }
641 }
642
Christopher Tate06efb532012-08-24 15:29:27 -0700643 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800644 Cursor cursor = null;
645 try {
646 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
647 null, null, null, null);
648 if (cursor != null && cursor.getCount() == 1) {
649 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800650 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800651 }
652 } catch (SQLiteException e) {
653 Log.w(TAG, "settings lookup error", e);
654 return null;
655 } finally {
656 if (cursor != null) cursor.close();
657 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800658 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800659 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800660 }
661
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700662 @Override
663 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700664 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
665 }
666
Christopher Tateb7564452012-09-19 16:21:18 -0700667 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700668 String sort, int forUser) {
669 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700670 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700671 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700672 dbH = getOrEstablishDatabase(
673 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700674 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800676 // The favorites table was moved from this provider to a provider inside Home
677 // Home still need to query this table to upgrade from pre-cupcake builds
678 // However, a cupcake+ build with no data does not contain this table which will
679 // cause an exception in the SQL stack. The following line is a special case to
680 // 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 -0800681 if (TABLE_FAVORITES.equals(args.table)) {
682 return null;
683 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
684 args.table = TABLE_FAVORITES;
685 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
686 if (cursor != null) {
687 boolean exists = cursor.getCount() > 0;
688 cursor.close();
689 if (!exists) return null;
690 } else {
691 return null;
692 }
693 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800694
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700695 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
696 qb.setTables(args.table);
697
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700698 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700699 // the default Cursor interface does not support per-user observation
700 try {
701 AbstractCursor c = (AbstractCursor) ret;
702 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
703 } catch (ClassCastException e) {
704 // details of the concrete Cursor implementation have changed and this code has
705 // not been updated to match -- complain and fail hard.
706 Log.wtf(TAG, "Incompatible cursor derivation!");
707 throw e;
708 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700709 return ret;
710 }
711
712 @Override
713 public String getType(Uri url) {
714 // If SqlArguments supplies a where clause, then it must be an item
715 // (because we aren't supplying our own where clause).
716 SqlArguments args = new SqlArguments(url, null, null);
717 if (TextUtils.isEmpty(args.where)) {
718 return "vnd.android.cursor.dir/" + args.table;
719 } else {
720 return "vnd.android.cursor.item/" + args.table;
721 }
722 }
723
724 @Override
725 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700726 final int callingUser = UserHandle.getCallingUserId();
727 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700728 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 if (TABLE_FAVORITES.equals(args.table)) {
730 return 0;
731 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700732 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700733 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700734
Christopher Tate06efb532012-08-24 15:29:27 -0700735 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
736 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700737 DatabaseHelper dbH = getOrEstablishDatabase(
738 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700739 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700740 db.beginTransaction();
741 try {
742 int numValues = values.length;
743 for (int i = 0; i < numValues; i++) {
744 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800745 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700746 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
747 }
748 db.setTransactionSuccessful();
749 } finally {
750 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700751 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700752 }
753
Christopher Tate06efb532012-08-24 15:29:27 -0700754 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700755 return values.length;
756 }
757
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700758 /*
759 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
760 * This setting contains a list of the currently enabled location providers.
761 * But helper functions in android.providers.Settings can enable or disable
762 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800763 *
764 * @returns whether the database needs to be updated or not, also modifying
765 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700766 */
767 private boolean parseProviderList(Uri url, ContentValues initialValues) {
768 String value = initialValues.getAsString(Settings.Secure.VALUE);
769 String newProviders = null;
770 if (value != null && value.length() > 1) {
771 char prefix = value.charAt(0);
772 if (prefix == '+' || prefix == '-') {
773 // skip prefix
774 value = value.substring(1);
775
776 // read list of enabled providers into "providers"
777 String providers = "";
778 String[] columns = {Settings.Secure.VALUE};
779 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
780 Cursor cursor = query(url, columns, where, null, null);
781 if (cursor != null && cursor.getCount() == 1) {
782 try {
783 cursor.moveToFirst();
784 providers = cursor.getString(0);
785 } finally {
786 cursor.close();
787 }
788 }
789
790 int index = providers.indexOf(value);
791 int end = index + value.length();
792 // check for commas to avoid matching on partial string
793 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
794 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
795
796 if (prefix == '+' && index < 0) {
797 // append the provider to the list if not present
798 if (providers.length() == 0) {
799 newProviders = value;
800 } else {
801 newProviders = providers + ',' + value;
802 }
803 } else if (prefix == '-' && index >= 0) {
804 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400805 // remove leading or trailing comma
806 if (index > 0) {
807 index--;
808 } else if (end < providers.length()) {
809 end++;
810 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700811
812 newProviders = providers.substring(0, index);
813 if (end < providers.length()) {
814 newProviders += providers.substring(end);
815 }
816 } else {
817 // nothing changed, so no need to update the database
818 return false;
819 }
820
821 if (newProviders != null) {
822 initialValues.put(Settings.Secure.VALUE, newProviders);
823 }
824 }
825 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800826
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700827 return true;
828 }
829
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700830 @Override
831 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700832 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
833 }
834
835 // Settings.put*ForUser() always winds up here, so this is where we apply
836 // policy around permission to write settings for other users.
837 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
838 final int callingUser = UserHandle.getCallingUserId();
839 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700840 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700841 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
842 "Not permitted to access settings for other users");
843 }
844
845 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
846 + " by " + callingUser);
847
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700848 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 if (TABLE_FAVORITES.equals(args.table)) {
850 return null;
851 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700852
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700853 // Special case LOCATION_PROVIDERS_ALLOWED.
854 // Support enabling/disabling a single provider (using "+" or "-" prefix)
855 String name = initialValues.getAsString(Settings.Secure.NAME);
856 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
857 if (!parseProviderList(url, initialValues)) return null;
858 }
859
Christopher Tatec221d2b2012-10-03 18:33:52 -0700860 // If this is an insert() of a key that has been migrated to the global store,
861 // redirect the operation to that store
862 if (name != null) {
863 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
864 if (!TABLE_GLOBAL.equals(args.table)) {
865 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
866 }
867 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
868 }
869 }
870
Christopher Tate34637e52012-10-04 15:00:00 -0700871 // Check write permissions only after determining which table the insert will touch
872 checkWritePermissions(args);
873
Christopher Tate06efb532012-08-24 15:29:27 -0700874 // The global table is stored under the owner, always
875 if (TABLE_GLOBAL.equals(args.table)) {
876 desiredUserHandle = UserHandle.USER_OWNER;
877 }
878
879 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800880 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
881 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
882 return Uri.withAppendedPath(url, name);
883 }
884
Christopher Tate06efb532012-08-24 15:29:27 -0700885 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
886 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700887 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700888 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700889 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700890 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700891 if (rowId <= 0) return null;
892
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800893 SettingsCache.populate(cache, initialValues); // before we notify
894
Christopher Tate78d2a662012-09-13 16:19:44 -0700895 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
896 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700897 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700898 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700899 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700900 return url;
901 }
902
903 @Override
904 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700905 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700906 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700907 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 if (TABLE_FAVORITES.equals(args.table)) {
909 return 0;
910 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
911 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700912 } else if (TABLE_GLOBAL.equals(args.table)) {
913 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700915 checkWritePermissions(args);
916
Christopher Tate06efb532012-08-24 15:29:27 -0700917 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
918 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700919 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700920 SQLiteDatabase db = dbH.getWritableDatabase();
921 int count = db.delete(args.table, args.where, args.args);
922 mutationCount.decrementAndGet();
923 if (count > 0) {
924 invalidateCache(callingUser, args.table); // before we notify
925 sendNotify(url, callingUser);
926 }
927 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700928 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
929 return count;
930 }
931
932 @Override
933 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700934 // NOTE: update() is never called by the front-end Settings API, and updates that
935 // wind up affecting rows in Secure that are globally shared will not have the
936 // intended effect (the update will be invisible to the rest of the system).
937 // This should have no practical effect, since writes to the Secure db can only
938 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700939 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700940 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700941 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (TABLE_FAVORITES.equals(args.table)) {
943 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700944 } else if (TABLE_GLOBAL.equals(args.table)) {
945 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700947 checkWritePermissions(args);
948
Christopher Tate06efb532012-08-24 15:29:27 -0700949 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
950 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700951 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700952 SQLiteDatabase db = dbH.getWritableDatabase();
953 int count = db.update(args.table, initialValues, args.where, args.args);
954 mutationCount.decrementAndGet();
955 if (count > 0) {
956 invalidateCache(callingUser, args.table); // before we notify
957 sendNotify(url, callingUser);
958 }
959 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700960 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
961 return count;
962 }
963
964 @Override
965 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
966
967 /*
968 * When a client attempts to openFile the default ringtone or
969 * notification setting Uri, we will proxy the call to the current
970 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700971 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972 int ringtoneType = RingtoneManager.getDefaultType(uri);
973 // Above call returns -1 if the Uri doesn't match a default type
974 if (ringtoneType != -1) {
975 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700976
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700977 // Get the current value for the default sound
978 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979
Marco Nelissen69f593c2009-07-28 09:55:04 -0700980 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700981 // Only proxy the openFile call to drm or media providers
982 String authority = soundUri.getAuthority();
983 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
984 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
985
986 if (isDrmAuthority) {
987 try {
988 // Check DRM access permission here, since once we
989 // do the below call the DRM will be checking our
990 // permission, not our caller's permission
991 DrmStore.enforceAccessDrmPermission(context);
992 } catch (SecurityException e) {
993 throw new FileNotFoundException(e.getMessage());
994 }
995 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700996
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700997 return context.getContentResolver().openFileDescriptor(soundUri, mode);
998 }
999 }
1000 }
1001
1002 return super.openFile(uri, mode);
1003 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001004
1005 @Override
1006 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1007
1008 /*
1009 * When a client attempts to openFile the default ringtone or
1010 * notification setting Uri, we will proxy the call to the current
1011 * default ringtone's Uri (if it is in the DRM or media provider).
1012 */
1013 int ringtoneType = RingtoneManager.getDefaultType(uri);
1014 // Above call returns -1 if the Uri doesn't match a default type
1015 if (ringtoneType != -1) {
1016 Context context = getContext();
1017
1018 // Get the current value for the default sound
1019 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1020
1021 if (soundUri != null) {
1022 // Only proxy the openFile call to drm or media providers
1023 String authority = soundUri.getAuthority();
1024 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1025 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1026
1027 if (isDrmAuthority) {
1028 try {
1029 // Check DRM access permission here, since once we
1030 // do the below call the DRM will be checking our
1031 // permission, not our caller's permission
1032 DrmStore.enforceAccessDrmPermission(context);
1033 } catch (SecurityException e) {
1034 throw new FileNotFoundException(e.getMessage());
1035 }
1036 }
1037
1038 ParcelFileDescriptor pfd = null;
1039 try {
1040 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1041 return new AssetFileDescriptor(pfd, 0, -1);
1042 } catch (FileNotFoundException ex) {
1043 // fall through and open the fallback ringtone below
1044 }
1045 }
1046
1047 try {
1048 return super.openAssetFile(soundUri, mode);
1049 } catch (FileNotFoundException ex) {
1050 // Since a non-null Uri was specified, but couldn't be opened,
1051 // fall back to the built-in ringtone.
1052 return context.getResources().openRawResourceFd(
1053 com.android.internal.R.raw.fallbackring);
1054 }
1055 }
1056 // no need to fall through and have openFile() try again, since we
1057 // already know that will fail.
1058 throw new FileNotFoundException(); // or return null ?
1059 }
1060
1061 // Note that this will end up calling openFile() above.
1062 return super.openAssetFile(uri, mode);
1063 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001064
1065 /**
1066 * In-memory LRU Cache of system and secure settings, along with
1067 * associated helper functions to keep cache coherent with the
1068 * database.
1069 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001070 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001071
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001072 private final String mCacheName;
1073 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1074
1075 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001076 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001077 mCacheName = name;
1078 }
1079
1080 /**
1081 * Is the whole database table slurped into this cache?
1082 */
1083 public boolean fullyMatchesDisk() {
1084 synchronized (this) {
1085 return mCacheFullyMatchesDisk;
1086 }
1087 }
1088
1089 public void setFullyMatchesDisk(boolean value) {
1090 synchronized (this) {
1091 mCacheFullyMatchesDisk = value;
1092 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001093 }
1094
1095 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001096 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1097 if (evicted) {
1098 mCacheFullyMatchesDisk = false;
1099 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001100 }
1101
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001102 /**
1103 * Atomic cache population, conditional on size of value and if
1104 * we lost a race.
1105 *
1106 * @returns a Bundle to send back to the client from call(), even
1107 * if we lost the race.
1108 */
1109 public Bundle putIfAbsent(String key, String value) {
1110 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1111 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1112 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001113 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001114 put(key, bundle);
1115 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001116 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001117 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001118 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001119 }
1120
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001121 /**
1122 * Populates a key in a given (possibly-null) cache.
1123 */
1124 public static void populate(SettingsCache cache, ContentValues contentValues) {
1125 if (cache == null) {
1126 return;
1127 }
1128 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1129 if (name == null) {
1130 Log.w(TAG, "null name populating settings cache.");
1131 return;
1132 }
1133 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001134 cache.populate(name, value);
1135 }
1136
1137 public void populate(String name, String value) {
1138 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001139 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001140 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001141 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001142 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001143 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001144 }
1145 }
1146
1147 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001148 * For suppressing duplicate/redundant settings inserts early,
1149 * checking our cache first (but without faulting it in),
1150 * before going to sqlite with the mutation.
1151 */
1152 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1153 if (cache == null) return false;
1154 synchronized (cache) {
1155 Bundle bundle = cache.get(name);
1156 if (bundle == null) return false;
1157 String oldValue = bundle.getPairValue();
1158 if (oldValue == null && value == null) return true;
1159 if ((oldValue == null) != (value == null)) return false;
1160 return oldValue.equals(value);
1161 }
1162 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001163 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001164}