blob: 67539222e0da751731e47bcd61acbab1d7ef4a8e [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
-b master501eec92009-07-06 13:53:11 -070019import java.io.FileNotFoundException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080020import java.security.SecureRandom;
Christopher Tate06efb532012-08-24 15:29:27 -070021import java.util.HashSet;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070022import java.util.concurrent.atomic.AtomicBoolean;
23import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070024
Christopher Tated5fe1472012-09-10 15:48:38 -070025import android.app.ActivityManager;
Dianne Hackborn961321f2013-02-05 17:22:41 -080026import android.app.AppOpsManager;
Christopher Tate45281862010-03-05 15:46:30 -080027import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029import android.content.ContentProvider;
30import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070033import android.content.Intent;
34import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Marco Nelissen69f593c2009-07-28 09:55:04 -070036import android.content.res.AssetFileDescriptor;
Christopher Tateafccaa82012-10-03 17:41:51 -070037import android.database.AbstractCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080040import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.sqlite.SQLiteQueryBuilder;
42import android.media.RingtoneManager;
43import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070044import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070046import android.os.DropBoxManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070047import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.os.ParcelFileDescriptor;
49import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070050import android.os.UserHandle;
51import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.provider.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;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700110
111 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
112
Christopher Tate06efb532012-08-24 15:29:27 -0700113 static {
114 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
115 // table, shared across all users
116 // These must match Settings.Secure.MOVED_TO_GLOBAL
117 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700118 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700119
120 // Keys from the 'system' table now moved to 'global'
121 // These must match Settings.System.MOVED_TO_GLOBAL
122 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700123 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700124 }
125
126 private boolean settingMovedToGlobal(final String name) {
127 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
128 }
129
130 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700131 * Decode a content URL into the table, projection, and arguments
132 * used to access the corresponding database rows.
133 */
134 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700136 public final String where;
137 public final String[] args;
138
139 /** Operate on existing rows. */
140 SqlArguments(Uri url, String where, String[] args) {
141 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700142 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700144 if (!DatabaseHelper.isValidTable(this.table)) {
145 throw new IllegalArgumentException("Bad root path: " + this.table);
146 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700147 this.where = where;
148 this.args = args;
149 } else if (url.getPathSegments().size() != 2) {
150 throw new IllegalArgumentException("Invalid URI: " + url);
151 } else if (!TextUtils.isEmpty(where)) {
152 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
153 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700154 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700155 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700156 if (!DatabaseHelper.isValidTable(this.table)) {
157 throw new IllegalArgumentException("Bad root path: " + this.table);
158 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700159 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
160 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700161 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700162 final String name = url.getPathSegments().get(1);
163 this.args = new String[] { name };
164 // Rewrite the table for known-migrated names
165 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
166 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
167 this.table = TABLE_GLOBAL;
168 }
169 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700170 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700171 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172 this.where = "_id=" + ContentUris.parseId(url);
173 this.args = null;
174 }
175 }
176 }
177
178 /** Insert new rows (no where clause allowed). */
179 SqlArguments(Uri url) {
180 if (url.getPathSegments().size() == 1) {
181 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700182 if (!DatabaseHelper.isValidTable(this.table)) {
183 throw new IllegalArgumentException("Bad root path: " + this.table);
184 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700185 this.where = null;
186 this.args = null;
187 } else {
188 throw new IllegalArgumentException("Invalid URI: " + url);
189 }
190 }
191 }
192
193 /**
194 * Get the content URI of a row added to a table.
195 * @param tableUri of the entire table
196 * @param values found in the row
197 * @param rowId of the row
198 * @return the content URI for this particular row
199 */
200 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
201 if (tableUri.getPathSegments().size() != 1) {
202 throw new IllegalArgumentException("Invalid URI: " + tableUri);
203 }
204 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700205 if (TABLE_SYSTEM.equals(table) ||
206 TABLE_SECURE.equals(table) ||
207 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700208 String name = values.getAsString(Settings.NameValueTable.NAME);
209 return Uri.withAppendedPath(tableUri, name);
210 } else {
211 return ContentUris.withAppendedId(tableUri, rowId);
212 }
213 }
214
215 /**
216 * Send a notification when a particular content URI changes.
217 * Modify the system property used to communicate the version of
218 * this table, for tables which have such a property. (The Settings
219 * contract class uses these to provide client-side caches.)
220 * @param uri to send notifications for
221 */
Christopher Tate06efb532012-08-24 15:29:27 -0700222 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700223 // Update the system property *first*, so if someone is listening for
224 // a notification and then using the contract class to get their data,
225 // the system property will be updated and they'll get the new data.
226
Amith Yamasanid1582142009-07-08 20:04:55 -0700227 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700228 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700229 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700230 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700231 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700232 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700233 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700234 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700235 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700236 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700237 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700238 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700239 }
240
241 if (property != null) {
242 long version = SystemProperties.getLong(property, 0) + 1;
243 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
244 SystemProperties.set(property, Long.toString(version));
245 }
246
-b master501eec92009-07-06 13:53:11 -0700247 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700248 if (backedUpDataChanged) {
249 mBackupManager.dataChanged();
250 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700251 // Now send the notification through the content framework.
252
253 String notify = uri.getQueryParameter("notify");
254 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700255 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700256 final long oldId = Binder.clearCallingIdentity();
257 try {
258 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
259 } finally {
260 Binder.restoreCallingIdentity(oldId);
261 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700262 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700263 } else {
264 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
265 }
266 }
267
268 /**
269 * Make sure the caller has permission to write this data.
270 * @param args supplied by the caller
271 * @throws SecurityException if the caller is forbidden to write.
272 */
273 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700274 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800275 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800276 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
277 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700278 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800279 String.format("Permission denial: writing to secure settings requires %1$s",
280 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700281 }
282 }
283
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700284 // FileObserver for external modifications to the database file.
285 // Note that this is for platform developers only with
286 // userdebug/eng builds who should be able to tinker with the
287 // sqlite database out from under the SettingsProvider, which is
288 // normally the exclusive owner of the database. But we keep this
289 // enabled all the time to minimize development-vs-user
290 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700291 private static SparseArray<SettingsFileObserver> sObserverInstances
292 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700293 private class SettingsFileObserver extends FileObserver {
294 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700295 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700296 private final String mPath;
297
Christopher Tate06efb532012-08-24 15:29:27 -0700298 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700299 super(path, FileObserver.CLOSE_WRITE |
300 FileObserver.CREATE | FileObserver.DELETE |
301 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700302 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700303 mPath = path;
304 }
305
306 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700307 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700308 if (modsInFlight > 0) {
309 // our own modification.
310 return;
311 }
Christopher Tate06efb532012-08-24 15:29:27 -0700312 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
313 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700314 if (!mIsDirty.compareAndSet(false, true)) {
315 // already handled. (we get a few update events
316 // during an sqlite write)
317 return;
318 }
Christopher Tate06efb532012-08-24 15:29:27 -0700319 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
320 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700321 mIsDirty.set(false);
322 }
323 }
324
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700325 @Override
326 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700327 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700328 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800329
Dianne Hackborn961321f2013-02-05 17:22:41 -0800330 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700331 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700332
Christopher Tate78d2a662012-09-13 16:19:44 -0700333 IntentFilter userFilter = new IntentFilter();
334 userFilter.addAction(Intent.ACTION_USER_REMOVED);
335 getContext().registerReceiver(new BroadcastReceiver() {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
339 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
340 UserHandle.USER_OWNER);
341 if (userHandle != UserHandle.USER_OWNER) {
342 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700343 }
344 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700345 }
346 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700347 return true;
348 }
349
Christopher Tate06efb532012-08-24 15:29:27 -0700350 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700351 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700352 // the db file itself will be deleted automatically, but we need to tear down
353 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700354 FileObserver observer = sObserverInstances.get(userHandle);
355 if (observer != null) {
356 observer.stopWatching();
357 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700358 }
Christopher Tate06efb532012-08-24 15:29:27 -0700359
360 mOpenHelpers.delete(userHandle);
361 sSystemCaches.delete(userHandle);
362 sSecureCaches.delete(userHandle);
363 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700364 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700365 }
366
Christopher Tate78d2a662012-09-13 16:19:44 -0700367 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700368 if (LOCAL_LOGV) {
369 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
370 }
371
Christopher Tate78d2a662012-09-13 16:19:44 -0700372 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700373
Christopher Tate78d2a662012-09-13 16:19:44 -0700374 synchronized (this) {
375 dbhelper = mOpenHelpers.get(userHandle);
376 if (dbhelper == null) {
377 dbhelper = new DatabaseHelper(getContext(), userHandle);
378 mOpenHelpers.append(userHandle, dbhelper);
379
380 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
381 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
382 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
383 }
384 }
385
386 // Initialization of the db *outside* the locks. It's possible that racing
387 // threads might wind up here, the second having read the cache entries
388 // written by the first, but that's benign: the SQLite helper implementation
389 // manages concurrency itself, and it's important that we not run the db
390 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700391 SQLiteDatabase db = dbhelper.getWritableDatabase();
392
Christopher Tate78d2a662012-09-13 16:19:44 -0700393 // Watch for external modifications to the database files,
394 // keeping our caches in sync. We synchronize the observer set
395 // separately, and of course it has to run after the db file
396 // itself was set up by the DatabaseHelper.
397 synchronized (sObserverInstances) {
398 if (sObserverInstances.get(userHandle) == null) {
399 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
400 sObserverInstances.append(userHandle, observer);
401 observer.startWatching();
402 }
403 }
Christopher Tate06efb532012-08-24 15:29:27 -0700404
Christopher Tate4dc7a682012-09-11 12:15:49 -0700405 ensureAndroidIdIsSet(userHandle);
406
Christopher Tate06efb532012-08-24 15:29:27 -0700407 startAsyncCachePopulation(userHandle);
408 }
409
410 class CachePrefetchThread extends Thread {
411 private int mUserHandle;
412
413 CachePrefetchThread(int userHandle) {
414 super("populate-settings-caches");
415 mUserHandle = userHandle;
416 }
417
418 @Override
419 public void run() {
420 fullyPopulateCaches(mUserHandle);
421 }
422 }
423
424 private void startAsyncCachePopulation(int userHandle) {
425 new CachePrefetchThread(userHandle).start();
426 }
427
428 private void fullyPopulateCaches(final int userHandle) {
429 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
430 // Only populate the globals cache once, for the owning user
431 if (userHandle == UserHandle.USER_OWNER) {
432 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
433 }
434 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
435 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700436 }
437
438 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700439 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
440 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700441 Cursor c = db.query(
442 table,
443 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
444 null, null, null, null, null,
445 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
446 try {
447 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800448 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700449 cache.setFullyMatchesDisk(true); // optimistic
450 int rows = 0;
451 while (c.moveToNext()) {
452 rows++;
453 String name = c.getString(0);
454 String value = c.getString(1);
455 cache.populate(name, value);
456 }
457 if (rows > MAX_CACHE_ENTRIES) {
458 // Somewhat redundant, as removeEldestEntry() will
459 // have already done this, but to be explicit:
460 cache.setFullyMatchesDisk(false);
461 Log.d(TAG, "row count exceeds max cache entries for table " + table);
462 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800463 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
464 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700465 }
466 } finally {
467 c.close();
468 }
469 }
470
Christopher Tate4dc7a682012-09-11 12:15:49 -0700471 private boolean ensureAndroidIdIsSet(int userHandle) {
472 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800473 new String[] { Settings.NameValueTable.VALUE },
474 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700475 new String[] { Settings.Secure.ANDROID_ID }, null,
476 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800477 try {
478 final String value = c.moveToNext() ? c.getString(0) : null;
479 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700480 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800481 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800482 final ContentValues values = new ContentValues();
483 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
484 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700485 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800486 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700487 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800488 return false;
489 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700490 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
491 + "] for user " + userHandle);
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700492 // Write a dropbox entry if it's a restricted profile
493 if (mUserManager.getUserInfo(userHandle).isRestricted()) {
494 DropBoxManager dbm = (DropBoxManager)
495 getContext().getSystemService(Context.DROPBOX_SERVICE);
496 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
497 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
498 + ",restricted_profile_ssaid,"
499 + newAndroidIdValue + "\n");
500 }
501 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800502 }
503 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800504 } finally {
505 c.close();
506 }
507 }
508
Christopher Tate06efb532012-08-24 15:29:27 -0700509 // Lazy-initialize the settings caches for non-primary users
510 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700511 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
512 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700513 }
514
515 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700516 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700517 long oldId = Binder.clearCallingIdentity();
518 try {
519 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
520 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700521 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700522 dbHelper = mOpenHelpers.get(callingUser);
523 }
524 return dbHelper;
525 } finally {
526 Binder.restoreCallingIdentity(oldId);
527 }
528 }
529
530 public SettingsCache cacheForTable(final int callingUser, String tableName) {
531 if (TABLE_SYSTEM.equals(tableName)) {
532 return getOrConstructCache(callingUser, sSystemCaches);
533 }
534 if (TABLE_SECURE.equals(tableName)) {
535 return getOrConstructCache(callingUser, sSecureCaches);
536 }
537 if (TABLE_GLOBAL.equals(tableName)) {
538 return sGlobalCache;
539 }
540 return null;
541 }
542
543 /**
544 * Used for wiping a whole cache on deletes when we're not
545 * sure what exactly was deleted or changed.
546 */
547 public void invalidateCache(final int callingUser, String tableName) {
548 SettingsCache cache = cacheForTable(callingUser, tableName);
549 if (cache == null) {
550 return;
551 }
552 synchronized (cache) {
553 cache.evictAll();
554 cache.mCacheFullyMatchesDisk = false;
555 }
556 }
557
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800558 /**
559 * Fast path that avoids the use of chatty remoted Cursors.
560 */
561 @Override
Dianne Hackborn961321f2013-02-05 17:22:41 -0800562 public Bundle callFromPackage(String callingPackage, String method, String request,
563 Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700564 int callingUser = UserHandle.getCallingUserId();
565 if (args != null) {
566 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
567 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700568 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
569 Binder.getCallingUid(), reqUser, false, true,
570 "get/set setting for user", null);
571 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700572 }
573 }
574
Christopher Tate61695ff2012-10-05 12:05:13 -0700575 // Note: we assume that get/put operations for moved-to-global names have already
576 // been directed to the new location on the caller side (otherwise we'd fix them
577 // up here).
578 DatabaseHelper dbHelper;
579 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700580
Christopher Tate61695ff2012-10-05 12:05:13 -0700581 // Get methods
582 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
583 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
584 dbHelper = getOrEstablishDatabase(callingUser);
585 cache = sSystemCaches.get(callingUser);
586 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
587 }
588 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
589 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
590 dbHelper = getOrEstablishDatabase(callingUser);
591 cache = sSecureCaches.get(callingUser);
592 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
593 }
594 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
595 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
596 // fast path: owner db & cache are immutable after onCreate() so we need not
597 // guard on the attempt to look them up
598 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
599 sGlobalCache, request);
600 }
Christopher Tate06efb532012-08-24 15:29:27 -0700601
Christopher Tate61695ff2012-10-05 12:05:13 -0700602 // Put methods - new value is in the args bundle under the key named by
603 // the Settings.NameValueTable.VALUE static.
604 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800605 ? null : args.getString(Settings.NameValueTable.VALUE);
606
607 // Framework can't do automatic permission checking for calls, so we need
608 // to do it here.
609 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
610 != PackageManager.PERMISSION_GRANTED) {
611 throw new SecurityException(
612 String.format("Permission denial: writing to settings requires %1$s",
613 android.Manifest.permission.WRITE_SETTINGS));
614 }
615
616 // Also need to take care of app op.
617 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
618 callingPackage) != AppOpsManager.MODE_ALLOWED) {
619 return null;
620 }
Christopher Tate06efb532012-08-24 15:29:27 -0700621
Christopher Tate61695ff2012-10-05 12:05:13 -0700622 final ContentValues values = new ContentValues();
623 values.put(Settings.NameValueTable.NAME, request);
624 values.put(Settings.NameValueTable.VALUE, newValue);
625 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
626 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
627 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
628 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
629 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
630 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
631 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
632 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
633 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
634 } else {
635 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700636 }
637
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800638 return null;
639 }
640
641 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
642 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700643 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
644 final SettingsCache cache, String key) {
645 if (cache == null) {
646 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
647 return null;
648 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800649 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800650 Bundle value = cache.get(key);
651 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700652 if (value != TOO_LARGE_TO_CACHE_MARKER) {
653 return value;
654 }
655 // else we fall through and read the value from disk
656 } else if (cache.fullyMatchesDisk()) {
657 // Fast path (very common). Don't even try touch disk
658 // if we know we've slurped it all in. Trying to
659 // touch the disk would mean waiting for yaffs2 to
660 // give us access, which could takes hundreds of
661 // milliseconds. And we're very likely being called
662 // from somebody's UI thread...
663 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800664 }
665 }
666
Christopher Tate06efb532012-08-24 15:29:27 -0700667 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800668 Cursor cursor = null;
669 try {
670 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
671 null, null, null, null);
672 if (cursor != null && cursor.getCount() == 1) {
673 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800674 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800675 }
676 } catch (SQLiteException e) {
677 Log.w(TAG, "settings lookup error", e);
678 return null;
679 } finally {
680 if (cursor != null) cursor.close();
681 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800682 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800683 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800684 }
685
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700686 @Override
687 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700688 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
689 }
690
Christopher Tateb7564452012-09-19 16:21:18 -0700691 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700692 String sort, int forUser) {
693 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700694 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700695 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700696 dbH = getOrEstablishDatabase(
697 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700698 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800700 // The favorites table was moved from this provider to a provider inside Home
701 // Home still need to query this table to upgrade from pre-cupcake builds
702 // However, a cupcake+ build with no data does not contain this table which will
703 // cause an exception in the SQL stack. The following line is a special case to
704 // 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 -0800705 if (TABLE_FAVORITES.equals(args.table)) {
706 return null;
707 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
708 args.table = TABLE_FAVORITES;
709 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
710 if (cursor != null) {
711 boolean exists = cursor.getCount() > 0;
712 cursor.close();
713 if (!exists) return null;
714 } else {
715 return null;
716 }
717 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800718
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700719 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
720 qb.setTables(args.table);
721
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700722 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700723 // the default Cursor interface does not support per-user observation
724 try {
725 AbstractCursor c = (AbstractCursor) ret;
726 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
727 } catch (ClassCastException e) {
728 // details of the concrete Cursor implementation have changed and this code has
729 // not been updated to match -- complain and fail hard.
730 Log.wtf(TAG, "Incompatible cursor derivation!");
731 throw e;
732 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700733 return ret;
734 }
735
736 @Override
737 public String getType(Uri url) {
738 // If SqlArguments supplies a where clause, then it must be an item
739 // (because we aren't supplying our own where clause).
740 SqlArguments args = new SqlArguments(url, null, null);
741 if (TextUtils.isEmpty(args.where)) {
742 return "vnd.android.cursor.dir/" + args.table;
743 } else {
744 return "vnd.android.cursor.item/" + args.table;
745 }
746 }
747
748 @Override
749 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700750 final int callingUser = UserHandle.getCallingUserId();
751 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700752 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 if (TABLE_FAVORITES.equals(args.table)) {
754 return 0;
755 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700756 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700757 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700758
Christopher Tate06efb532012-08-24 15:29:27 -0700759 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
760 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700761 DatabaseHelper dbH = getOrEstablishDatabase(
762 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700763 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700764 db.beginTransaction();
765 try {
766 int numValues = values.length;
767 for (int i = 0; i < numValues; i++) {
768 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800769 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700770 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
771 }
772 db.setTransactionSuccessful();
773 } finally {
774 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700775 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700776 }
777
Christopher Tate06efb532012-08-24 15:29:27 -0700778 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700779 return values.length;
780 }
781
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700782 /*
783 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
784 * This setting contains a list of the currently enabled location providers.
785 * But helper functions in android.providers.Settings can enable or disable
786 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800787 *
788 * @returns whether the database needs to be updated or not, also modifying
789 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700790 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500791 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700792 String value = initialValues.getAsString(Settings.Secure.VALUE);
793 String newProviders = null;
794 if (value != null && value.length() > 1) {
795 char prefix = value.charAt(0);
796 if (prefix == '+' || prefix == '-') {
797 // skip prefix
798 value = value.substring(1);
799
800 // read list of enabled providers into "providers"
801 String providers = "";
802 String[] columns = {Settings.Secure.VALUE};
803 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -0500804 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700805 if (cursor != null && cursor.getCount() == 1) {
806 try {
807 cursor.moveToFirst();
808 providers = cursor.getString(0);
809 } finally {
810 cursor.close();
811 }
812 }
813
814 int index = providers.indexOf(value);
815 int end = index + value.length();
816 // check for commas to avoid matching on partial string
817 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
818 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
819
820 if (prefix == '+' && index < 0) {
821 // append the provider to the list if not present
822 if (providers.length() == 0) {
823 newProviders = value;
824 } else {
825 newProviders = providers + ',' + value;
826 }
827 } else if (prefix == '-' && index >= 0) {
828 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400829 // remove leading or trailing comma
830 if (index > 0) {
831 index--;
832 } else if (end < providers.length()) {
833 end++;
834 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700835
836 newProviders = providers.substring(0, index);
837 if (end < providers.length()) {
838 newProviders += providers.substring(end);
839 }
840 } else {
841 // nothing changed, so no need to update the database
842 return false;
843 }
844
845 if (newProviders != null) {
846 initialValues.put(Settings.Secure.VALUE, newProviders);
847 }
848 }
849 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800850
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700851 return true;
852 }
853
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700854 @Override
855 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700856 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
857 }
858
859 // Settings.put*ForUser() always winds up here, so this is where we apply
860 // policy around permission to write settings for other users.
861 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
862 final int callingUser = UserHandle.getCallingUserId();
863 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700864 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700865 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
866 "Not permitted to access settings for other users");
867 }
868
869 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
870 + " by " + callingUser);
871
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700872 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 if (TABLE_FAVORITES.equals(args.table)) {
874 return null;
875 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700876
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700877 // Special case LOCATION_PROVIDERS_ALLOWED.
878 // Support enabling/disabling a single provider (using "+" or "-" prefix)
879 String name = initialValues.getAsString(Settings.Secure.NAME);
880 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -0500881 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700882 }
883
Christopher Tatec221d2b2012-10-03 18:33:52 -0700884 // If this is an insert() of a key that has been migrated to the global store,
885 // redirect the operation to that store
886 if (name != null) {
887 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
888 if (!TABLE_GLOBAL.equals(args.table)) {
889 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
890 }
891 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
892 }
893 }
894
Christopher Tate34637e52012-10-04 15:00:00 -0700895 // Check write permissions only after determining which table the insert will touch
896 checkWritePermissions(args);
897
Christopher Tate06efb532012-08-24 15:29:27 -0700898 // The global table is stored under the owner, always
899 if (TABLE_GLOBAL.equals(args.table)) {
900 desiredUserHandle = UserHandle.USER_OWNER;
901 }
902
903 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800904 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
905 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
906 return Uri.withAppendedPath(url, name);
907 }
908
Christopher Tate06efb532012-08-24 15:29:27 -0700909 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
910 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700911 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700912 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700913 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700914 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700915 if (rowId <= 0) return null;
916
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800917 SettingsCache.populate(cache, initialValues); // before we notify
918
Christopher Tate78d2a662012-09-13 16:19:44 -0700919 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
920 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700921 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700922 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700923 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700924 return url;
925 }
926
927 @Override
928 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700929 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700930 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700931 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 if (TABLE_FAVORITES.equals(args.table)) {
933 return 0;
934 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
935 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700936 } else if (TABLE_GLOBAL.equals(args.table)) {
937 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700939 checkWritePermissions(args);
940
Christopher Tate06efb532012-08-24 15:29:27 -0700941 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
942 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700943 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700944 SQLiteDatabase db = dbH.getWritableDatabase();
945 int count = db.delete(args.table, args.where, args.args);
946 mutationCount.decrementAndGet();
947 if (count > 0) {
948 invalidateCache(callingUser, args.table); // before we notify
949 sendNotify(url, callingUser);
950 }
951 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700952 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
953 return count;
954 }
955
956 @Override
957 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700958 // NOTE: update() is never called by the front-end Settings API, and updates that
959 // wind up affecting rows in Secure that are globally shared will not have the
960 // intended effect (the update will be invisible to the rest of the system).
961 // This should have no practical effect, since writes to the Secure db can only
962 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -0700963 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700964 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 if (TABLE_FAVORITES.equals(args.table)) {
967 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700968 } else if (TABLE_GLOBAL.equals(args.table)) {
969 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700971 checkWritePermissions(args);
972
Christopher Tate06efb532012-08-24 15:29:27 -0700973 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
974 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700975 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700976 SQLiteDatabase db = dbH.getWritableDatabase();
977 int count = db.update(args.table, initialValues, args.where, args.args);
978 mutationCount.decrementAndGet();
979 if (count > 0) {
980 invalidateCache(callingUser, args.table); // before we notify
981 sendNotify(url, callingUser);
982 }
983 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700984 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
985 return count;
986 }
987
988 @Override
989 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
990
991 /*
992 * When a client attempts to openFile the default ringtone or
993 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -0700994 * default ringtone's Uri (if it is in the media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700995 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700996 int ringtoneType = RingtoneManager.getDefaultType(uri);
997 // Above call returns -1 if the Uri doesn't match a default type
998 if (ringtoneType != -1) {
999 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001000
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001001 // Get the current value for the default sound
1002 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001003
Marco Nelissen69f593c2009-07-28 09:55:04 -07001004 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001005 // Proxy the openFile call to media provider
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001006 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001007 if (authority.equals(MediaStore.AUTHORITY)) {
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
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001022 * default ringtone's Uri (if it is in the media provider).
Marco Nelissen69f593c2009-07-28 09:55:04 -07001023 */
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) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001033 // Proxy the openFile call to media provider
Marco Nelissen69f593c2009-07-28 09:55:04 -07001034 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001035 if (authority.equals(MediaStore.AUTHORITY)) {
Marco Nelissen69f593c2009-07-28 09:55:04 -07001036 ParcelFileDescriptor pfd = null;
1037 try {
1038 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1039 return new AssetFileDescriptor(pfd, 0, -1);
1040 } catch (FileNotFoundException ex) {
1041 // fall through and open the fallback ringtone below
1042 }
1043 }
1044
1045 try {
1046 return super.openAssetFile(soundUri, mode);
1047 } catch (FileNotFoundException ex) {
1048 // Since a non-null Uri was specified, but couldn't be opened,
1049 // fall back to the built-in ringtone.
1050 return context.getResources().openRawResourceFd(
1051 com.android.internal.R.raw.fallbackring);
1052 }
1053 }
1054 // no need to fall through and have openFile() try again, since we
1055 // already know that will fail.
1056 throw new FileNotFoundException(); // or return null ?
1057 }
1058
1059 // Note that this will end up calling openFile() above.
1060 return super.openAssetFile(uri, mode);
1061 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001062
1063 /**
1064 * In-memory LRU Cache of system and secure settings, along with
1065 * associated helper functions to keep cache coherent with the
1066 * database.
1067 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001068 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001069
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001070 private final String mCacheName;
1071 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1072
1073 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001074 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001075 mCacheName = name;
1076 }
1077
1078 /**
1079 * Is the whole database table slurped into this cache?
1080 */
1081 public boolean fullyMatchesDisk() {
1082 synchronized (this) {
1083 return mCacheFullyMatchesDisk;
1084 }
1085 }
1086
1087 public void setFullyMatchesDisk(boolean value) {
1088 synchronized (this) {
1089 mCacheFullyMatchesDisk = value;
1090 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001091 }
1092
1093 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001094 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1095 if (evicted) {
1096 mCacheFullyMatchesDisk = false;
1097 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001098 }
1099
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001100 /**
1101 * Atomic cache population, conditional on size of value and if
1102 * we lost a race.
1103 *
1104 * @returns a Bundle to send back to the client from call(), even
1105 * if we lost the race.
1106 */
1107 public Bundle putIfAbsent(String key, String value) {
1108 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1109 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1110 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001111 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001112 put(key, bundle);
1113 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001114 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001115 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001116 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001117 }
1118
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001119 /**
1120 * Populates a key in a given (possibly-null) cache.
1121 */
1122 public static void populate(SettingsCache cache, ContentValues contentValues) {
1123 if (cache == null) {
1124 return;
1125 }
1126 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1127 if (name == null) {
1128 Log.w(TAG, "null name populating settings cache.");
1129 return;
1130 }
1131 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001132 cache.populate(name, value);
1133 }
1134
1135 public void populate(String name, String value) {
1136 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001137 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001138 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001139 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001140 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001141 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001142 }
1143 }
1144
1145 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001146 * For suppressing duplicate/redundant settings inserts early,
1147 * checking our cache first (but without faulting it in),
1148 * before going to sqlite with the mutation.
1149 */
1150 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1151 if (cache == null) return false;
1152 synchronized (cache) {
1153 Bundle bundle = cache.get(name);
1154 if (bundle == null) return false;
1155 String oldValue = bundle.getPairValue();
1156 if (oldValue == null && value == null) return true;
1157 if ((oldValue == null) != (value == null)) return false;
1158 return oldValue.equals(value);
1159 }
1160 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001161 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001162}