blob: f894068a9b3cdb03ac4ab2bd1c476b084275330f [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.MediaStore;
52import android.provider.Settings;
53import android.text.TextUtils;
54import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080055import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070056import android.util.Slog;
57import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070059public class SettingsProvider extends ContentProvider {
60 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070061 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062
Christopher Tate06efb532012-08-24 15:29:27 -070063 private static final String TABLE_SYSTEM = "system";
64 private static final String TABLE_SECURE = "secure";
65 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 private static final String TABLE_FAVORITES = "favorites";
67 private static final String TABLE_OLD_FAVORITES = "old_favorites";
68
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080069 private static final String[] COLUMN_VALUE = new String[] { "value" };
70
Christopher Tate06efb532012-08-24 15:29:27 -070071 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080072 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070073 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070074 private static final SparseArray<SettingsCache> sSystemCaches
75 = new SparseArray<SettingsCache>();
76 private static final SparseArray<SettingsCache> sSecureCaches
77 = new SparseArray<SettingsCache>();
78 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070079
80 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070081 // database mutations are currently being handled for this user.
82 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070083 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070084 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
85 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080086
Christopher Tate78d2a662012-09-13 16:19:44 -070087 // Each defined user has their own settings
88 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
89
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080090 // Over this size we don't reject loading or saving settings but
91 // we do consider them broken/malicious and don't keep them in
92 // memory at least:
93 private static final int MAX_CACHE_ENTRY_SIZE = 500;
94
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080095 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
96
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070097 // Used as a sentinel value in an instance equality test when we
98 // want to cache the existence of a key, but not store its value.
99 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
100
Christopher Tate06efb532012-08-24 15:29:27 -0700101 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700102 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700103
104 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700105 * Settings which need to be treated as global/shared in multi-user environments.
106 */
107 static final HashSet<String> sSecureGlobalKeys;
108 static final HashSet<String> sSystemGlobalKeys;
109 static {
110 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
111 // table, shared across all users
112 // These must match Settings.Secure.MOVED_TO_GLOBAL
113 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700114 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700115
116 // Keys from the 'system' table now moved to 'global'
117 // These must match Settings.System.MOVED_TO_GLOBAL
118 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700119 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700120 }
121
122 private boolean settingMovedToGlobal(final String name) {
123 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
124 }
125
126 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700127 * Decode a content URL into the table, projection, and arguments
128 * used to access the corresponding database rows.
129 */
130 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700132 public final String where;
133 public final String[] args;
134
135 /** Operate on existing rows. */
136 SqlArguments(Uri url, String where, String[] args) {
137 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700138 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700139 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700140 if (!DatabaseHelper.isValidTable(this.table)) {
141 throw new IllegalArgumentException("Bad root path: " + this.table);
142 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143 this.where = where;
144 this.args = args;
145 } else if (url.getPathSegments().size() != 2) {
146 throw new IllegalArgumentException("Invalid URI: " + url);
147 } else if (!TextUtils.isEmpty(where)) {
148 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
149 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700150 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700151 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700152 if (!DatabaseHelper.isValidTable(this.table)) {
153 throw new IllegalArgumentException("Bad root path: " + this.table);
154 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700155 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
156 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700157 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700158 final String name = url.getPathSegments().get(1);
159 this.args = new String[] { name };
160 // Rewrite the table for known-migrated names
161 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
162 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
163 this.table = TABLE_GLOBAL;
164 }
165 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700166 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700167 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168 this.where = "_id=" + ContentUris.parseId(url);
169 this.args = null;
170 }
171 }
172 }
173
174 /** Insert new rows (no where clause allowed). */
175 SqlArguments(Uri url) {
176 if (url.getPathSegments().size() == 1) {
177 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700178 if (!DatabaseHelper.isValidTable(this.table)) {
179 throw new IllegalArgumentException("Bad root path: " + this.table);
180 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700181 this.where = null;
182 this.args = null;
183 } else {
184 throw new IllegalArgumentException("Invalid URI: " + url);
185 }
186 }
187 }
188
189 /**
190 * Get the content URI of a row added to a table.
191 * @param tableUri of the entire table
192 * @param values found in the row
193 * @param rowId of the row
194 * @return the content URI for this particular row
195 */
196 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
197 if (tableUri.getPathSegments().size() != 1) {
198 throw new IllegalArgumentException("Invalid URI: " + tableUri);
199 }
200 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700201 if (TABLE_SYSTEM.equals(table) ||
202 TABLE_SECURE.equals(table) ||
203 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700204 String name = values.getAsString(Settings.NameValueTable.NAME);
205 return Uri.withAppendedPath(tableUri, name);
206 } else {
207 return ContentUris.withAppendedId(tableUri, rowId);
208 }
209 }
210
211 /**
212 * Send a notification when a particular content URI changes.
213 * Modify the system property used to communicate the version of
214 * this table, for tables which have such a property. (The Settings
215 * contract class uses these to provide client-side caches.)
216 * @param uri to send notifications for
217 */
Christopher Tate06efb532012-08-24 15:29:27 -0700218 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700219 // Update the system property *first*, so if someone is listening for
220 // a notification and then using the contract class to get their data,
221 // the system property will be updated and they'll get the new data.
222
Amith Yamasanid1582142009-07-08 20:04:55 -0700223 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700224 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700225 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700226 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700227 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700228 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700229 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700230 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700231 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700232 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700233 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700234 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700235 }
236
237 if (property != null) {
238 long version = SystemProperties.getLong(property, 0) + 1;
239 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
240 SystemProperties.set(property, Long.toString(version));
241 }
242
-b master501eec92009-07-06 13:53:11 -0700243 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700244 if (backedUpDataChanged) {
245 mBackupManager.dataChanged();
246 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700247 // Now send the notification through the content framework.
248
249 String notify = uri.getQueryParameter("notify");
250 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700251 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700252 final long oldId = Binder.clearCallingIdentity();
253 try {
254 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
255 } finally {
256 Binder.restoreCallingIdentity(oldId);
257 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700258 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700259 } else {
260 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
261 }
262 }
263
264 /**
265 * Make sure the caller has permission to write this data.
266 * @param args supplied by the caller
267 * @throws SecurityException if the caller is forbidden to write.
268 */
269 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700270 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800271 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800272 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
273 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700274 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800275 String.format("Permission denial: writing to secure settings requires %1$s",
276 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700277 }
278 }
279
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700280 // FileObserver for external modifications to the database file.
281 // Note that this is for platform developers only with
282 // userdebug/eng builds who should be able to tinker with the
283 // sqlite database out from under the SettingsProvider, which is
284 // normally the exclusive owner of the database. But we keep this
285 // enabled all the time to minimize development-vs-user
286 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700287 private static SparseArray<SettingsFileObserver> sObserverInstances
288 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700289 private class SettingsFileObserver extends FileObserver {
290 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700291 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700292 private final String mPath;
293
Christopher Tate06efb532012-08-24 15:29:27 -0700294 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700295 super(path, FileObserver.CLOSE_WRITE |
296 FileObserver.CREATE | FileObserver.DELETE |
297 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700298 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700299 mPath = path;
300 }
301
302 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700303 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700304 if (modsInFlight > 0) {
305 // our own modification.
306 return;
307 }
Christopher Tate06efb532012-08-24 15:29:27 -0700308 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
309 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700310 if (!mIsDirty.compareAndSet(false, true)) {
311 // already handled. (we get a few update events
312 // during an sqlite write)
313 return;
314 }
Christopher Tate06efb532012-08-24 15:29:27 -0700315 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
316 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700317 mIsDirty.set(false);
318 }
319 }
320
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 @Override
322 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700323 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700324 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800325
Dianne Hackborn961321f2013-02-05 17:22:41 -0800326 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700327 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700328
Christopher Tate78d2a662012-09-13 16:19:44 -0700329 IntentFilter userFilter = new IntentFilter();
330 userFilter.addAction(Intent.ACTION_USER_REMOVED);
331 getContext().registerReceiver(new BroadcastReceiver() {
332 @Override
333 public void onReceive(Context context, Intent intent) {
334 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
335 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
336 UserHandle.USER_OWNER);
337 if (userHandle != UserHandle.USER_OWNER) {
338 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700339 }
340 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700341 }
342 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700343 return true;
344 }
345
Christopher Tate06efb532012-08-24 15:29:27 -0700346 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700347 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700348 // the db file itself will be deleted automatically, but we need to tear down
349 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700350 FileObserver observer = sObserverInstances.get(userHandle);
351 if (observer != null) {
352 observer.stopWatching();
353 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700354 }
Christopher Tate06efb532012-08-24 15:29:27 -0700355
356 mOpenHelpers.delete(userHandle);
357 sSystemCaches.delete(userHandle);
358 sSecureCaches.delete(userHandle);
359 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700360 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700361 }
362
Christopher Tate78d2a662012-09-13 16:19:44 -0700363 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700364 if (LOCAL_LOGV) {
365 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
366 }
367
Christopher Tate78d2a662012-09-13 16:19:44 -0700368 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700369
Christopher Tate78d2a662012-09-13 16:19:44 -0700370 synchronized (this) {
371 dbhelper = mOpenHelpers.get(userHandle);
372 if (dbhelper == null) {
373 dbhelper = new DatabaseHelper(getContext(), userHandle);
374 mOpenHelpers.append(userHandle, dbhelper);
375
376 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
377 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
378 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
379 }
380 }
381
382 // Initialization of the db *outside* the locks. It's possible that racing
383 // threads might wind up here, the second having read the cache entries
384 // written by the first, but that's benign: the SQLite helper implementation
385 // manages concurrency itself, and it's important that we not run the db
386 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700387 SQLiteDatabase db = dbhelper.getWritableDatabase();
388
Christopher Tate78d2a662012-09-13 16:19:44 -0700389 // Watch for external modifications to the database files,
390 // keeping our caches in sync. We synchronize the observer set
391 // separately, and of course it has to run after the db file
392 // itself was set up by the DatabaseHelper.
393 synchronized (sObserverInstances) {
394 if (sObserverInstances.get(userHandle) == null) {
395 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
396 sObserverInstances.append(userHandle, observer);
397 observer.startWatching();
398 }
399 }
Christopher Tate06efb532012-08-24 15:29:27 -0700400
Christopher Tate4dc7a682012-09-11 12:15:49 -0700401 ensureAndroidIdIsSet(userHandle);
402
Christopher Tate06efb532012-08-24 15:29:27 -0700403 startAsyncCachePopulation(userHandle);
404 }
405
406 class CachePrefetchThread extends Thread {
407 private int mUserHandle;
408
409 CachePrefetchThread(int userHandle) {
410 super("populate-settings-caches");
411 mUserHandle = userHandle;
412 }
413
414 @Override
415 public void run() {
416 fullyPopulateCaches(mUserHandle);
417 }
418 }
419
420 private void startAsyncCachePopulation(int userHandle) {
421 new CachePrefetchThread(userHandle).start();
422 }
423
424 private void fullyPopulateCaches(final int userHandle) {
425 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
426 // Only populate the globals cache once, for the owning user
427 if (userHandle == UserHandle.USER_OWNER) {
428 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
429 }
430 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
431 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700432 }
433
434 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700435 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
436 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700437 Cursor c = db.query(
438 table,
439 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
440 null, null, null, null, null,
441 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
442 try {
443 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800444 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700445 cache.setFullyMatchesDisk(true); // optimistic
446 int rows = 0;
447 while (c.moveToNext()) {
448 rows++;
449 String name = c.getString(0);
450 String value = c.getString(1);
451 cache.populate(name, value);
452 }
453 if (rows > MAX_CACHE_ENTRIES) {
454 // Somewhat redundant, as removeEldestEntry() will
455 // have already done this, but to be explicit:
456 cache.setFullyMatchesDisk(false);
457 Log.d(TAG, "row count exceeds max cache entries for table " + table);
458 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800459 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
460 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700461 }
462 } finally {
463 c.close();
464 }
465 }
466
Christopher Tate4dc7a682012-09-11 12:15:49 -0700467 private boolean ensureAndroidIdIsSet(int userHandle) {
468 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800469 new String[] { Settings.NameValueTable.VALUE },
470 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700471 new String[] { Settings.Secure.ANDROID_ID }, null,
472 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800473 try {
474 final String value = c.moveToNext() ? c.getString(0) : null;
475 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700476 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800477 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800478 final ContentValues values = new ContentValues();
479 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
480 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700481 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800482 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700483 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800484 return false;
485 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700486 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
487 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800488 }
489 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800490 } finally {
491 c.close();
492 }
493 }
494
Christopher Tate06efb532012-08-24 15:29:27 -0700495 // Lazy-initialize the settings caches for non-primary users
496 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700497 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
498 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700499 }
500
501 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700502 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700503 long oldId = Binder.clearCallingIdentity();
504 try {
505 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
506 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700507 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700508 dbHelper = mOpenHelpers.get(callingUser);
509 }
510 return dbHelper;
511 } finally {
512 Binder.restoreCallingIdentity(oldId);
513 }
514 }
515
516 public SettingsCache cacheForTable(final int callingUser, String tableName) {
517 if (TABLE_SYSTEM.equals(tableName)) {
518 return getOrConstructCache(callingUser, sSystemCaches);
519 }
520 if (TABLE_SECURE.equals(tableName)) {
521 return getOrConstructCache(callingUser, sSecureCaches);
522 }
523 if (TABLE_GLOBAL.equals(tableName)) {
524 return sGlobalCache;
525 }
526 return null;
527 }
528
529 /**
530 * Used for wiping a whole cache on deletes when we're not
531 * sure what exactly was deleted or changed.
532 */
533 public void invalidateCache(final int callingUser, String tableName) {
534 SettingsCache cache = cacheForTable(callingUser, tableName);
535 if (cache == null) {
536 return;
537 }
538 synchronized (cache) {
539 cache.evictAll();
540 cache.mCacheFullyMatchesDisk = false;
541 }
542 }
543
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800544 /**
545 * Fast path that avoids the use of chatty remoted Cursors.
546 */
547 @Override
Dianne Hackborn961321f2013-02-05 17:22:41 -0800548 public Bundle callFromPackage(String callingPackage, String method, String request,
549 Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700550 int callingUser = UserHandle.getCallingUserId();
551 if (args != null) {
552 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
553 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700554 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
555 Binder.getCallingUid(), reqUser, false, true,
556 "get/set setting for user", null);
557 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700558 }
559 }
560
Christopher Tate61695ff2012-10-05 12:05:13 -0700561 // Note: we assume that get/put operations for moved-to-global names have already
562 // been directed to the new location on the caller side (otherwise we'd fix them
563 // up here).
564 DatabaseHelper dbHelper;
565 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700566
Christopher Tate61695ff2012-10-05 12:05:13 -0700567 // Get methods
568 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
569 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
570 dbHelper = getOrEstablishDatabase(callingUser);
571 cache = sSystemCaches.get(callingUser);
572 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
573 }
574 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
575 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
576 dbHelper = getOrEstablishDatabase(callingUser);
577 cache = sSecureCaches.get(callingUser);
578 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
579 }
580 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
581 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
582 // fast path: owner db & cache are immutable after onCreate() so we need not
583 // guard on the attempt to look them up
584 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
585 sGlobalCache, request);
586 }
Christopher Tate06efb532012-08-24 15:29:27 -0700587
Christopher Tate61695ff2012-10-05 12:05:13 -0700588 // Put methods - new value is in the args bundle under the key named by
589 // the Settings.NameValueTable.VALUE static.
590 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800591 ? null : args.getString(Settings.NameValueTable.VALUE);
592
593 // Framework can't do automatic permission checking for calls, so we need
594 // to do it here.
595 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
596 != PackageManager.PERMISSION_GRANTED) {
597 throw new SecurityException(
598 String.format("Permission denial: writing to settings requires %1$s",
599 android.Manifest.permission.WRITE_SETTINGS));
600 }
601
602 // Also need to take care of app op.
603 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
604 callingPackage) != AppOpsManager.MODE_ALLOWED) {
605 return null;
606 }
Christopher Tate06efb532012-08-24 15:29:27 -0700607
Christopher Tate61695ff2012-10-05 12:05:13 -0700608 final ContentValues values = new ContentValues();
609 values.put(Settings.NameValueTable.NAME, request);
610 values.put(Settings.NameValueTable.VALUE, newValue);
611 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
612 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
613 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
614 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
615 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
616 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
617 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
618 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
619 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
620 } else {
621 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700622 }
623
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800624 return null;
625 }
626
627 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
628 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700629 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
630 final SettingsCache cache, String key) {
631 if (cache == null) {
632 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
633 return null;
634 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800635 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800636 Bundle value = cache.get(key);
637 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700638 if (value != TOO_LARGE_TO_CACHE_MARKER) {
639 return value;
640 }
641 // else we fall through and read the value from disk
642 } else if (cache.fullyMatchesDisk()) {
643 // Fast path (very common). Don't even try touch disk
644 // if we know we've slurped it all in. Trying to
645 // touch the disk would mean waiting for yaffs2 to
646 // give us access, which could takes hundreds of
647 // milliseconds. And we're very likely being called
648 // from somebody's UI thread...
649 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800650 }
651 }
652
Christopher Tate06efb532012-08-24 15:29:27 -0700653 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800654 Cursor cursor = null;
655 try {
656 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
657 null, null, null, null);
658 if (cursor != null && cursor.getCount() == 1) {
659 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800660 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800661 }
662 } catch (SQLiteException e) {
663 Log.w(TAG, "settings lookup error", e);
664 return null;
665 } finally {
666 if (cursor != null) cursor.close();
667 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800668 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800669 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800670 }
671
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700672 @Override
673 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700674 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
675 }
676
Christopher Tateb7564452012-09-19 16:21:18 -0700677 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700678 String sort, int forUser) {
679 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700680 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700681 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700682 dbH = getOrEstablishDatabase(
683 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700684 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800686 // The favorites table was moved from this provider to a provider inside Home
687 // Home still need to query this table to upgrade from pre-cupcake builds
688 // However, a cupcake+ build with no data does not contain this table which will
689 // cause an exception in the SQL stack. The following line is a special case to
690 // 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 -0800691 if (TABLE_FAVORITES.equals(args.table)) {
692 return null;
693 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
694 args.table = TABLE_FAVORITES;
695 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
696 if (cursor != null) {
697 boolean exists = cursor.getCount() > 0;
698 cursor.close();
699 if (!exists) return null;
700 } else {
701 return null;
702 }
703 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800704
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700705 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
706 qb.setTables(args.table);
707
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700708 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700709 // the default Cursor interface does not support per-user observation
710 try {
711 AbstractCursor c = (AbstractCursor) ret;
712 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
713 } catch (ClassCastException e) {
714 // details of the concrete Cursor implementation have changed and this code has
715 // not been updated to match -- complain and fail hard.
716 Log.wtf(TAG, "Incompatible cursor derivation!");
717 throw e;
718 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700719 return ret;
720 }
721
722 @Override
723 public String getType(Uri url) {
724 // If SqlArguments supplies a where clause, then it must be an item
725 // (because we aren't supplying our own where clause).
726 SqlArguments args = new SqlArguments(url, null, null);
727 if (TextUtils.isEmpty(args.where)) {
728 return "vnd.android.cursor.dir/" + args.table;
729 } else {
730 return "vnd.android.cursor.item/" + args.table;
731 }
732 }
733
734 @Override
735 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700736 final int callingUser = UserHandle.getCallingUserId();
737 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700738 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 if (TABLE_FAVORITES.equals(args.table)) {
740 return 0;
741 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700742 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700743 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700744
Christopher Tate06efb532012-08-24 15:29:27 -0700745 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
746 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700747 DatabaseHelper dbH = getOrEstablishDatabase(
748 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700749 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700750 db.beginTransaction();
751 try {
752 int numValues = values.length;
753 for (int i = 0; i < numValues; i++) {
754 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800755 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700756 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
757 }
758 db.setTransactionSuccessful();
759 } finally {
760 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700761 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700762 }
763
Christopher Tate06efb532012-08-24 15:29:27 -0700764 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700765 return values.length;
766 }
767
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700768 /*
769 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
770 * This setting contains a list of the currently enabled location providers.
771 * But helper functions in android.providers.Settings can enable or disable
772 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800773 *
774 * @returns whether the database needs to be updated or not, also modifying
775 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700776 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500777 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700778 String value = initialValues.getAsString(Settings.Secure.VALUE);
779 String newProviders = null;
780 if (value != null && value.length() > 1) {
781 char prefix = value.charAt(0);
782 if (prefix == '+' || prefix == '-') {
783 // skip prefix
784 value = value.substring(1);
785
786 // read list of enabled providers into "providers"
787 String providers = "";
788 String[] columns = {Settings.Secure.VALUE};
789 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -0500790 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700791 if (cursor != null && cursor.getCount() == 1) {
792 try {
793 cursor.moveToFirst();
794 providers = cursor.getString(0);
795 } finally {
796 cursor.close();
797 }
798 }
799
800 int index = providers.indexOf(value);
801 int end = index + value.length();
802 // check for commas to avoid matching on partial string
803 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
804 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
805
806 if (prefix == '+' && index < 0) {
807 // append the provider to the list if not present
808 if (providers.length() == 0) {
809 newProviders = value;
810 } else {
811 newProviders = providers + ',' + value;
812 }
813 } else if (prefix == '-' && index >= 0) {
814 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400815 // remove leading or trailing comma
816 if (index > 0) {
817 index--;
818 } else if (end < providers.length()) {
819 end++;
820 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700821
822 newProviders = providers.substring(0, index);
823 if (end < providers.length()) {
824 newProviders += providers.substring(end);
825 }
826 } else {
827 // nothing changed, so no need to update the database
828 return false;
829 }
830
831 if (newProviders != null) {
832 initialValues.put(Settings.Secure.VALUE, newProviders);
833 }
834 }
835 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800836
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700837 return true;
838 }
839
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700840 @Override
841 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700842 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
843 }
844
845 // Settings.put*ForUser() always winds up here, so this is where we apply
846 // policy around permission to write settings for other users.
847 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
848 final int callingUser = UserHandle.getCallingUserId();
849 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700850 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700851 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
852 "Not permitted to access settings for other users");
853 }
854
855 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
856 + " by " + callingUser);
857
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700858 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (TABLE_FAVORITES.equals(args.table)) {
860 return null;
861 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700862
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700863 // Special case LOCATION_PROVIDERS_ALLOWED.
864 // Support enabling/disabling a single provider (using "+" or "-" prefix)
865 String name = initialValues.getAsString(Settings.Secure.NAME);
866 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -0500867 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700868 }
869
Christopher Tatec221d2b2012-10-03 18:33:52 -0700870 // If this is an insert() of a key that has been migrated to the global store,
871 // redirect the operation to that store
872 if (name != null) {
873 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
874 if (!TABLE_GLOBAL.equals(args.table)) {
875 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
876 }
877 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
878 }
879 }
880
Christopher Tate34637e52012-10-04 15:00:00 -0700881 // Check write permissions only after determining which table the insert will touch
882 checkWritePermissions(args);
883
Christopher Tate06efb532012-08-24 15:29:27 -0700884 // The global table is stored under the owner, always
885 if (TABLE_GLOBAL.equals(args.table)) {
886 desiredUserHandle = UserHandle.USER_OWNER;
887 }
888
889 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800890 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
891 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
892 return Uri.withAppendedPath(url, name);
893 }
894
Christopher Tate06efb532012-08-24 15:29:27 -0700895 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
896 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700897 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700898 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700899 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700900 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700901 if (rowId <= 0) return null;
902
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800903 SettingsCache.populate(cache, initialValues); // before we notify
904
Christopher Tate78d2a662012-09-13 16:19:44 -0700905 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
906 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700907 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700908 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700909 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700910 return url;
911 }
912
913 @Override
914 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700915 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700916 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700917 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 if (TABLE_FAVORITES.equals(args.table)) {
919 return 0;
920 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
921 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700922 } else if (TABLE_GLOBAL.equals(args.table)) {
923 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700925 checkWritePermissions(args);
926
Christopher Tate06efb532012-08-24 15:29:27 -0700927 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
928 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700929 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700930 SQLiteDatabase db = dbH.getWritableDatabase();
931 int count = db.delete(args.table, args.where, args.args);
932 mutationCount.decrementAndGet();
933 if (count > 0) {
934 invalidateCache(callingUser, args.table); // before we notify
935 sendNotify(url, callingUser);
936 }
937 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700938 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
939 return count;
940 }
941
942 @Override
943 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700944 // NOTE: update() is never called by the front-end Settings API, and updates that
945 // wind up affecting rows in Secure that are globally shared will not have the
946 // intended effect (the update will be invisible to the rest of the system).
947 // This should have no practical effect, since writes to the Secure db can only
948 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700949 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700950 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700951 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 if (TABLE_FAVORITES.equals(args.table)) {
953 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700954 } else if (TABLE_GLOBAL.equals(args.table)) {
955 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700957 checkWritePermissions(args);
958
Christopher Tate06efb532012-08-24 15:29:27 -0700959 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
960 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700961 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700962 SQLiteDatabase db = dbH.getWritableDatabase();
963 int count = db.update(args.table, initialValues, args.where, args.args);
964 mutationCount.decrementAndGet();
965 if (count > 0) {
966 invalidateCache(callingUser, args.table); // before we notify
967 sendNotify(url, callingUser);
968 }
969 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700970 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
971 return count;
972 }
973
974 @Override
975 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
976
977 /*
978 * When a client attempts to openFile the default ringtone or
979 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -0700980 * default ringtone's Uri (if it is in the media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700981 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700982 int ringtoneType = RingtoneManager.getDefaultType(uri);
983 // Above call returns -1 if the Uri doesn't match a default type
984 if (ringtoneType != -1) {
985 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700986
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700987 // Get the current value for the default sound
988 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700989
Marco Nelissen69f593c2009-07-28 09:55:04 -0700990 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -0700991 // Proxy the openFile call to media provider
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700992 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -0700993 if (authority.equals(MediaStore.AUTHORITY)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700994 return context.getContentResolver().openFileDescriptor(soundUri, mode);
995 }
996 }
997 }
998
999 return super.openFile(uri, mode);
1000 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001001
1002 @Override
1003 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1004
1005 /*
1006 * When a client attempts to openFile the default ringtone or
1007 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001008 * default ringtone's Uri (if it is in the media provider).
Marco Nelissen69f593c2009-07-28 09:55:04 -07001009 */
1010 int ringtoneType = RingtoneManager.getDefaultType(uri);
1011 // Above call returns -1 if the Uri doesn't match a default type
1012 if (ringtoneType != -1) {
1013 Context context = getContext();
1014
1015 // Get the current value for the default sound
1016 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1017
1018 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001019 // Proxy the openFile call to media provider
Marco Nelissen69f593c2009-07-28 09:55:04 -07001020 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001021 if (authority.equals(MediaStore.AUTHORITY)) {
Marco Nelissen69f593c2009-07-28 09:55:04 -07001022 ParcelFileDescriptor pfd = null;
1023 try {
1024 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1025 return new AssetFileDescriptor(pfd, 0, -1);
1026 } catch (FileNotFoundException ex) {
1027 // fall through and open the fallback ringtone below
1028 }
1029 }
1030
1031 try {
1032 return super.openAssetFile(soundUri, mode);
1033 } catch (FileNotFoundException ex) {
1034 // Since a non-null Uri was specified, but couldn't be opened,
1035 // fall back to the built-in ringtone.
1036 return context.getResources().openRawResourceFd(
1037 com.android.internal.R.raw.fallbackring);
1038 }
1039 }
1040 // no need to fall through and have openFile() try again, since we
1041 // already know that will fail.
1042 throw new FileNotFoundException(); // or return null ?
1043 }
1044
1045 // Note that this will end up calling openFile() above.
1046 return super.openAssetFile(uri, mode);
1047 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001048
1049 /**
1050 * In-memory LRU Cache of system and secure settings, along with
1051 * associated helper functions to keep cache coherent with the
1052 * database.
1053 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001054 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001055
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001056 private final String mCacheName;
1057 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1058
1059 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001060 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001061 mCacheName = name;
1062 }
1063
1064 /**
1065 * Is the whole database table slurped into this cache?
1066 */
1067 public boolean fullyMatchesDisk() {
1068 synchronized (this) {
1069 return mCacheFullyMatchesDisk;
1070 }
1071 }
1072
1073 public void setFullyMatchesDisk(boolean value) {
1074 synchronized (this) {
1075 mCacheFullyMatchesDisk = value;
1076 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001077 }
1078
1079 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001080 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1081 if (evicted) {
1082 mCacheFullyMatchesDisk = false;
1083 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001084 }
1085
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001086 /**
1087 * Atomic cache population, conditional on size of value and if
1088 * we lost a race.
1089 *
1090 * @returns a Bundle to send back to the client from call(), even
1091 * if we lost the race.
1092 */
1093 public Bundle putIfAbsent(String key, String value) {
1094 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1095 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1096 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001097 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001098 put(key, bundle);
1099 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001100 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001101 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001102 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001103 }
1104
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001105 /**
1106 * Populates a key in a given (possibly-null) cache.
1107 */
1108 public static void populate(SettingsCache cache, ContentValues contentValues) {
1109 if (cache == null) {
1110 return;
1111 }
1112 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1113 if (name == null) {
1114 Log.w(TAG, "null name populating settings cache.");
1115 return;
1116 }
1117 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001118 cache.populate(name, value);
1119 }
1120
1121 public void populate(String name, String value) {
1122 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001123 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001124 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001125 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001126 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001127 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001128 }
1129 }
1130
1131 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001132 * For suppressing duplicate/redundant settings inserts early,
1133 * checking our cache first (but without faulting it in),
1134 * before going to sqlite with the mutation.
1135 */
1136 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1137 if (cache == null) return false;
1138 synchronized (cache) {
1139 Bundle bundle = cache.get(name);
1140 if (bundle == null) return false;
1141 String oldValue = bundle.getPairValue();
1142 if (oldValue == null && value == null) return true;
1143 if ((oldValue == null) != (value == null)) return false;
1144 return oldValue.equals(value);
1145 }
1146 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001147 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001148}