blob: b1c218d3f5bb2d0f82b92124785e825864294ee0 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
-b master501eec92009-07-06 13:53:11 -070019import java.io.FileNotFoundException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080020import java.security.SecureRandom;
Christopher Tate06efb532012-08-24 15:29:27 -070021import java.util.HashSet;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070022import java.util.concurrent.atomic.AtomicBoolean;
23import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070024
Christopher Tated5fe1472012-09-10 15:48:38 -070025import android.app.ActivityManager;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070027import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentProvider;
29import android.content.ContentUris;
30import android.content.ContentValues;
31import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070032import android.content.Intent;
33import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.pm.PackageManager;
Marco Nelissen69f593c2009-07-28 09:55:04 -070035import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.Cursor;
37import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080038import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.database.sqlite.SQLiteQueryBuilder;
40import android.media.RingtoneManager;
41import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070044import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.os.ParcelFileDescriptor;
46import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070047import android.os.UserHandle;
48import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.provider.DrmStore;
50import android.provider.MediaStore;
51import android.provider.Settings;
52import android.text.TextUtils;
53import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080054import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.util.Slog;
56import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058public class SettingsProvider extends ContentProvider {
59 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070060 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061
Christopher Tate06efb532012-08-24 15:29:27 -070062 private static final String TABLE_SYSTEM = "system";
63 private static final String TABLE_SECURE = "secure";
64 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 private static final String TABLE_FAVORITES = "favorites";
66 private static final String TABLE_OLD_FAVORITES = "old_favorites";
67
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080068 private static final String[] COLUMN_VALUE = new String[] { "value" };
69
Christopher Tate06efb532012-08-24 15:29:27 -070070 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080071 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070072 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070073 private static final SparseArray<SettingsCache> sSystemCaches
74 = new SparseArray<SettingsCache>();
75 private static final SparseArray<SettingsCache> sSecureCaches
76 = new SparseArray<SettingsCache>();
77 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070078
79 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070080 // database mutations are currently being handled for this user.
81 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070083 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
84 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080085
Christopher Tate78d2a662012-09-13 16:19:44 -070086 // Each defined user has their own settings
87 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
88
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080089 // Over this size we don't reject loading or saving settings but
90 // we do consider them broken/malicious and don't keep them in
91 // memory at least:
92 private static final int MAX_CACHE_ENTRY_SIZE = 500;
93
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080094 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
95
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070096 // Used as a sentinel value in an instance equality test when we
97 // want to cache the existence of a key, but not store its value.
98 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
99
Christopher Tate06efb532012-08-24 15:29:27 -0700100 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700101 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102
103 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700104 * Settings which need to be treated as global/shared in multi-user environments.
105 */
106 static final HashSet<String> sSecureGlobalKeys;
107 static final HashSet<String> sSystemGlobalKeys;
108 static {
109 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
110 // table, shared across all users
111 // These must match Settings.Secure.MOVED_TO_GLOBAL
112 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700113 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700114
115 // Keys from the 'system' table now moved to 'global'
116 // These must match Settings.System.MOVED_TO_GLOBAL
117 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700118 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700119 }
120
121 private boolean settingMovedToGlobal(final String name) {
122 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
123 }
124
125 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700126 * Decode a content URL into the table, projection, and arguments
127 * used to access the corresponding database rows.
128 */
129 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700131 public final String where;
132 public final String[] args;
133
134 /** Operate on existing rows. */
135 SqlArguments(Uri url, String where, String[] args) {
136 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700137 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 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 {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700149 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700150 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700151 if (!DatabaseHelper.isValidTable(this.table)) {
152 throw new IllegalArgumentException("Bad root path: " + this.table);
153 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700154 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
155 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700156 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700157 final String name = url.getPathSegments().get(1);
158 this.args = new String[] { name };
159 // Rewrite the table for known-migrated names
160 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
161 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
162 this.table = TABLE_GLOBAL;
163 }
164 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700165 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700166 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167 this.where = "_id=" + ContentUris.parseId(url);
168 this.args = null;
169 }
170 }
171 }
172
173 /** Insert new rows (no where clause allowed). */
174 SqlArguments(Uri url) {
175 if (url.getPathSegments().size() == 1) {
176 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700177 if (!DatabaseHelper.isValidTable(this.table)) {
178 throw new IllegalArgumentException("Bad root path: " + this.table);
179 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700180 this.where = null;
181 this.args = null;
182 } else {
183 throw new IllegalArgumentException("Invalid URI: " + url);
184 }
185 }
186 }
187
188 /**
189 * Get the content URI of a row added to a table.
190 * @param tableUri of the entire table
191 * @param values found in the row
192 * @param rowId of the row
193 * @return the content URI for this particular row
194 */
195 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
196 if (tableUri.getPathSegments().size() != 1) {
197 throw new IllegalArgumentException("Invalid URI: " + tableUri);
198 }
199 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700200 if (TABLE_SYSTEM.equals(table) ||
201 TABLE_SECURE.equals(table) ||
202 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700203 String name = values.getAsString(Settings.NameValueTable.NAME);
204 return Uri.withAppendedPath(tableUri, name);
205 } else {
206 return ContentUris.withAppendedId(tableUri, rowId);
207 }
208 }
209
210 /**
211 * Send a notification when a particular content URI changes.
212 * Modify the system property used to communicate the version of
213 * this table, for tables which have such a property. (The Settings
214 * contract class uses these to provide client-side caches.)
215 * @param uri to send notifications for
216 */
Christopher Tate06efb532012-08-24 15:29:27 -0700217 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700218 // Update the system property *first*, so if someone is listening for
219 // a notification and then using the contract class to get their data,
220 // the system property will be updated and they'll get the new data.
221
Amith Yamasanid1582142009-07-08 20:04:55 -0700222 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700223 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700224 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700225 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700226 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700227 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700228 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700229 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700230 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700231 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700232 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700233 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700234 }
235
236 if (property != null) {
237 long version = SystemProperties.getLong(property, 0) + 1;
238 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
239 SystemProperties.set(property, Long.toString(version));
240 }
241
-b master501eec92009-07-06 13:53:11 -0700242 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700243 if (backedUpDataChanged) {
244 mBackupManager.dataChanged();
245 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 // Now send the notification through the content framework.
247
248 String notify = uri.getQueryParameter("notify");
249 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700250 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700251 final long oldId = Binder.clearCallingIdentity();
252 try {
253 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
254 } finally {
255 Binder.restoreCallingIdentity(oldId);
256 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700257 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 } else {
259 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
260 }
261 }
262
263 /**
264 * Make sure the caller has permission to write this data.
265 * @param args supplied by the caller
266 * @throws SecurityException if the caller is forbidden to write.
267 */
268 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700269 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800270 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800271 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
272 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700273 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800274 String.format("Permission denial: writing to secure settings requires %1$s",
275 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 }
277 }
278
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700279 // FileObserver for external modifications to the database file.
280 // Note that this is for platform developers only with
281 // userdebug/eng builds who should be able to tinker with the
282 // sqlite database out from under the SettingsProvider, which is
283 // normally the exclusive owner of the database. But we keep this
284 // enabled all the time to minimize development-vs-user
285 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700286 private static SparseArray<SettingsFileObserver> sObserverInstances
287 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700288 private class SettingsFileObserver extends FileObserver {
289 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700290 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700291 private final String mPath;
292
Christopher Tate06efb532012-08-24 15:29:27 -0700293 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700294 super(path, FileObserver.CLOSE_WRITE |
295 FileObserver.CREATE | FileObserver.DELETE |
296 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700297 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700298 mPath = path;
299 }
300
301 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700302 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700303 if (modsInFlight > 0) {
304 // our own modification.
305 return;
306 }
Christopher Tate06efb532012-08-24 15:29:27 -0700307 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
308 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700309 if (!mIsDirty.compareAndSet(false, true)) {
310 // already handled. (we get a few update events
311 // during an sqlite write)
312 return;
313 }
Christopher Tate06efb532012-08-24 15:29:27 -0700314 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
315 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700316 mIsDirty.set(false);
317 }
318 }
319
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700320 @Override
321 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700322 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700323 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800324
Christopher Tate78d2a662012-09-13 16:19:44 -0700325 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700326
Christopher Tate78d2a662012-09-13 16:19:44 -0700327 IntentFilter userFilter = new IntentFilter();
328 userFilter.addAction(Intent.ACTION_USER_REMOVED);
329 getContext().registerReceiver(new BroadcastReceiver() {
330 @Override
331 public void onReceive(Context context, Intent intent) {
332 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
333 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
334 UserHandle.USER_OWNER);
335 if (userHandle != UserHandle.USER_OWNER) {
336 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700337 }
338 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700339 }
340 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700341 return true;
342 }
343
Christopher Tate06efb532012-08-24 15:29:27 -0700344 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700345 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700346 // the db file itself will be deleted automatically, but we need to tear down
347 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700348 FileObserver observer = sObserverInstances.get(userHandle);
349 if (observer != null) {
350 observer.stopWatching();
351 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700352 }
Christopher Tate06efb532012-08-24 15:29:27 -0700353
354 mOpenHelpers.delete(userHandle);
355 sSystemCaches.delete(userHandle);
356 sSecureCaches.delete(userHandle);
357 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700358 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700359 }
360
Christopher Tate78d2a662012-09-13 16:19:44 -0700361 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700362 if (LOCAL_LOGV) {
363 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
364 }
365
Christopher Tate78d2a662012-09-13 16:19:44 -0700366 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700367
Christopher Tate78d2a662012-09-13 16:19:44 -0700368 synchronized (this) {
369 dbhelper = mOpenHelpers.get(userHandle);
370 if (dbhelper == null) {
371 dbhelper = new DatabaseHelper(getContext(), userHandle);
372 mOpenHelpers.append(userHandle, dbhelper);
373
374 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
375 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
376 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
377 }
378 }
379
380 // Initialization of the db *outside* the locks. It's possible that racing
381 // threads might wind up here, the second having read the cache entries
382 // written by the first, but that's benign: the SQLite helper implementation
383 // manages concurrency itself, and it's important that we not run the db
384 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700385 SQLiteDatabase db = dbhelper.getWritableDatabase();
386
Christopher Tate78d2a662012-09-13 16:19:44 -0700387 // Watch for external modifications to the database files,
388 // keeping our caches in sync. We synchronize the observer set
389 // separately, and of course it has to run after the db file
390 // itself was set up by the DatabaseHelper.
391 synchronized (sObserverInstances) {
392 if (sObserverInstances.get(userHandle) == null) {
393 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
394 sObserverInstances.append(userHandle, observer);
395 observer.startWatching();
396 }
397 }
Christopher Tate06efb532012-08-24 15:29:27 -0700398
Christopher Tate4dc7a682012-09-11 12:15:49 -0700399 ensureAndroidIdIsSet(userHandle);
400
Christopher Tate06efb532012-08-24 15:29:27 -0700401 startAsyncCachePopulation(userHandle);
402 }
403
404 class CachePrefetchThread extends Thread {
405 private int mUserHandle;
406
407 CachePrefetchThread(int userHandle) {
408 super("populate-settings-caches");
409 mUserHandle = userHandle;
410 }
411
412 @Override
413 public void run() {
414 fullyPopulateCaches(mUserHandle);
415 }
416 }
417
418 private void startAsyncCachePopulation(int userHandle) {
419 new CachePrefetchThread(userHandle).start();
420 }
421
422 private void fullyPopulateCaches(final int userHandle) {
423 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
424 // Only populate the globals cache once, for the owning user
425 if (userHandle == UserHandle.USER_OWNER) {
426 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
427 }
428 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
429 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700430 }
431
432 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700433 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
434 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700435 Cursor c = db.query(
436 table,
437 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
438 null, null, null, null, null,
439 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
440 try {
441 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800442 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700443 cache.setFullyMatchesDisk(true); // optimistic
444 int rows = 0;
445 while (c.moveToNext()) {
446 rows++;
447 String name = c.getString(0);
448 String value = c.getString(1);
449 cache.populate(name, value);
450 }
451 if (rows > MAX_CACHE_ENTRIES) {
452 // Somewhat redundant, as removeEldestEntry() will
453 // have already done this, but to be explicit:
454 cache.setFullyMatchesDisk(false);
455 Log.d(TAG, "row count exceeds max cache entries for table " + table);
456 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700457 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700458 cache.fullyMatchesDisk());
459 }
460 } finally {
461 c.close();
462 }
463 }
464
Christopher Tate4dc7a682012-09-11 12:15:49 -0700465 private boolean ensureAndroidIdIsSet(int userHandle) {
466 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800467 new String[] { Settings.NameValueTable.VALUE },
468 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700469 new String[] { Settings.Secure.ANDROID_ID }, null,
470 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800471 try {
472 final String value = c.moveToNext() ? c.getString(0) : null;
473 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700474 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800475 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800476 final ContentValues values = new ContentValues();
477 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
478 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700479 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800480 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700481 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800482 return false;
483 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700484 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
485 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800486 }
487 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800488 } finally {
489 c.close();
490 }
491 }
492
Christopher Tate06efb532012-08-24 15:29:27 -0700493 // Lazy-initialize the settings caches for non-primary users
494 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700495 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
496 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700497 }
498
499 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700500 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700501 long oldId = Binder.clearCallingIdentity();
502 try {
503 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
504 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700505 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700506 dbHelper = mOpenHelpers.get(callingUser);
507 }
508 return dbHelper;
509 } finally {
510 Binder.restoreCallingIdentity(oldId);
511 }
512 }
513
514 public SettingsCache cacheForTable(final int callingUser, String tableName) {
515 if (TABLE_SYSTEM.equals(tableName)) {
516 return getOrConstructCache(callingUser, sSystemCaches);
517 }
518 if (TABLE_SECURE.equals(tableName)) {
519 return getOrConstructCache(callingUser, sSecureCaches);
520 }
521 if (TABLE_GLOBAL.equals(tableName)) {
522 return sGlobalCache;
523 }
524 return null;
525 }
526
527 /**
528 * Used for wiping a whole cache on deletes when we're not
529 * sure what exactly was deleted or changed.
530 */
531 public void invalidateCache(final int callingUser, String tableName) {
532 SettingsCache cache = cacheForTable(callingUser, tableName);
533 if (cache == null) {
534 return;
535 }
536 synchronized (cache) {
537 cache.evictAll();
538 cache.mCacheFullyMatchesDisk = false;
539 }
540 }
541
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800542 /**
543 * Fast path that avoids the use of chatty remoted Cursors.
544 */
545 @Override
546 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700547 int callingUser = UserHandle.getCallingUserId();
548 if (args != null) {
549 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
550 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700551 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
552 Binder.getCallingUid(), reqUser, false, true,
553 "get/set setting for user", null);
554 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700555 }
556 }
557
Christopher Tateb7564452012-09-19 16:21:18 -0700558 // Okay, permission checks have cleared. Reset to our own identity so we can
559 // manipulate all users' data with impunity.
560 long oldId = Binder.clearCallingIdentity();
561 try {
562 // Note: we assume that get/put operations for moved-to-global names have already
563 // been directed to the new location on the caller side (otherwise we'd fix them
564 // up here).
565 DatabaseHelper dbHelper;
566 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700567
Christopher Tateb7564452012-09-19 16:21:18 -0700568 // Get methods
569 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
570 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
571 dbHelper = getOrEstablishDatabase(callingUser);
572 cache = sSystemCaches.get(callingUser);
573 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
574 }
575 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
576 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
577 dbHelper = getOrEstablishDatabase(callingUser);
578 cache = sSecureCaches.get(callingUser);
579 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
580 }
581 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
582 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
583 // fast path: owner db & cache are immutable after onCreate() so we need not
584 // guard on the attempt to look them up
585 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
586 sGlobalCache, request);
587 }
Christopher Tate06efb532012-08-24 15:29:27 -0700588
Christopher Tateb7564452012-09-19 16:21:18 -0700589 // Put methods - new value is in the args bundle under the key named by
590 // the Settings.NameValueTable.VALUE static.
591 final String newValue = (args == null)
592 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700593
Christopher Tateb7564452012-09-19 16:21:18 -0700594 final ContentValues values = new ContentValues();
595 values.put(Settings.NameValueTable.NAME, request);
596 values.put(Settings.NameValueTable.VALUE, newValue);
597 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
598 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
599 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
600 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
601 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
602 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
603 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
604 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
605 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
606 } else {
607 Slog.w(TAG, "call() with invalid method: " + method);
608 }
609 } finally {
610 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700611 }
612
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800613 return null;
614 }
615
616 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
617 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700618 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
619 final SettingsCache cache, String key) {
620 if (cache == null) {
621 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
622 return null;
623 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800624 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800625 Bundle value = cache.get(key);
626 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700627 if (value != TOO_LARGE_TO_CACHE_MARKER) {
628 return value;
629 }
630 // else we fall through and read the value from disk
631 } else if (cache.fullyMatchesDisk()) {
632 // Fast path (very common). Don't even try touch disk
633 // if we know we've slurped it all in. Trying to
634 // touch the disk would mean waiting for yaffs2 to
635 // give us access, which could takes hundreds of
636 // milliseconds. And we're very likely being called
637 // from somebody's UI thread...
638 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800639 }
640 }
641
Christopher Tate06efb532012-08-24 15:29:27 -0700642 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800643 Cursor cursor = null;
644 try {
645 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
646 null, null, null, null);
647 if (cursor != null && cursor.getCount() == 1) {
648 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800649 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800650 }
651 } catch (SQLiteException e) {
652 Log.w(TAG, "settings lookup error", e);
653 return null;
654 } finally {
655 if (cursor != null) cursor.close();
656 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800657 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800658 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800659 }
660
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700661 @Override
662 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700663 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
664 }
665
Christopher Tateb7564452012-09-19 16:21:18 -0700666 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700667 String sort, int forUser) {
668 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700669 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700670 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700671 dbH = getOrEstablishDatabase(
672 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700673 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800675 // The favorites table was moved from this provider to a provider inside Home
676 // Home still need to query this table to upgrade from pre-cupcake builds
677 // However, a cupcake+ build with no data does not contain this table which will
678 // cause an exception in the SQL stack. The following line is a special case to
679 // 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 -0800680 if (TABLE_FAVORITES.equals(args.table)) {
681 return null;
682 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
683 args.table = TABLE_FAVORITES;
684 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
685 if (cursor != null) {
686 boolean exists = cursor.getCount() > 0;
687 cursor.close();
688 if (!exists) return null;
689 } else {
690 return null;
691 }
692 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800693
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700694 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
695 qb.setTables(args.table);
696
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700697 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
698 ret.setNotificationUri(getContext().getContentResolver(), url);
699 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 Tatec221d2b2012-10-03 18:33:52 -0700851 // If this is an insert() of a key that has been migrated to the global store,
852 // redirect the operation to that store
853 if (name != null) {
854 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
855 if (!TABLE_GLOBAL.equals(args.table)) {
856 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
857 }
858 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
859 }
860 }
861
Christopher Tate06efb532012-08-24 15:29:27 -0700862 // The global table is stored under the owner, always
863 if (TABLE_GLOBAL.equals(args.table)) {
864 desiredUserHandle = UserHandle.USER_OWNER;
865 }
866
867 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800868 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
869 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
870 return Uri.withAppendedPath(url, name);
871 }
872
Christopher Tate06efb532012-08-24 15:29:27 -0700873 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
874 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700875 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700876 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700877 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700878 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700879 if (rowId <= 0) return null;
880
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800881 SettingsCache.populate(cache, initialValues); // before we notify
882
Christopher Tate78d2a662012-09-13 16:19:44 -0700883 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
884 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700885 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700886 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700887 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700888 return url;
889 }
890
891 @Override
892 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700893 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700894 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700895 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 if (TABLE_FAVORITES.equals(args.table)) {
897 return 0;
898 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
899 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700900 } else if (TABLE_GLOBAL.equals(args.table)) {
901 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700903 checkWritePermissions(args);
904
Christopher Tate06efb532012-08-24 15:29:27 -0700905 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
906 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700907 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700908 SQLiteDatabase db = dbH.getWritableDatabase();
909 int count = db.delete(args.table, args.where, args.args);
910 mutationCount.decrementAndGet();
911 if (count > 0) {
912 invalidateCache(callingUser, args.table); // before we notify
913 sendNotify(url, callingUser);
914 }
915 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700916 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
917 return count;
918 }
919
920 @Override
921 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700922 // NOTE: update() is never called by the front-end Settings API, and updates that
923 // wind up affecting rows in Secure that are globally shared will not have the
924 // intended effect (the update will be invisible to the rest of the system).
925 // This should have no practical effect, since writes to the Secure db can only
926 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700927 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700928 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700929 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 if (TABLE_FAVORITES.equals(args.table)) {
931 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700932 } else if (TABLE_GLOBAL.equals(args.table)) {
933 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700935 checkWritePermissions(args);
936
Christopher Tate06efb532012-08-24 15:29:27 -0700937 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
938 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700939 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700940 SQLiteDatabase db = dbH.getWritableDatabase();
941 int count = db.update(args.table, initialValues, args.where, args.args);
942 mutationCount.decrementAndGet();
943 if (count > 0) {
944 invalidateCache(callingUser, args.table); // before we notify
945 sendNotify(url, callingUser);
946 }
947 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700948 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
949 return count;
950 }
951
952 @Override
953 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
954
955 /*
956 * When a client attempts to openFile the default ringtone or
957 * notification setting Uri, we will proxy the call to the current
958 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700959 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700960 int ringtoneType = RingtoneManager.getDefaultType(uri);
961 // Above call returns -1 if the Uri doesn't match a default type
962 if (ringtoneType != -1) {
963 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700964
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 // Get the current value for the default sound
966 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700967
Marco Nelissen69f593c2009-07-28 09:55:04 -0700968 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700969 // Only proxy the openFile call to drm or media providers
970 String authority = soundUri.getAuthority();
971 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
972 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
973
974 if (isDrmAuthority) {
975 try {
976 // Check DRM access permission here, since once we
977 // do the below call the DRM will be checking our
978 // permission, not our caller's permission
979 DrmStore.enforceAccessDrmPermission(context);
980 } catch (SecurityException e) {
981 throw new FileNotFoundException(e.getMessage());
982 }
983 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700984
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700985 return context.getContentResolver().openFileDescriptor(soundUri, mode);
986 }
987 }
988 }
989
990 return super.openFile(uri, mode);
991 }
Marco Nelissen69f593c2009-07-28 09:55:04 -0700992
993 @Override
994 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
995
996 /*
997 * When a client attempts to openFile the default ringtone or
998 * notification setting Uri, we will proxy the call to the current
999 * default ringtone's Uri (if it is in the DRM or media provider).
1000 */
1001 int ringtoneType = RingtoneManager.getDefaultType(uri);
1002 // Above call returns -1 if the Uri doesn't match a default type
1003 if (ringtoneType != -1) {
1004 Context context = getContext();
1005
1006 // Get the current value for the default sound
1007 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1008
1009 if (soundUri != null) {
1010 // Only proxy the openFile call to drm or media providers
1011 String authority = soundUri.getAuthority();
1012 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1013 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1014
1015 if (isDrmAuthority) {
1016 try {
1017 // Check DRM access permission here, since once we
1018 // do the below call the DRM will be checking our
1019 // permission, not our caller's permission
1020 DrmStore.enforceAccessDrmPermission(context);
1021 } catch (SecurityException e) {
1022 throw new FileNotFoundException(e.getMessage());
1023 }
1024 }
1025
1026 ParcelFileDescriptor pfd = null;
1027 try {
1028 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1029 return new AssetFileDescriptor(pfd, 0, -1);
1030 } catch (FileNotFoundException ex) {
1031 // fall through and open the fallback ringtone below
1032 }
1033 }
1034
1035 try {
1036 return super.openAssetFile(soundUri, mode);
1037 } catch (FileNotFoundException ex) {
1038 // Since a non-null Uri was specified, but couldn't be opened,
1039 // fall back to the built-in ringtone.
1040 return context.getResources().openRawResourceFd(
1041 com.android.internal.R.raw.fallbackring);
1042 }
1043 }
1044 // no need to fall through and have openFile() try again, since we
1045 // already know that will fail.
1046 throw new FileNotFoundException(); // or return null ?
1047 }
1048
1049 // Note that this will end up calling openFile() above.
1050 return super.openAssetFile(uri, mode);
1051 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001052
1053 /**
1054 * In-memory LRU Cache of system and secure settings, along with
1055 * associated helper functions to keep cache coherent with the
1056 * database.
1057 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001058 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001059
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001060 private final String mCacheName;
1061 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1062
1063 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001064 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001065 mCacheName = name;
1066 }
1067
1068 /**
1069 * Is the whole database table slurped into this cache?
1070 */
1071 public boolean fullyMatchesDisk() {
1072 synchronized (this) {
1073 return mCacheFullyMatchesDisk;
1074 }
1075 }
1076
1077 public void setFullyMatchesDisk(boolean value) {
1078 synchronized (this) {
1079 mCacheFullyMatchesDisk = value;
1080 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001081 }
1082
1083 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001084 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1085 if (evicted) {
1086 mCacheFullyMatchesDisk = false;
1087 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001088 }
1089
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001090 /**
1091 * Atomic cache population, conditional on size of value and if
1092 * we lost a race.
1093 *
1094 * @returns a Bundle to send back to the client from call(), even
1095 * if we lost the race.
1096 */
1097 public Bundle putIfAbsent(String key, String value) {
1098 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1099 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1100 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001101 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001102 put(key, bundle);
1103 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001104 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001105 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001106 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001107 }
1108
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001109 /**
1110 * Populates a key in a given (possibly-null) cache.
1111 */
1112 public static void populate(SettingsCache cache, ContentValues contentValues) {
1113 if (cache == null) {
1114 return;
1115 }
1116 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1117 if (name == null) {
1118 Log.w(TAG, "null name populating settings cache.");
1119 return;
1120 }
1121 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001122 cache.populate(name, value);
1123 }
1124
1125 public void populate(String name, String value) {
1126 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001127 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001128 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001129 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001130 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001131 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001132 }
1133 }
1134
1135 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001136 * For suppressing duplicate/redundant settings inserts early,
1137 * checking our cache first (but without faulting it in),
1138 * before going to sqlite with the mutation.
1139 */
1140 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1141 if (cache == null) return false;
1142 synchronized (cache) {
1143 Bundle bundle = cache.get(name);
1144 if (bundle == null) return false;
1145 String oldValue = bundle.getPairValue();
1146 if (oldValue == null && value == null) return true;
1147 if ((oldValue == null) != (value == null)) return false;
1148 return oldValue.equals(value);
1149 }
1150 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001151 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001152}