blob: 017750443736813a2ba670650e36566284f2a0d5 [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;
Dianne Hackborn961321f2013-02-05 17:22:41 -080026import android.app.AppOpsManager;
Christopher Tate45281862010-03-05 15:46:30 -080027import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029import android.content.ContentProvider;
30import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070033import android.content.Intent;
34import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Marco Nelissen69f593c2009-07-28 09:55:04 -070036import android.content.res.AssetFileDescriptor;
Christopher Tateafccaa82012-10-03 17:41:51 -070037import android.database.AbstractCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080040import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.sqlite.SQLiteQueryBuilder;
42import android.media.RingtoneManager;
43import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070044import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070046import android.os.DropBoxManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070047import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.os.ParcelFileDescriptor;
49import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070050import android.os.UserHandle;
51import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.provider.DrmStore;
53import android.provider.MediaStore;
54import android.provider.Settings;
55import android.text.TextUtils;
56import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080057import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070058import android.util.Slog;
59import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061public class SettingsProvider extends ContentProvider {
62 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070063 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064
Christopher Tate06efb532012-08-24 15:29:27 -070065 private static final String TABLE_SYSTEM = "system";
66 private static final String TABLE_SECURE = "secure";
67 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 private static final String TABLE_FAVORITES = "favorites";
69 private static final String TABLE_OLD_FAVORITES = "old_favorites";
70
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080071 private static final String[] COLUMN_VALUE = new String[] { "value" };
72
Christopher Tate06efb532012-08-24 15:29:27 -070073 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080074 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070075 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070076 private static final SparseArray<SettingsCache> sSystemCaches
77 = new SparseArray<SettingsCache>();
78 private static final SparseArray<SettingsCache> sSecureCaches
79 = new SparseArray<SettingsCache>();
80 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070081
82 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070083 // database mutations are currently being handled for this user.
84 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070085 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070086 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
87 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080088
Christopher Tate78d2a662012-09-13 16:19:44 -070089 // Each defined user has their own settings
90 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
91
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080092 // Over this size we don't reject loading or saving settings but
93 // we do consider them broken/malicious and don't keep them in
94 // memory at least:
95 private static final int MAX_CACHE_ENTRY_SIZE = 500;
96
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080097 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
98
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070099 // Used as a sentinel value in an instance equality test when we
100 // want to cache the existence of a key, but not store its value.
101 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
102
Christopher Tate06efb532012-08-24 15:29:27 -0700103 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700104 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105
106 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700107 * Settings which need to be treated as global/shared in multi-user environments.
108 */
109 static final HashSet<String> sSecureGlobalKeys;
110 static final HashSet<String> sSystemGlobalKeys;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700111
112 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
113
Christopher Tate06efb532012-08-24 15:29:27 -0700114 static {
115 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
116 // table, shared across all users
117 // These must match Settings.Secure.MOVED_TO_GLOBAL
118 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700119 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700120
121 // Keys from the 'system' table now moved to 'global'
122 // These must match Settings.System.MOVED_TO_GLOBAL
123 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700124 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700125 }
126
127 private boolean settingMovedToGlobal(final String name) {
128 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
129 }
130
131 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700132 * Decode a content URL into the table, projection, and arguments
133 * used to access the corresponding database rows.
134 */
135 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700137 public final String where;
138 public final String[] args;
139
140 /** Operate on existing rows. */
141 SqlArguments(Uri url, String where, String[] args) {
142 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700143 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700145 if (!DatabaseHelper.isValidTable(this.table)) {
146 throw new IllegalArgumentException("Bad root path: " + this.table);
147 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700148 this.where = where;
149 this.args = args;
150 } else if (url.getPathSegments().size() != 2) {
151 throw new IllegalArgumentException("Invalid URI: " + url);
152 } else if (!TextUtils.isEmpty(where)) {
153 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
154 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700155 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700156 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700157 if (!DatabaseHelper.isValidTable(this.table)) {
158 throw new IllegalArgumentException("Bad root path: " + this.table);
159 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700160 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
161 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700163 final String name = url.getPathSegments().get(1);
164 this.args = new String[] { name };
165 // Rewrite the table for known-migrated names
166 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
167 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
168 this.table = TABLE_GLOBAL;
169 }
170 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700171 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700172 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700173 this.where = "_id=" + ContentUris.parseId(url);
174 this.args = null;
175 }
176 }
177 }
178
179 /** Insert new rows (no where clause allowed). */
180 SqlArguments(Uri url) {
181 if (url.getPathSegments().size() == 1) {
182 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700183 if (!DatabaseHelper.isValidTable(this.table)) {
184 throw new IllegalArgumentException("Bad root path: " + this.table);
185 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700186 this.where = null;
187 this.args = null;
188 } else {
189 throw new IllegalArgumentException("Invalid URI: " + url);
190 }
191 }
192 }
193
194 /**
195 * Get the content URI of a row added to a table.
196 * @param tableUri of the entire table
197 * @param values found in the row
198 * @param rowId of the row
199 * @return the content URI for this particular row
200 */
201 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
202 if (tableUri.getPathSegments().size() != 1) {
203 throw new IllegalArgumentException("Invalid URI: " + tableUri);
204 }
205 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700206 if (TABLE_SYSTEM.equals(table) ||
207 TABLE_SECURE.equals(table) ||
208 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700209 String name = values.getAsString(Settings.NameValueTable.NAME);
210 return Uri.withAppendedPath(tableUri, name);
211 } else {
212 return ContentUris.withAppendedId(tableUri, rowId);
213 }
214 }
215
216 /**
217 * Send a notification when a particular content URI changes.
218 * Modify the system property used to communicate the version of
219 * this table, for tables which have such a property. (The Settings
220 * contract class uses these to provide client-side caches.)
221 * @param uri to send notifications for
222 */
Christopher Tate06efb532012-08-24 15:29:27 -0700223 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700224 // Update the system property *first*, so if someone is listening for
225 // a notification and then using the contract class to get their data,
226 // the system property will be updated and they'll get the new data.
227
Amith Yamasanid1582142009-07-08 20:04:55 -0700228 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700230 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700231 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700232 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700233 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700234 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700235 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700236 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700237 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700238 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700239 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700240 }
241
242 if (property != null) {
243 long version = SystemProperties.getLong(property, 0) + 1;
244 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
245 SystemProperties.set(property, Long.toString(version));
246 }
247
-b master501eec92009-07-06 13:53:11 -0700248 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700249 if (backedUpDataChanged) {
250 mBackupManager.dataChanged();
251 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252 // Now send the notification through the content framework.
253
254 String notify = uri.getQueryParameter("notify");
255 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700256 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700257 final long oldId = Binder.clearCallingIdentity();
258 try {
259 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
260 } finally {
261 Binder.restoreCallingIdentity(oldId);
262 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700263 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700264 } else {
265 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
266 }
267 }
268
269 /**
270 * Make sure the caller has permission to write this data.
271 * @param args supplied by the caller
272 * @throws SecurityException if the caller is forbidden to write.
273 */
274 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700275 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800276 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800277 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
278 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700279 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800280 String.format("Permission denial: writing to secure settings requires %1$s",
281 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700282 }
283 }
284
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700285 // FileObserver for external modifications to the database file.
286 // Note that this is for platform developers only with
287 // userdebug/eng builds who should be able to tinker with the
288 // sqlite database out from under the SettingsProvider, which is
289 // normally the exclusive owner of the database. But we keep this
290 // enabled all the time to minimize development-vs-user
291 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700292 private static SparseArray<SettingsFileObserver> sObserverInstances
293 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700294 private class SettingsFileObserver extends FileObserver {
295 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700296 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700297 private final String mPath;
298
Christopher Tate06efb532012-08-24 15:29:27 -0700299 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700300 super(path, FileObserver.CLOSE_WRITE |
301 FileObserver.CREATE | FileObserver.DELETE |
302 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700303 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700304 mPath = path;
305 }
306
307 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700308 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700309 if (modsInFlight > 0) {
310 // our own modification.
311 return;
312 }
Christopher Tate06efb532012-08-24 15:29:27 -0700313 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
314 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700315 if (!mIsDirty.compareAndSet(false, true)) {
316 // already handled. (we get a few update events
317 // during an sqlite write)
318 return;
319 }
Christopher Tate06efb532012-08-24 15:29:27 -0700320 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
321 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700322 mIsDirty.set(false);
323 }
324 }
325
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700326 @Override
327 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700328 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700329 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800330
Dianne Hackborn961321f2013-02-05 17:22:41 -0800331 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700332 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700333
Christopher Tate78d2a662012-09-13 16:19:44 -0700334 IntentFilter userFilter = new IntentFilter();
335 userFilter.addAction(Intent.ACTION_USER_REMOVED);
336 getContext().registerReceiver(new BroadcastReceiver() {
337 @Override
338 public void onReceive(Context context, Intent intent) {
339 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
340 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
341 UserHandle.USER_OWNER);
342 if (userHandle != UserHandle.USER_OWNER) {
343 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700344 }
345 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700346 }
347 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700348 return true;
349 }
350
Christopher Tate06efb532012-08-24 15:29:27 -0700351 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700352 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700353 // the db file itself will be deleted automatically, but we need to tear down
354 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700355 FileObserver observer = sObserverInstances.get(userHandle);
356 if (observer != null) {
357 observer.stopWatching();
358 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700359 }
Christopher Tate06efb532012-08-24 15:29:27 -0700360
361 mOpenHelpers.delete(userHandle);
362 sSystemCaches.delete(userHandle);
363 sSecureCaches.delete(userHandle);
364 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700365 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700366 }
367
Christopher Tate78d2a662012-09-13 16:19:44 -0700368 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700369 if (LOCAL_LOGV) {
370 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
371 }
372
Christopher Tate78d2a662012-09-13 16:19:44 -0700373 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700374
Christopher Tate78d2a662012-09-13 16:19:44 -0700375 synchronized (this) {
376 dbhelper = mOpenHelpers.get(userHandle);
377 if (dbhelper == null) {
378 dbhelper = new DatabaseHelper(getContext(), userHandle);
379 mOpenHelpers.append(userHandle, dbhelper);
380
381 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
382 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
383 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
384 }
385 }
386
387 // Initialization of the db *outside* the locks. It's possible that racing
388 // threads might wind up here, the second having read the cache entries
389 // written by the first, but that's benign: the SQLite helper implementation
390 // manages concurrency itself, and it's important that we not run the db
391 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700392 SQLiteDatabase db = dbhelper.getWritableDatabase();
393
Christopher Tate78d2a662012-09-13 16:19:44 -0700394 // Watch for external modifications to the database files,
395 // keeping our caches in sync. We synchronize the observer set
396 // separately, and of course it has to run after the db file
397 // itself was set up by the DatabaseHelper.
398 synchronized (sObserverInstances) {
399 if (sObserverInstances.get(userHandle) == null) {
400 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
401 sObserverInstances.append(userHandle, observer);
402 observer.startWatching();
403 }
404 }
Christopher Tate06efb532012-08-24 15:29:27 -0700405
Christopher Tate4dc7a682012-09-11 12:15:49 -0700406 ensureAndroidIdIsSet(userHandle);
407
Christopher Tate06efb532012-08-24 15:29:27 -0700408 startAsyncCachePopulation(userHandle);
409 }
410
411 class CachePrefetchThread extends Thread {
412 private int mUserHandle;
413
414 CachePrefetchThread(int userHandle) {
415 super("populate-settings-caches");
416 mUserHandle = userHandle;
417 }
418
419 @Override
420 public void run() {
421 fullyPopulateCaches(mUserHandle);
422 }
423 }
424
425 private void startAsyncCachePopulation(int userHandle) {
426 new CachePrefetchThread(userHandle).start();
427 }
428
429 private void fullyPopulateCaches(final int userHandle) {
430 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
431 // Only populate the globals cache once, for the owning user
432 if (userHandle == UserHandle.USER_OWNER) {
433 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
434 }
435 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
436 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700437 }
438
439 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700440 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
441 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700442 Cursor c = db.query(
443 table,
444 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
445 null, null, null, null, null,
446 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
447 try {
448 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800449 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700450 cache.setFullyMatchesDisk(true); // optimistic
451 int rows = 0;
452 while (c.moveToNext()) {
453 rows++;
454 String name = c.getString(0);
455 String value = c.getString(1);
456 cache.populate(name, value);
457 }
458 if (rows > MAX_CACHE_ENTRIES) {
459 // Somewhat redundant, as removeEldestEntry() will
460 // have already done this, but to be explicit:
461 cache.setFullyMatchesDisk(false);
462 Log.d(TAG, "row count exceeds max cache entries for table " + table);
463 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800464 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
465 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700466 }
467 } finally {
468 c.close();
469 }
470 }
471
Christopher Tate4dc7a682012-09-11 12:15:49 -0700472 private boolean ensureAndroidIdIsSet(int userHandle) {
473 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800474 new String[] { Settings.NameValueTable.VALUE },
475 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700476 new String[] { Settings.Secure.ANDROID_ID }, null,
477 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800478 try {
479 final String value = c.moveToNext() ? c.getString(0) : null;
480 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700481 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800482 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800483 final ContentValues values = new ContentValues();
484 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
485 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700486 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800487 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700488 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800489 return false;
490 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700491 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
492 + "] for user " + userHandle);
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700493 // Write a dropbox entry if it's a restricted profile
494 if (mUserManager.getUserInfo(userHandle).isRestricted()) {
495 DropBoxManager dbm = (DropBoxManager)
496 getContext().getSystemService(Context.DROPBOX_SERVICE);
497 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
498 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
499 + ",restricted_profile_ssaid,"
500 + newAndroidIdValue + "\n");
501 }
502 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800503 }
504 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800505 } finally {
506 c.close();
507 }
508 }
509
Christopher Tate06efb532012-08-24 15:29:27 -0700510 // Lazy-initialize the settings caches for non-primary users
511 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700512 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
513 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700514 }
515
516 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700517 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700518 long oldId = Binder.clearCallingIdentity();
519 try {
520 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
521 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700522 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700523 dbHelper = mOpenHelpers.get(callingUser);
524 }
525 return dbHelper;
526 } finally {
527 Binder.restoreCallingIdentity(oldId);
528 }
529 }
530
531 public SettingsCache cacheForTable(final int callingUser, String tableName) {
532 if (TABLE_SYSTEM.equals(tableName)) {
533 return getOrConstructCache(callingUser, sSystemCaches);
534 }
535 if (TABLE_SECURE.equals(tableName)) {
536 return getOrConstructCache(callingUser, sSecureCaches);
537 }
538 if (TABLE_GLOBAL.equals(tableName)) {
539 return sGlobalCache;
540 }
541 return null;
542 }
543
544 /**
545 * Used for wiping a whole cache on deletes when we're not
546 * sure what exactly was deleted or changed.
547 */
548 public void invalidateCache(final int callingUser, String tableName) {
549 SettingsCache cache = cacheForTable(callingUser, tableName);
550 if (cache == null) {
551 return;
552 }
553 synchronized (cache) {
554 cache.evictAll();
555 cache.mCacheFullyMatchesDisk = false;
556 }
557 }
558
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800559 /**
560 * Fast path that avoids the use of chatty remoted Cursors.
561 */
562 @Override
Dianne Hackborn961321f2013-02-05 17:22:41 -0800563 public Bundle callFromPackage(String callingPackage, String method, String request,
564 Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700565 int callingUser = UserHandle.getCallingUserId();
566 if (args != null) {
567 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
568 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700569 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
570 Binder.getCallingUid(), reqUser, false, true,
571 "get/set setting for user", null);
572 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700573 }
574 }
575
Christopher Tate61695ff2012-10-05 12:05:13 -0700576 // Note: we assume that get/put operations for moved-to-global names have already
577 // been directed to the new location on the caller side (otherwise we'd fix them
578 // up here).
579 DatabaseHelper dbHelper;
580 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700581
Christopher Tate61695ff2012-10-05 12:05:13 -0700582 // Get methods
583 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
584 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
585 dbHelper = getOrEstablishDatabase(callingUser);
586 cache = sSystemCaches.get(callingUser);
587 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
588 }
589 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
590 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
591 dbHelper = getOrEstablishDatabase(callingUser);
592 cache = sSecureCaches.get(callingUser);
593 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
594 }
595 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
596 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
597 // fast path: owner db & cache are immutable after onCreate() so we need not
598 // guard on the attempt to look them up
599 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
600 sGlobalCache, request);
601 }
Christopher Tate06efb532012-08-24 15:29:27 -0700602
Christopher Tate61695ff2012-10-05 12:05:13 -0700603 // Put methods - new value is in the args bundle under the key named by
604 // the Settings.NameValueTable.VALUE static.
605 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800606 ? null : args.getString(Settings.NameValueTable.VALUE);
607
608 // Framework can't do automatic permission checking for calls, so we need
609 // to do it here.
610 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
611 != PackageManager.PERMISSION_GRANTED) {
612 throw new SecurityException(
613 String.format("Permission denial: writing to settings requires %1$s",
614 android.Manifest.permission.WRITE_SETTINGS));
615 }
616
617 // Also need to take care of app op.
618 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
619 callingPackage) != AppOpsManager.MODE_ALLOWED) {
620 return null;
621 }
Christopher Tate06efb532012-08-24 15:29:27 -0700622
Christopher Tate61695ff2012-10-05 12:05:13 -0700623 final ContentValues values = new ContentValues();
624 values.put(Settings.NameValueTable.NAME, request);
625 values.put(Settings.NameValueTable.VALUE, newValue);
626 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
627 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
628 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
629 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
630 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
631 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
632 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
633 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
634 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
635 } else {
636 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700637 }
638
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800639 return null;
640 }
641
642 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
643 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700644 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
645 final SettingsCache cache, String key) {
646 if (cache == null) {
647 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
648 return null;
649 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800650 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800651 Bundle value = cache.get(key);
652 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700653 if (value != TOO_LARGE_TO_CACHE_MARKER) {
654 return value;
655 }
656 // else we fall through and read the value from disk
657 } else if (cache.fullyMatchesDisk()) {
658 // Fast path (very common). Don't even try touch disk
659 // if we know we've slurped it all in. Trying to
660 // touch the disk would mean waiting for yaffs2 to
661 // give us access, which could takes hundreds of
662 // milliseconds. And we're very likely being called
663 // from somebody's UI thread...
664 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800665 }
666 }
667
Christopher Tate06efb532012-08-24 15:29:27 -0700668 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800669 Cursor cursor = null;
670 try {
671 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
672 null, null, null, null);
673 if (cursor != null && cursor.getCount() == 1) {
674 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800675 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800676 }
677 } catch (SQLiteException e) {
678 Log.w(TAG, "settings lookup error", e);
679 return null;
680 } finally {
681 if (cursor != null) cursor.close();
682 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800683 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800684 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800685 }
686
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700687 @Override
688 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700689 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
690 }
691
Christopher Tateb7564452012-09-19 16:21:18 -0700692 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700693 String sort, int forUser) {
694 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700695 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700696 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700697 dbH = getOrEstablishDatabase(
698 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700699 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800701 // The favorites table was moved from this provider to a provider inside Home
702 // Home still need to query this table to upgrade from pre-cupcake builds
703 // However, a cupcake+ build with no data does not contain this table which will
704 // cause an exception in the SQL stack. The following line is a special case to
705 // 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 -0800706 if (TABLE_FAVORITES.equals(args.table)) {
707 return null;
708 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
709 args.table = TABLE_FAVORITES;
710 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
711 if (cursor != null) {
712 boolean exists = cursor.getCount() > 0;
713 cursor.close();
714 if (!exists) return null;
715 } else {
716 return null;
717 }
718 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800719
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700720 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
721 qb.setTables(args.table);
722
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700723 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700724 // the default Cursor interface does not support per-user observation
725 try {
726 AbstractCursor c = (AbstractCursor) ret;
727 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
728 } catch (ClassCastException e) {
729 // details of the concrete Cursor implementation have changed and this code has
730 // not been updated to match -- complain and fail hard.
731 Log.wtf(TAG, "Incompatible cursor derivation!");
732 throw e;
733 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700734 return ret;
735 }
736
737 @Override
738 public String getType(Uri url) {
739 // If SqlArguments supplies a where clause, then it must be an item
740 // (because we aren't supplying our own where clause).
741 SqlArguments args = new SqlArguments(url, null, null);
742 if (TextUtils.isEmpty(args.where)) {
743 return "vnd.android.cursor.dir/" + args.table;
744 } else {
745 return "vnd.android.cursor.item/" + args.table;
746 }
747 }
748
749 @Override
750 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700751 final int callingUser = UserHandle.getCallingUserId();
752 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700753 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 if (TABLE_FAVORITES.equals(args.table)) {
755 return 0;
756 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700757 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700758 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700759
Christopher Tate06efb532012-08-24 15:29:27 -0700760 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
761 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700762 DatabaseHelper dbH = getOrEstablishDatabase(
763 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700764 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700765 db.beginTransaction();
766 try {
767 int numValues = values.length;
768 for (int i = 0; i < numValues; i++) {
769 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800770 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700771 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
772 }
773 db.setTransactionSuccessful();
774 } finally {
775 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700776 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700777 }
778
Christopher Tate06efb532012-08-24 15:29:27 -0700779 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700780 return values.length;
781 }
782
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700783 /*
784 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
785 * This setting contains a list of the currently enabled location providers.
786 * But helper functions in android.providers.Settings can enable or disable
787 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800788 *
789 * @returns whether the database needs to be updated or not, also modifying
790 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700791 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500792 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700793 String value = initialValues.getAsString(Settings.Secure.VALUE);
794 String newProviders = null;
795 if (value != null && value.length() > 1) {
796 char prefix = value.charAt(0);
797 if (prefix == '+' || prefix == '-') {
798 // skip prefix
799 value = value.substring(1);
800
801 // read list of enabled providers into "providers"
802 String providers = "";
803 String[] columns = {Settings.Secure.VALUE};
804 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -0500805 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700806 if (cursor != null && cursor.getCount() == 1) {
807 try {
808 cursor.moveToFirst();
809 providers = cursor.getString(0);
810 } finally {
811 cursor.close();
812 }
813 }
814
815 int index = providers.indexOf(value);
816 int end = index + value.length();
817 // check for commas to avoid matching on partial string
818 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
819 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
820
821 if (prefix == '+' && index < 0) {
822 // append the provider to the list if not present
823 if (providers.length() == 0) {
824 newProviders = value;
825 } else {
826 newProviders = providers + ',' + value;
827 }
828 } else if (prefix == '-' && index >= 0) {
829 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400830 // remove leading or trailing comma
831 if (index > 0) {
832 index--;
833 } else if (end < providers.length()) {
834 end++;
835 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700836
837 newProviders = providers.substring(0, index);
838 if (end < providers.length()) {
839 newProviders += providers.substring(end);
840 }
841 } else {
842 // nothing changed, so no need to update the database
843 return false;
844 }
845
846 if (newProviders != null) {
847 initialValues.put(Settings.Secure.VALUE, newProviders);
848 }
849 }
850 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800851
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700852 return true;
853 }
854
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700855 @Override
856 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700857 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
858 }
859
860 // Settings.put*ForUser() always winds up here, so this is where we apply
861 // policy around permission to write settings for other users.
862 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
863 final int callingUser = UserHandle.getCallingUserId();
864 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700865 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700866 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
867 "Not permitted to access settings for other users");
868 }
869
870 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
871 + " by " + callingUser);
872
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700873 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 if (TABLE_FAVORITES.equals(args.table)) {
875 return null;
876 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700877
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700878 // Special case LOCATION_PROVIDERS_ALLOWED.
879 // Support enabling/disabling a single provider (using "+" or "-" prefix)
880 String name = initialValues.getAsString(Settings.Secure.NAME);
881 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -0500882 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700883 }
884
Christopher Tatec221d2b2012-10-03 18:33:52 -0700885 // If this is an insert() of a key that has been migrated to the global store,
886 // redirect the operation to that store
887 if (name != null) {
888 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
889 if (!TABLE_GLOBAL.equals(args.table)) {
890 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
891 }
892 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
893 }
894 }
895
Christopher Tate34637e52012-10-04 15:00:00 -0700896 // Check write permissions only after determining which table the insert will touch
897 checkWritePermissions(args);
898
Christopher Tate06efb532012-08-24 15:29:27 -0700899 // The global table is stored under the owner, always
900 if (TABLE_GLOBAL.equals(args.table)) {
901 desiredUserHandle = UserHandle.USER_OWNER;
902 }
903
904 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800905 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
906 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
907 return Uri.withAppendedPath(url, name);
908 }
909
Christopher Tate06efb532012-08-24 15:29:27 -0700910 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
911 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700912 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700913 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700914 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700915 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700916 if (rowId <= 0) return null;
917
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800918 SettingsCache.populate(cache, initialValues); // before we notify
919
Christopher Tate78d2a662012-09-13 16:19:44 -0700920 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
921 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700922 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700923 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700924 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700925 return url;
926 }
927
928 @Override
929 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700930 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700931 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700932 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 if (TABLE_FAVORITES.equals(args.table)) {
934 return 0;
935 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
936 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700937 } else if (TABLE_GLOBAL.equals(args.table)) {
938 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700940 checkWritePermissions(args);
941
Christopher Tate06efb532012-08-24 15:29:27 -0700942 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
943 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700944 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700945 SQLiteDatabase db = dbH.getWritableDatabase();
946 int count = db.delete(args.table, args.where, args.args);
947 mutationCount.decrementAndGet();
948 if (count > 0) {
949 invalidateCache(callingUser, args.table); // before we notify
950 sendNotify(url, callingUser);
951 }
952 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700953 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
954 return count;
955 }
956
957 @Override
958 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700959 // NOTE: update() is never called by the front-end Settings API, and updates that
960 // wind up affecting rows in Secure that are globally shared will not have the
961 // intended effect (the update will be invisible to the rest of the system).
962 // This should have no practical effect, since writes to the Secure db can only
963 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700964 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700965 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700966 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 if (TABLE_FAVORITES.equals(args.table)) {
968 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700969 } else if (TABLE_GLOBAL.equals(args.table)) {
970 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972 checkWritePermissions(args);
973
Christopher Tate06efb532012-08-24 15:29:27 -0700974 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
975 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700976 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700977 SQLiteDatabase db = dbH.getWritableDatabase();
978 int count = db.update(args.table, initialValues, args.where, args.args);
979 mutationCount.decrementAndGet();
980 if (count > 0) {
981 invalidateCache(callingUser, args.table); // before we notify
982 sendNotify(url, callingUser);
983 }
984 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700985 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
986 return count;
987 }
988
989 @Override
990 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
991
992 /*
993 * When a client attempts to openFile the default ringtone or
994 * notification setting Uri, we will proxy the call to the current
995 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700996 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700997 int ringtoneType = RingtoneManager.getDefaultType(uri);
998 // Above call returns -1 if the Uri doesn't match a default type
999 if (ringtoneType != -1) {
1000 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001001
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001002 // Get the current value for the default sound
1003 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001004
Marco Nelissen69f593c2009-07-28 09:55:04 -07001005 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001006 // Only proxy the openFile call to drm or media providers
1007 String authority = soundUri.getAuthority();
1008 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1009 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1010
1011 if (isDrmAuthority) {
1012 try {
1013 // Check DRM access permission here, since once we
1014 // do the below call the DRM will be checking our
1015 // permission, not our caller's permission
1016 DrmStore.enforceAccessDrmPermission(context);
1017 } catch (SecurityException e) {
1018 throw new FileNotFoundException(e.getMessage());
1019 }
1020 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001021
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001022 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1023 }
1024 }
1025 }
1026
1027 return super.openFile(uri, mode);
1028 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001029
1030 @Override
1031 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1032
1033 /*
1034 * When a client attempts to openFile the default ringtone or
1035 * notification setting Uri, we will proxy the call to the current
1036 * default ringtone's Uri (if it is in the DRM or media provider).
1037 */
1038 int ringtoneType = RingtoneManager.getDefaultType(uri);
1039 // Above call returns -1 if the Uri doesn't match a default type
1040 if (ringtoneType != -1) {
1041 Context context = getContext();
1042
1043 // Get the current value for the default sound
1044 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1045
1046 if (soundUri != null) {
1047 // Only proxy the openFile call to drm or media providers
1048 String authority = soundUri.getAuthority();
1049 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1050 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1051
1052 if (isDrmAuthority) {
1053 try {
1054 // Check DRM access permission here, since once we
1055 // do the below call the DRM will be checking our
1056 // permission, not our caller's permission
1057 DrmStore.enforceAccessDrmPermission(context);
1058 } catch (SecurityException e) {
1059 throw new FileNotFoundException(e.getMessage());
1060 }
1061 }
1062
1063 ParcelFileDescriptor pfd = null;
1064 try {
1065 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1066 return new AssetFileDescriptor(pfd, 0, -1);
1067 } catch (FileNotFoundException ex) {
1068 // fall through and open the fallback ringtone below
1069 }
1070 }
1071
1072 try {
1073 return super.openAssetFile(soundUri, mode);
1074 } catch (FileNotFoundException ex) {
1075 // Since a non-null Uri was specified, but couldn't be opened,
1076 // fall back to the built-in ringtone.
1077 return context.getResources().openRawResourceFd(
1078 com.android.internal.R.raw.fallbackring);
1079 }
1080 }
1081 // no need to fall through and have openFile() try again, since we
1082 // already know that will fail.
1083 throw new FileNotFoundException(); // or return null ?
1084 }
1085
1086 // Note that this will end up calling openFile() above.
1087 return super.openAssetFile(uri, mode);
1088 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001089
1090 /**
1091 * In-memory LRU Cache of system and secure settings, along with
1092 * associated helper functions to keep cache coherent with the
1093 * database.
1094 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001095 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001096
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001097 private final String mCacheName;
1098 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1099
1100 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001101 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001102 mCacheName = name;
1103 }
1104
1105 /**
1106 * Is the whole database table slurped into this cache?
1107 */
1108 public boolean fullyMatchesDisk() {
1109 synchronized (this) {
1110 return mCacheFullyMatchesDisk;
1111 }
1112 }
1113
1114 public void setFullyMatchesDisk(boolean value) {
1115 synchronized (this) {
1116 mCacheFullyMatchesDisk = value;
1117 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001118 }
1119
1120 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001121 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1122 if (evicted) {
1123 mCacheFullyMatchesDisk = false;
1124 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001125 }
1126
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001127 /**
1128 * Atomic cache population, conditional on size of value and if
1129 * we lost a race.
1130 *
1131 * @returns a Bundle to send back to the client from call(), even
1132 * if we lost the race.
1133 */
1134 public Bundle putIfAbsent(String key, String value) {
1135 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1136 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1137 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001138 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001139 put(key, bundle);
1140 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001141 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001142 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001143 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001144 }
1145
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001146 /**
1147 * Populates a key in a given (possibly-null) cache.
1148 */
1149 public static void populate(SettingsCache cache, ContentValues contentValues) {
1150 if (cache == null) {
1151 return;
1152 }
1153 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1154 if (name == null) {
1155 Log.w(TAG, "null name populating settings cache.");
1156 return;
1157 }
1158 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001159 cache.populate(name, value);
1160 }
1161
1162 public void populate(String name, String value) {
1163 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001164 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001165 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001166 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001167 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001168 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001169 }
1170 }
1171
1172 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001173 * For suppressing duplicate/redundant settings inserts early,
1174 * checking our cache first (but without faulting it in),
1175 * before going to sqlite with the mutation.
1176 */
1177 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1178 if (cache == null) return false;
1179 synchronized (cache) {
1180 Bundle bundle = cache.get(name);
1181 if (bundle == null) return false;
1182 String oldValue = bundle.getPairValue();
1183 if (oldValue == null && value == null) return true;
1184 if ((oldValue == null) != (value == null)) return false;
1185 return oldValue.equals(value);
1186 }
1187 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001188 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001189}