blob: 659651b887c416e40c019a002c4cf60b781de34f [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;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070046import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070047import android.os.ParcelFileDescriptor;
48import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.UserHandle;
50import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070051import android.provider.DrmStore;
52import android.provider.MediaStore;
53import android.provider.Settings;
54import android.text.TextUtils;
55import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080056import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070057import android.util.Slog;
58import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060public class SettingsProvider extends ContentProvider {
61 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070062 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063
Christopher Tate06efb532012-08-24 15:29:27 -070064 private static final String TABLE_SYSTEM = "system";
65 private static final String TABLE_SECURE = "secure";
66 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 private static final String TABLE_FAVORITES = "favorites";
68 private static final String TABLE_OLD_FAVORITES = "old_favorites";
69
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080070 private static final String[] COLUMN_VALUE = new String[] { "value" };
71
Christopher Tate06efb532012-08-24 15:29:27 -070072 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080073 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070074 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070075 private static final SparseArray<SettingsCache> sSystemCaches
76 = new SparseArray<SettingsCache>();
77 private static final SparseArray<SettingsCache> sSecureCaches
78 = new SparseArray<SettingsCache>();
79 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070080
81 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070082 // database mutations are currently being handled for this user.
83 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070084 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070085 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
86 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080087
Christopher Tate78d2a662012-09-13 16:19:44 -070088 // Each defined user has their own settings
89 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
90
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080091 // Over this size we don't reject loading or saving settings but
92 // we do consider them broken/malicious and don't keep them in
93 // memory at least:
94 private static final int MAX_CACHE_ENTRY_SIZE = 500;
95
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080096 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
97
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070098 // Used as a sentinel value in an instance equality test when we
99 // want to cache the existence of a key, but not store its value.
100 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
101
Christopher Tate06efb532012-08-24 15:29:27 -0700102 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700103 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700104
105 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700106 * Settings which need to be treated as global/shared in multi-user environments.
107 */
108 static final HashSet<String> sSecureGlobalKeys;
109 static final HashSet<String> sSystemGlobalKeys;
110 static {
111 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
112 // table, shared across all users
113 // These must match Settings.Secure.MOVED_TO_GLOBAL
114 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700115 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700116
117 // Keys from the 'system' table now moved to 'global'
118 // These must match Settings.System.MOVED_TO_GLOBAL
119 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700120 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700121 }
122
123 private boolean settingMovedToGlobal(final String name) {
124 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
125 }
126
127 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700128 * Decode a content URL into the table, projection, and arguments
129 * used to access the corresponding database rows.
130 */
131 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133 public final String where;
134 public final String[] args;
135
136 /** Operate on existing rows. */
137 SqlArguments(Uri url, String where, String[] args) {
138 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700139 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700141 if (!DatabaseHelper.isValidTable(this.table)) {
142 throw new IllegalArgumentException("Bad root path: " + this.table);
143 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144 this.where = where;
145 this.args = args;
146 } else if (url.getPathSegments().size() != 2) {
147 throw new IllegalArgumentException("Invalid URI: " + url);
148 } else if (!TextUtils.isEmpty(where)) {
149 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
150 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700151 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700152 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700153 if (!DatabaseHelper.isValidTable(this.table)) {
154 throw new IllegalArgumentException("Bad root path: " + this.table);
155 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700156 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
157 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700158 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700159 final String name = url.getPathSegments().get(1);
160 this.args = new String[] { name };
161 // Rewrite the table for known-migrated names
162 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
163 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
164 this.table = TABLE_GLOBAL;
165 }
166 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700168 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700169 this.where = "_id=" + ContentUris.parseId(url);
170 this.args = null;
171 }
172 }
173 }
174
175 /** Insert new rows (no where clause allowed). */
176 SqlArguments(Uri url) {
177 if (url.getPathSegments().size() == 1) {
178 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700179 if (!DatabaseHelper.isValidTable(this.table)) {
180 throw new IllegalArgumentException("Bad root path: " + this.table);
181 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700182 this.where = null;
183 this.args = null;
184 } else {
185 throw new IllegalArgumentException("Invalid URI: " + url);
186 }
187 }
188 }
189
190 /**
191 * Get the content URI of a row added to a table.
192 * @param tableUri of the entire table
193 * @param values found in the row
194 * @param rowId of the row
195 * @return the content URI for this particular row
196 */
197 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
198 if (tableUri.getPathSegments().size() != 1) {
199 throw new IllegalArgumentException("Invalid URI: " + tableUri);
200 }
201 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700202 if (TABLE_SYSTEM.equals(table) ||
203 TABLE_SECURE.equals(table) ||
204 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700205 String name = values.getAsString(Settings.NameValueTable.NAME);
206 return Uri.withAppendedPath(tableUri, name);
207 } else {
208 return ContentUris.withAppendedId(tableUri, rowId);
209 }
210 }
211
212 /**
213 * Send a notification when a particular content URI changes.
214 * Modify the system property used to communicate the version of
215 * this table, for tables which have such a property. (The Settings
216 * contract class uses these to provide client-side caches.)
217 * @param uri to send notifications for
218 */
Christopher Tate06efb532012-08-24 15:29:27 -0700219 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700220 // Update the system property *first*, so if someone is listening for
221 // a notification and then using the contract class to get their data,
222 // the system property will be updated and they'll get the new data.
223
Amith Yamasanid1582142009-07-08 20:04:55 -0700224 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700225 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700226 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700227 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700228 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700229 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700230 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700231 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700232 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700233 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700234 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700235 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700236 }
237
238 if (property != null) {
239 long version = SystemProperties.getLong(property, 0) + 1;
240 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
241 SystemProperties.set(property, Long.toString(version));
242 }
243
-b master501eec92009-07-06 13:53:11 -0700244 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700245 if (backedUpDataChanged) {
246 mBackupManager.dataChanged();
247 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 // Now send the notification through the content framework.
249
250 String notify = uri.getQueryParameter("notify");
251 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700252 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700253 final long oldId = Binder.clearCallingIdentity();
254 try {
255 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
256 } finally {
257 Binder.restoreCallingIdentity(oldId);
258 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700259 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 } else {
261 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
262 }
263 }
264
265 /**
266 * Make sure the caller has permission to write this data.
267 * @param args supplied by the caller
268 * @throws SecurityException if the caller is forbidden to write.
269 */
270 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700271 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800272 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800273 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
274 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700275 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800276 String.format("Permission denial: writing to secure settings requires %1$s",
277 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278 }
279 }
280
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700281 // FileObserver for external modifications to the database file.
282 // Note that this is for platform developers only with
283 // userdebug/eng builds who should be able to tinker with the
284 // sqlite database out from under the SettingsProvider, which is
285 // normally the exclusive owner of the database. But we keep this
286 // enabled all the time to minimize development-vs-user
287 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700288 private static SparseArray<SettingsFileObserver> sObserverInstances
289 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700290 private class SettingsFileObserver extends FileObserver {
291 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700292 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700293 private final String mPath;
294
Christopher Tate06efb532012-08-24 15:29:27 -0700295 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700296 super(path, FileObserver.CLOSE_WRITE |
297 FileObserver.CREATE | FileObserver.DELETE |
298 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700299 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700300 mPath = path;
301 }
302
303 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700304 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700305 if (modsInFlight > 0) {
306 // our own modification.
307 return;
308 }
Christopher Tate06efb532012-08-24 15:29:27 -0700309 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
310 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700311 if (!mIsDirty.compareAndSet(false, true)) {
312 // already handled. (we get a few update events
313 // during an sqlite write)
314 return;
315 }
Christopher Tate06efb532012-08-24 15:29:27 -0700316 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
317 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700318 mIsDirty.set(false);
319 }
320 }
321
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700322 @Override
323 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700324 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700325 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800326
Dianne Hackborn961321f2013-02-05 17:22:41 -0800327 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700328 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700329
Christopher Tate78d2a662012-09-13 16:19:44 -0700330 IntentFilter userFilter = new IntentFilter();
331 userFilter.addAction(Intent.ACTION_USER_REMOVED);
332 getContext().registerReceiver(new BroadcastReceiver() {
333 @Override
334 public void onReceive(Context context, Intent intent) {
335 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
336 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
337 UserHandle.USER_OWNER);
338 if (userHandle != UserHandle.USER_OWNER) {
339 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700340 }
341 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700342 }
343 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700344 return true;
345 }
346
Christopher Tate06efb532012-08-24 15:29:27 -0700347 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700348 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700349 // the db file itself will be deleted automatically, but we need to tear down
350 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700351 FileObserver observer = sObserverInstances.get(userHandle);
352 if (observer != null) {
353 observer.stopWatching();
354 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700355 }
Christopher Tate06efb532012-08-24 15:29:27 -0700356
357 mOpenHelpers.delete(userHandle);
358 sSystemCaches.delete(userHandle);
359 sSecureCaches.delete(userHandle);
360 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700361 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700362 }
363
Christopher Tate78d2a662012-09-13 16:19:44 -0700364 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700365 if (LOCAL_LOGV) {
366 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
367 }
368
Christopher Tate78d2a662012-09-13 16:19:44 -0700369 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700370
Christopher Tate78d2a662012-09-13 16:19:44 -0700371 synchronized (this) {
372 dbhelper = mOpenHelpers.get(userHandle);
373 if (dbhelper == null) {
374 dbhelper = new DatabaseHelper(getContext(), userHandle);
375 mOpenHelpers.append(userHandle, dbhelper);
376
377 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
378 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
379 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
380 }
381 }
382
383 // Initialization of the db *outside* the locks. It's possible that racing
384 // threads might wind up here, the second having read the cache entries
385 // written by the first, but that's benign: the SQLite helper implementation
386 // manages concurrency itself, and it's important that we not run the db
387 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700388 SQLiteDatabase db = dbhelper.getWritableDatabase();
389
Christopher Tate78d2a662012-09-13 16:19:44 -0700390 // Watch for external modifications to the database files,
391 // keeping our caches in sync. We synchronize the observer set
392 // separately, and of course it has to run after the db file
393 // itself was set up by the DatabaseHelper.
394 synchronized (sObserverInstances) {
395 if (sObserverInstances.get(userHandle) == null) {
396 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
397 sObserverInstances.append(userHandle, observer);
398 observer.startWatching();
399 }
400 }
Christopher Tate06efb532012-08-24 15:29:27 -0700401
Christopher Tate4dc7a682012-09-11 12:15:49 -0700402 ensureAndroidIdIsSet(userHandle);
403
Christopher Tate06efb532012-08-24 15:29:27 -0700404 startAsyncCachePopulation(userHandle);
405 }
406
407 class CachePrefetchThread extends Thread {
408 private int mUserHandle;
409
410 CachePrefetchThread(int userHandle) {
411 super("populate-settings-caches");
412 mUserHandle = userHandle;
413 }
414
415 @Override
416 public void run() {
417 fullyPopulateCaches(mUserHandle);
418 }
419 }
420
421 private void startAsyncCachePopulation(int userHandle) {
422 new CachePrefetchThread(userHandle).start();
423 }
424
425 private void fullyPopulateCaches(final int userHandle) {
426 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
427 // Only populate the globals cache once, for the owning user
428 if (userHandle == UserHandle.USER_OWNER) {
429 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
430 }
431 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
432 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700433 }
434
435 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700436 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
437 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700438 Cursor c = db.query(
439 table,
440 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
441 null, null, null, null, null,
442 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
443 try {
444 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800445 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700446 cache.setFullyMatchesDisk(true); // optimistic
447 int rows = 0;
448 while (c.moveToNext()) {
449 rows++;
450 String name = c.getString(0);
451 String value = c.getString(1);
452 cache.populate(name, value);
453 }
454 if (rows > MAX_CACHE_ENTRIES) {
455 // Somewhat redundant, as removeEldestEntry() will
456 // have already done this, but to be explicit:
457 cache.setFullyMatchesDisk(false);
458 Log.d(TAG, "row count exceeds max cache entries for table " + table);
459 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800460 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
461 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700462 }
463 } finally {
464 c.close();
465 }
466 }
467
Christopher Tate4dc7a682012-09-11 12:15:49 -0700468 private boolean ensureAndroidIdIsSet(int userHandle) {
469 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800470 new String[] { Settings.NameValueTable.VALUE },
471 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700472 new String[] { Settings.Secure.ANDROID_ID }, null,
473 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800474 try {
475 final String value = c.moveToNext() ? c.getString(0) : null;
476 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700477 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800478 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800479 final ContentValues values = new ContentValues();
480 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
481 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700482 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800483 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700484 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800485 return false;
486 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700487 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
488 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800489 }
490 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800491 } finally {
492 c.close();
493 }
494 }
495
Christopher Tate06efb532012-08-24 15:29:27 -0700496 // Lazy-initialize the settings caches for non-primary users
497 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700498 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
499 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700500 }
501
502 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700503 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700504 long oldId = Binder.clearCallingIdentity();
505 try {
506 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
507 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700508 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700509 dbHelper = mOpenHelpers.get(callingUser);
510 }
511 return dbHelper;
512 } finally {
513 Binder.restoreCallingIdentity(oldId);
514 }
515 }
516
517 public SettingsCache cacheForTable(final int callingUser, String tableName) {
518 if (TABLE_SYSTEM.equals(tableName)) {
519 return getOrConstructCache(callingUser, sSystemCaches);
520 }
521 if (TABLE_SECURE.equals(tableName)) {
522 return getOrConstructCache(callingUser, sSecureCaches);
523 }
524 if (TABLE_GLOBAL.equals(tableName)) {
525 return sGlobalCache;
526 }
527 return null;
528 }
529
530 /**
531 * Used for wiping a whole cache on deletes when we're not
532 * sure what exactly was deleted or changed.
533 */
534 public void invalidateCache(final int callingUser, String tableName) {
535 SettingsCache cache = cacheForTable(callingUser, tableName);
536 if (cache == null) {
537 return;
538 }
539 synchronized (cache) {
540 cache.evictAll();
541 cache.mCacheFullyMatchesDisk = false;
542 }
543 }
544
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800545 /**
546 * Fast path that avoids the use of chatty remoted Cursors.
547 */
548 @Override
Dianne Hackborn961321f2013-02-05 17:22:41 -0800549 public Bundle callFromPackage(String callingPackage, String method, String request,
550 Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700551 int callingUser = UserHandle.getCallingUserId();
552 if (args != null) {
553 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
554 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700555 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
556 Binder.getCallingUid(), reqUser, false, true,
557 "get/set setting for user", null);
558 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700559 }
560 }
561
Christopher Tate61695ff2012-10-05 12:05:13 -0700562 // 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 Tate61695ff2012-10-05 12:05:13 -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 Tate61695ff2012-10-05 12:05:13 -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)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800592 ? null : args.getString(Settings.NameValueTable.VALUE);
593
594 // Framework can't do automatic permission checking for calls, so we need
595 // to do it here.
596 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
597 != PackageManager.PERMISSION_GRANTED) {
598 throw new SecurityException(
599 String.format("Permission denial: writing to settings requires %1$s",
600 android.Manifest.permission.WRITE_SETTINGS));
601 }
602
603 // Also need to take care of app op.
604 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
605 callingPackage) != AppOpsManager.MODE_ALLOWED) {
606 return null;
607 }
Christopher Tate06efb532012-08-24 15:29:27 -0700608
Christopher Tate61695ff2012-10-05 12:05:13 -0700609 final ContentValues values = new ContentValues();
610 values.put(Settings.NameValueTable.NAME, request);
611 values.put(Settings.NameValueTable.VALUE, newValue);
612 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
613 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
614 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
615 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
616 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
617 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
618 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
619 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
620 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
621 } else {
622 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700623 }
624
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800625 return null;
626 }
627
628 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
629 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700630 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
631 final SettingsCache cache, String key) {
632 if (cache == null) {
633 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
634 return null;
635 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800636 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800637 Bundle value = cache.get(key);
638 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700639 if (value != TOO_LARGE_TO_CACHE_MARKER) {
640 return value;
641 }
642 // else we fall through and read the value from disk
643 } else if (cache.fullyMatchesDisk()) {
644 // Fast path (very common). Don't even try touch disk
645 // if we know we've slurped it all in. Trying to
646 // touch the disk would mean waiting for yaffs2 to
647 // give us access, which could takes hundreds of
648 // milliseconds. And we're very likely being called
649 // from somebody's UI thread...
650 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800651 }
652 }
653
Christopher Tate06efb532012-08-24 15:29:27 -0700654 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800655 Cursor cursor = null;
656 try {
657 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
658 null, null, null, null);
659 if (cursor != null && cursor.getCount() == 1) {
660 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800661 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800662 }
663 } catch (SQLiteException e) {
664 Log.w(TAG, "settings lookup error", e);
665 return null;
666 } finally {
667 if (cursor != null) cursor.close();
668 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800669 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800670 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800671 }
672
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700673 @Override
674 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700675 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
676 }
677
Christopher Tateb7564452012-09-19 16:21:18 -0700678 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700679 String sort, int forUser) {
680 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700681 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700682 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700683 dbH = getOrEstablishDatabase(
684 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700685 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800687 // The favorites table was moved from this provider to a provider inside Home
688 // Home still need to query this table to upgrade from pre-cupcake builds
689 // However, a cupcake+ build with no data does not contain this table which will
690 // cause an exception in the SQL stack. The following line is a special case to
691 // 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 -0800692 if (TABLE_FAVORITES.equals(args.table)) {
693 return null;
694 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
695 args.table = TABLE_FAVORITES;
696 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
697 if (cursor != null) {
698 boolean exists = cursor.getCount() > 0;
699 cursor.close();
700 if (!exists) return null;
701 } else {
702 return null;
703 }
704 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800705
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700706 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
707 qb.setTables(args.table);
708
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700709 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700710 // the default Cursor interface does not support per-user observation
711 try {
712 AbstractCursor c = (AbstractCursor) ret;
713 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
714 } catch (ClassCastException e) {
715 // details of the concrete Cursor implementation have changed and this code has
716 // not been updated to match -- complain and fail hard.
717 Log.wtf(TAG, "Incompatible cursor derivation!");
718 throw e;
719 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700720 return ret;
721 }
722
723 @Override
724 public String getType(Uri url) {
725 // If SqlArguments supplies a where clause, then it must be an item
726 // (because we aren't supplying our own where clause).
727 SqlArguments args = new SqlArguments(url, null, null);
728 if (TextUtils.isEmpty(args.where)) {
729 return "vnd.android.cursor.dir/" + args.table;
730 } else {
731 return "vnd.android.cursor.item/" + args.table;
732 }
733 }
734
735 @Override
736 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700737 final int callingUser = UserHandle.getCallingUserId();
738 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700739 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 if (TABLE_FAVORITES.equals(args.table)) {
741 return 0;
742 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700743 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700744 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700745
Christopher Tate06efb532012-08-24 15:29:27 -0700746 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
747 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700748 DatabaseHelper dbH = getOrEstablishDatabase(
749 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700750 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700751 db.beginTransaction();
752 try {
753 int numValues = values.length;
754 for (int i = 0; i < numValues; i++) {
755 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800756 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700757 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
758 }
759 db.setTransactionSuccessful();
760 } finally {
761 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700762 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700763 }
764
Christopher Tate06efb532012-08-24 15:29:27 -0700765 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700766 return values.length;
767 }
768
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700769 /*
770 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
771 * This setting contains a list of the currently enabled location providers.
772 * But helper functions in android.providers.Settings can enable or disable
773 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800774 *
775 * @returns whether the database needs to be updated or not, also modifying
776 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700777 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500778 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700779 String value = initialValues.getAsString(Settings.Secure.VALUE);
780 String newProviders = null;
781 if (value != null && value.length() > 1) {
782 char prefix = value.charAt(0);
783 if (prefix == '+' || prefix == '-') {
784 // skip prefix
785 value = value.substring(1);
786
787 // read list of enabled providers into "providers"
788 String providers = "";
789 String[] columns = {Settings.Secure.VALUE};
790 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -0500791 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700792 if (cursor != null && cursor.getCount() == 1) {
793 try {
794 cursor.moveToFirst();
795 providers = cursor.getString(0);
796 } finally {
797 cursor.close();
798 }
799 }
800
801 int index = providers.indexOf(value);
802 int end = index + value.length();
803 // check for commas to avoid matching on partial string
804 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
805 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
806
807 if (prefix == '+' && index < 0) {
808 // append the provider to the list if not present
809 if (providers.length() == 0) {
810 newProviders = value;
811 } else {
812 newProviders = providers + ',' + value;
813 }
814 } else if (prefix == '-' && index >= 0) {
815 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400816 // remove leading or trailing comma
817 if (index > 0) {
818 index--;
819 } else if (end < providers.length()) {
820 end++;
821 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700822
823 newProviders = providers.substring(0, index);
824 if (end < providers.length()) {
825 newProviders += providers.substring(end);
826 }
827 } else {
828 // nothing changed, so no need to update the database
829 return false;
830 }
831
832 if (newProviders != null) {
833 initialValues.put(Settings.Secure.VALUE, newProviders);
834 }
835 }
836 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800837
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700838 return true;
839 }
840
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700841 @Override
842 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700843 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
844 }
845
846 // Settings.put*ForUser() always winds up here, so this is where we apply
847 // policy around permission to write settings for other users.
848 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
849 final int callingUser = UserHandle.getCallingUserId();
850 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700851 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700852 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
853 "Not permitted to access settings for other users");
854 }
855
856 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
857 + " by " + callingUser);
858
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700859 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 if (TABLE_FAVORITES.equals(args.table)) {
861 return null;
862 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700863
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700864 // Special case LOCATION_PROVIDERS_ALLOWED.
865 // Support enabling/disabling a single provider (using "+" or "-" prefix)
866 String name = initialValues.getAsString(Settings.Secure.NAME);
867 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -0500868 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700869 }
870
Christopher Tatec221d2b2012-10-03 18:33:52 -0700871 // If this is an insert() of a key that has been migrated to the global store,
872 // redirect the operation to that store
873 if (name != null) {
874 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
875 if (!TABLE_GLOBAL.equals(args.table)) {
876 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
877 }
878 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
879 }
880 }
881
Christopher Tate34637e52012-10-04 15:00:00 -0700882 // Check write permissions only after determining which table the insert will touch
883 checkWritePermissions(args);
884
Christopher Tate06efb532012-08-24 15:29:27 -0700885 // The global table is stored under the owner, always
886 if (TABLE_GLOBAL.equals(args.table)) {
887 desiredUserHandle = UserHandle.USER_OWNER;
888 }
889
890 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800891 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
892 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
893 return Uri.withAppendedPath(url, name);
894 }
895
Christopher Tate06efb532012-08-24 15:29:27 -0700896 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
897 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700898 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700899 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700900 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700901 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700902 if (rowId <= 0) return null;
903
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800904 SettingsCache.populate(cache, initialValues); // before we notify
905
Christopher Tate78d2a662012-09-13 16:19:44 -0700906 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
907 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700908 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700909 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700910 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700911 return url;
912 }
913
914 @Override
915 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700916 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700917 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700918 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (TABLE_FAVORITES.equals(args.table)) {
920 return 0;
921 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
922 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700923 } else if (TABLE_GLOBAL.equals(args.table)) {
924 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700926 checkWritePermissions(args);
927
Christopher Tate06efb532012-08-24 15:29:27 -0700928 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
929 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700930 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700931 SQLiteDatabase db = dbH.getWritableDatabase();
932 int count = db.delete(args.table, args.where, args.args);
933 mutationCount.decrementAndGet();
934 if (count > 0) {
935 invalidateCache(callingUser, args.table); // before we notify
936 sendNotify(url, callingUser);
937 }
938 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700939 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
940 return count;
941 }
942
943 @Override
944 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700945 // NOTE: update() is never called by the front-end Settings API, and updates that
946 // wind up affecting rows in Secure that are globally shared will not have the
947 // intended effect (the update will be invisible to the rest of the system).
948 // This should have no practical effect, since writes to the Secure db can only
949 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700950 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700951 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700952 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 if (TABLE_FAVORITES.equals(args.table)) {
954 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700955 } else if (TABLE_GLOBAL.equals(args.table)) {
956 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700958 checkWritePermissions(args);
959
Christopher Tate06efb532012-08-24 15:29:27 -0700960 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
961 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700962 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700963 SQLiteDatabase db = dbH.getWritableDatabase();
964 int count = db.update(args.table, initialValues, args.where, args.args);
965 mutationCount.decrementAndGet();
966 if (count > 0) {
967 invalidateCache(callingUser, args.table); // before we notify
968 sendNotify(url, callingUser);
969 }
970 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700971 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
972 return count;
973 }
974
975 @Override
976 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
977
978 /*
979 * When a client attempts to openFile the default ringtone or
980 * notification setting Uri, we will proxy the call to the current
981 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700982 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700983 int ringtoneType = RingtoneManager.getDefaultType(uri);
984 // Above call returns -1 if the Uri doesn't match a default type
985 if (ringtoneType != -1) {
986 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700987
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700988 // Get the current value for the default sound
989 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700990
Marco Nelissen69f593c2009-07-28 09:55:04 -0700991 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700992 // Only proxy the openFile call to drm or media providers
993 String authority = soundUri.getAuthority();
994 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
995 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
996
997 if (isDrmAuthority) {
998 try {
999 // Check DRM access permission here, since once we
1000 // do the below call the DRM will be checking our
1001 // permission, not our caller's permission
1002 DrmStore.enforceAccessDrmPermission(context);
1003 } catch (SecurityException e) {
1004 throw new FileNotFoundException(e.getMessage());
1005 }
1006 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001007
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001008 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1009 }
1010 }
1011 }
1012
1013 return super.openFile(uri, mode);
1014 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001015
1016 @Override
1017 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1018
1019 /*
1020 * When a client attempts to openFile the default ringtone or
1021 * notification setting Uri, we will proxy the call to the current
1022 * default ringtone's Uri (if it is in the DRM or media provider).
1023 */
1024 int ringtoneType = RingtoneManager.getDefaultType(uri);
1025 // Above call returns -1 if the Uri doesn't match a default type
1026 if (ringtoneType != -1) {
1027 Context context = getContext();
1028
1029 // Get the current value for the default sound
1030 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1031
1032 if (soundUri != null) {
1033 // Only proxy the openFile call to drm or media providers
1034 String authority = soundUri.getAuthority();
1035 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1036 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1037
1038 if (isDrmAuthority) {
1039 try {
1040 // Check DRM access permission here, since once we
1041 // do the below call the DRM will be checking our
1042 // permission, not our caller's permission
1043 DrmStore.enforceAccessDrmPermission(context);
1044 } catch (SecurityException e) {
1045 throw new FileNotFoundException(e.getMessage());
1046 }
1047 }
1048
1049 ParcelFileDescriptor pfd = null;
1050 try {
1051 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1052 return new AssetFileDescriptor(pfd, 0, -1);
1053 } catch (FileNotFoundException ex) {
1054 // fall through and open the fallback ringtone below
1055 }
1056 }
1057
1058 try {
1059 return super.openAssetFile(soundUri, mode);
1060 } catch (FileNotFoundException ex) {
1061 // Since a non-null Uri was specified, but couldn't be opened,
1062 // fall back to the built-in ringtone.
1063 return context.getResources().openRawResourceFd(
1064 com.android.internal.R.raw.fallbackring);
1065 }
1066 }
1067 // no need to fall through and have openFile() try again, since we
1068 // already know that will fail.
1069 throw new FileNotFoundException(); // or return null ?
1070 }
1071
1072 // Note that this will end up calling openFile() above.
1073 return super.openAssetFile(uri, mode);
1074 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001075
1076 /**
1077 * In-memory LRU Cache of system and secure settings, along with
1078 * associated helper functions to keep cache coherent with the
1079 * database.
1080 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001081 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001082
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001083 private final String mCacheName;
1084 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1085
1086 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001087 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001088 mCacheName = name;
1089 }
1090
1091 /**
1092 * Is the whole database table slurped into this cache?
1093 */
1094 public boolean fullyMatchesDisk() {
1095 synchronized (this) {
1096 return mCacheFullyMatchesDisk;
1097 }
1098 }
1099
1100 public void setFullyMatchesDisk(boolean value) {
1101 synchronized (this) {
1102 mCacheFullyMatchesDisk = value;
1103 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001104 }
1105
1106 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001107 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1108 if (evicted) {
1109 mCacheFullyMatchesDisk = false;
1110 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001111 }
1112
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001113 /**
1114 * Atomic cache population, conditional on size of value and if
1115 * we lost a race.
1116 *
1117 * @returns a Bundle to send back to the client from call(), even
1118 * if we lost the race.
1119 */
1120 public Bundle putIfAbsent(String key, String value) {
1121 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1122 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1123 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001124 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001125 put(key, bundle);
1126 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001127 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001128 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001129 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001130 }
1131
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001132 /**
1133 * Populates a key in a given (possibly-null) cache.
1134 */
1135 public static void populate(SettingsCache cache, ContentValues contentValues) {
1136 if (cache == null) {
1137 return;
1138 }
1139 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1140 if (name == null) {
1141 Log.w(TAG, "null name populating settings cache.");
1142 return;
1143 }
1144 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001145 cache.populate(name, value);
1146 }
1147
1148 public void populate(String name, String value) {
1149 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001150 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001151 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001152 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001153 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001154 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001155 }
1156 }
1157
1158 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001159 * For suppressing duplicate/redundant settings inserts early,
1160 * checking our cache first (but without faulting it in),
1161 * before going to sqlite with the mutation.
1162 */
1163 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1164 if (cache == null) return false;
1165 synchronized (cache) {
1166 Bundle bundle = cache.get(name);
1167 if (bundle == null) return false;
1168 String oldValue = bundle.getPairValue();
1169 if (oldValue == null && value == null) return true;
1170 if ((oldValue == null) != (value == null)) return false;
1171 return oldValue.equals(value);
1172 }
1173 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001174 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001175}